@floydous/pi-agent-kernel 0.4.3 → 0.5.0
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/AGENT_KERNEL_SYS_PROMPT.md +1 -7
- package/CHANGELOG.md +36 -0
- package/README.md +6 -53
- package/config.example.toml +0 -8
- package/docs/README.md +1 -2
- package/docs/architecture.md +2 -3
- package/docs/configuration.md +10 -9
- package/docs/editing-and-verification.md +1 -3
- package/docs/retrieval.md +6 -11
- package/docs/testing.md +3 -3
- package/package.json +4 -2
- package/src/config/agent_kernel_command.ts +8 -39
- package/src/config/kernel_config.ts +30 -68
- package/src/config/toml.ts +6 -1
- package/src/editing/auto_heal.ts +1 -1
- package/src/editing/patch.ts +27 -16
- package/src/editing/post_edit_verification.ts +12 -10
- package/src/editing/smart_anchor.ts +7 -5
- package/src/editing/syntax-verify.ts +9 -5
- package/src/index.ts +15 -257
- package/src/retrieval/search_bm25.ts +4 -2
- package/src/retrieval/search_chunker.ts +1 -1
- package/src/retrieval/search_config.ts +4 -6
- package/src/retrieval/search_embedder.ts +3 -2
- package/src/retrieval/search_index.ts +82 -35
- package/src/retrieval/search_modal.ts +7 -8
- package/src/retrieval/{repomap.ts → tag_extractor.ts} +5 -292
- package/src/retrieval/tree_sitter_engine.ts +70 -34
- package/src/retrieval/workspace_walker.ts +6 -2
- package/src/safety/atomic_write.ts +1 -1
- package/src/safety/epistemic_guard.ts +105 -31
- package/src/safety/output_clamper.ts +14 -8
- package/src/tools/code_search_output.ts +2 -1
- package/src/tools/code_search_tool.ts +2 -5
- package/src/tools/context.ts +0 -14
- package/src/tools/edit_tool.ts +82 -115
- package/src/tools/read_tool.ts +42 -178
- package/src/ui/footer.ts +7 -7
- package/docs/lsp.md +0 -31
- package/src/lsp/adapters/base.ts +0 -42
- package/src/lsp/adapters/index.ts +0 -21
- package/src/lsp/adapters/python.ts +0 -37
- package/src/lsp/adapters/rust.ts +0 -35
- package/src/lsp/adapters/typescript.ts +0 -40
- package/src/lsp/index.ts +0 -13
- package/src/lsp/lsp_client.ts +0 -765
- package/src/lsp/lsp_detector.ts +0 -52
- package/src/lsp/lsp_formatter.ts +0 -323
- package/src/lsp/lsp_installer.ts +0 -320
- package/src/lsp/lsp_manager.ts +0 -202
- package/src/lsp/lsp_modal.ts +0 -675
- package/src/lsp/lsp_registry.ts +0 -600
- package/src/lsp/lsp_types.ts +0 -143
- package/src/retrieval/ast_search.ts +0 -999
- package/src/retrieval/symbol_reader.ts +0 -228
- package/src/tools/ast_search_formatter.ts +0 -161
- package/src/tools/ast_search_tool.ts +0 -146
- package/src/tools/lsp_tool.ts +0 -794
- package/src/tools/repo_map_tool.ts +0 -56
package/src/lsp/lsp_client.ts
DELETED
|
@@ -1,765 +0,0 @@
|
|
|
1
|
-
import crossSpawn from "cross-spawn";
|
|
2
|
-
import { type ChildProcess } from "node:child_process";
|
|
3
|
-
import * as fs from "node:fs";
|
|
4
|
-
import * as path from "node:path";
|
|
5
|
-
import {
|
|
6
|
-
type LspRequest,
|
|
7
|
-
type LspNotification,
|
|
8
|
-
type LspClientState,
|
|
9
|
-
type LspDiagnostic,
|
|
10
|
-
type LspLocation,
|
|
11
|
-
type LspHover,
|
|
12
|
-
type LspDocumentSymbol,
|
|
13
|
-
type LspSymbolInformation,
|
|
14
|
-
} from "./lsp_types";
|
|
15
|
-
import { pathToUri, normalizeUri, normalizeLocations } from "./lsp_formatter";
|
|
16
|
-
import { getLspAdapter, type LspAdapter } from "./adapters";
|
|
17
|
-
import { kernelDebug } from "../safety/kernel_debug";
|
|
18
|
-
import { loadKernelConfig } from "../config";
|
|
19
|
-
|
|
20
|
-
const LSP_ENV_ALLOWLIST = new Set([
|
|
21
|
-
"path",
|
|
22
|
-
"pathext",
|
|
23
|
-
"home",
|
|
24
|
-
"userprofile",
|
|
25
|
-
"homedrive",
|
|
26
|
-
"homepath",
|
|
27
|
-
"temp",
|
|
28
|
-
"tmp",
|
|
29
|
-
"tmpdir",
|
|
30
|
-
"systemroot",
|
|
31
|
-
"windir",
|
|
32
|
-
"comspec",
|
|
33
|
-
"appdata",
|
|
34
|
-
"localappdata",
|
|
35
|
-
"programdata",
|
|
36
|
-
"programfiles",
|
|
37
|
-
"programfiles(x86)",
|
|
38
|
-
"lang",
|
|
39
|
-
"lc_all",
|
|
40
|
-
"java_home",
|
|
41
|
-
"jdk_home",
|
|
42
|
-
"goroot",
|
|
43
|
-
"gopath",
|
|
44
|
-
"cargo_home",
|
|
45
|
-
"rustup_home",
|
|
46
|
-
"pythonhome",
|
|
47
|
-
"pythonpath",
|
|
48
|
-
"virtual_env",
|
|
49
|
-
"node_path",
|
|
50
|
-
"ld_library_path",
|
|
51
|
-
]);
|
|
52
|
-
|
|
53
|
-
export function buildLspEnvironment(
|
|
54
|
-
overrides: Record<string, string> = {},
|
|
55
|
-
): Record<string, string> {
|
|
56
|
-
const source = new Map<string, { key: string; value: string }>();
|
|
57
|
-
for (const [key, value] of Object.entries(process.env)) {
|
|
58
|
-
if (typeof value === "string") source.set(key.toLowerCase(), { key, value });
|
|
59
|
-
}
|
|
60
|
-
const result: Record<string, string> = {};
|
|
61
|
-
for (const [lowerKey, entry] of source) {
|
|
62
|
-
if (LSP_ENV_ALLOWLIST.has(lowerKey)) result[entry.key] = entry.value;
|
|
63
|
-
}
|
|
64
|
-
for (const [key, value] of Object.entries(overrides)) {
|
|
65
|
-
if (LSP_ENV_ALLOWLIST.has(key.toLowerCase())) result[key] = value;
|
|
66
|
-
}
|
|
67
|
-
return result;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
export const MAX_LSP_STDERR_BYTES = 64 * 1024;
|
|
71
|
-
export const MAX_LSP_DOCUMENT_BYTES = 5 * 1024 * 1024;
|
|
72
|
-
export const MAX_LSP_DIAGNOSTICS = 200;
|
|
73
|
-
|
|
74
|
-
export interface StdioLspClientOptions {
|
|
75
|
-
command: string;
|
|
76
|
-
args: string[];
|
|
77
|
-
cwd: string;
|
|
78
|
-
languageId: string;
|
|
79
|
-
adapter?: LspAdapter;
|
|
80
|
-
env?: Record<string, string>;
|
|
81
|
-
idleTimeoutMs?: number;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
export class StdioLspClient {
|
|
85
|
-
public readonly id: string;
|
|
86
|
-
public readonly languageId: string;
|
|
87
|
-
public readonly rootDir: string;
|
|
88
|
-
private options: StdioLspClientOptions;
|
|
89
|
-
private adapter: LspAdapter;
|
|
90
|
-
|
|
91
|
-
private process: ChildProcess | null = null;
|
|
92
|
-
private state: LspClientState = "stopped";
|
|
93
|
-
private nextRequestId = 1;
|
|
94
|
-
private pendingRequests = new Map<
|
|
95
|
-
number | string,
|
|
96
|
-
{
|
|
97
|
-
resolve: (res: any) => void;
|
|
98
|
-
reject: (err: any) => void;
|
|
99
|
-
timer: NodeJS.Timeout;
|
|
100
|
-
}
|
|
101
|
-
>();
|
|
102
|
-
private buffer = Buffer.alloc(0);
|
|
103
|
-
private diagnosticsCache = new Map<string, LspDiagnostic[]>();
|
|
104
|
-
private diagnosticListeners = new Map<string, Array<(diags: LspDiagnostic[]) => void>>();
|
|
105
|
-
private openDocuments = new Map<string, { version: number; text: string }>();
|
|
106
|
-
private lastActivityTime = Date.now();
|
|
107
|
-
private serverCapabilities: any = {};
|
|
108
|
-
private static readonly MAX_HEADER_SIZE = 8192;
|
|
109
|
-
private static readonly MAX_BUFFER_SIZE = 50 * 1024 * 1024;
|
|
110
|
-
private static readonly MAX_CONTENT_LENGTH = 25 * 1024 * 1024;
|
|
111
|
-
|
|
112
|
-
constructor(id: string, options: StdioLspClientOptions) {
|
|
113
|
-
this.id = id;
|
|
114
|
-
this.languageId = options.languageId;
|
|
115
|
-
this.rootDir = options.cwd;
|
|
116
|
-
this.options = options;
|
|
117
|
-
this.adapter = options.adapter || getLspAdapter(options.languageId);
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
public getState(): LspClientState {
|
|
121
|
-
return this.state;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
public getLastActivity(): number {
|
|
125
|
-
return this.lastActivityTime;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
public touch(): void {
|
|
129
|
-
this.lastActivityTime = Date.now();
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
/**
|
|
133
|
-
* Start server process and perform two-phase LSP handshake (initialize -> initialized)
|
|
134
|
-
*/
|
|
135
|
-
public async start(): Promise<boolean> {
|
|
136
|
-
if (this.state === "ready" || this.state === "starting") return true;
|
|
137
|
-
|
|
138
|
-
this.state = "starting";
|
|
139
|
-
this.touch();
|
|
140
|
-
|
|
141
|
-
try {
|
|
142
|
-
this.process = crossSpawn(this.options.command, this.options.args, {
|
|
143
|
-
cwd: this.rootDir,
|
|
144
|
-
env: buildLspEnvironment(this.options.env),
|
|
145
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
146
|
-
shell: false,
|
|
147
|
-
windowsHide: true,
|
|
148
|
-
});
|
|
149
|
-
|
|
150
|
-
this.process.stdout?.on("data", (chunk: Buffer) => {
|
|
151
|
-
this.onData(chunk);
|
|
152
|
-
});
|
|
153
|
-
|
|
154
|
-
let serverStderr = "";
|
|
155
|
-
this.process.stderr?.on("data", (chunk: Buffer) => {
|
|
156
|
-
if (serverStderr.length < MAX_LSP_STDERR_BYTES) {
|
|
157
|
-
serverStderr = `${serverStderr}${chunk.toString("utf8")}`.slice(0, MAX_LSP_STDERR_BYTES);
|
|
158
|
-
}
|
|
159
|
-
});
|
|
160
|
-
|
|
161
|
-
this.process.on("error", (err) => {
|
|
162
|
-
this.state = "error";
|
|
163
|
-
});
|
|
164
|
-
|
|
165
|
-
this.process.on("exit", (code) => {
|
|
166
|
-
this.state = "stopped";
|
|
167
|
-
const trimmedErr = serverStderr.trim();
|
|
168
|
-
const exitMsg = trimmedErr
|
|
169
|
-
? `LSP server process exited (code ${code}): ${trimmedErr}`
|
|
170
|
-
: `LSP server process exited (code ${code})`;
|
|
171
|
-
this.cleanupPending(new Error(exitMsg));
|
|
172
|
-
});
|
|
173
|
-
|
|
174
|
-
// Handshake Phase 1: initialize
|
|
175
|
-
const rootUri = pathToUri(this.rootDir);
|
|
176
|
-
const customInitOpts = this.adapter.getInitializationOptions?.(this.rootDir) || {};
|
|
177
|
-
const customCaps = this.adapter.getClientCapabilities?.() || {};
|
|
178
|
-
|
|
179
|
-
const initResult = await this.sendRequest<any>(
|
|
180
|
-
"initialize",
|
|
181
|
-
{
|
|
182
|
-
processId: process.pid,
|
|
183
|
-
rootUri,
|
|
184
|
-
rootPath: this.rootDir,
|
|
185
|
-
workspaceFolders: [{ uri: rootUri, name: "workspace" }],
|
|
186
|
-
capabilities: {
|
|
187
|
-
workspace: {
|
|
188
|
-
workspaceFolders: true,
|
|
189
|
-
configuration: true,
|
|
190
|
-
},
|
|
191
|
-
textDocument: {
|
|
192
|
-
synchronization: {
|
|
193
|
-
dynamicRegistration: false,
|
|
194
|
-
willSave: false,
|
|
195
|
-
willSaveWaitUntil: false,
|
|
196
|
-
didSave: true,
|
|
197
|
-
},
|
|
198
|
-
publishDiagnostics: {
|
|
199
|
-
relatedInformation: true,
|
|
200
|
-
versionSupport: true,
|
|
201
|
-
},
|
|
202
|
-
hover: {
|
|
203
|
-
contentFormat: ["markdown", "plaintext"],
|
|
204
|
-
},
|
|
205
|
-
definition: {
|
|
206
|
-
linkSupport: true,
|
|
207
|
-
},
|
|
208
|
-
references: {},
|
|
209
|
-
documentSymbol: {
|
|
210
|
-
hierarchicalDocumentSymbolSupport: true,
|
|
211
|
-
},
|
|
212
|
-
diagnostic: {
|
|
213
|
-
dynamicRegistration: false,
|
|
214
|
-
},
|
|
215
|
-
},
|
|
216
|
-
...customCaps,
|
|
217
|
-
},
|
|
218
|
-
initializationOptions: {
|
|
219
|
-
...customInitOpts,
|
|
220
|
-
},
|
|
221
|
-
},
|
|
222
|
-
loadKernelConfig().lsp.init_timeout_ms || 25000,
|
|
223
|
-
);
|
|
224
|
-
|
|
225
|
-
this.serverCapabilities = initResult?.capabilities || {};
|
|
226
|
-
|
|
227
|
-
// Handshake Phase 2: initialized notification
|
|
228
|
-
this.sendNotification("initialized", {});
|
|
229
|
-
this.state = "ready";
|
|
230
|
-
return true;
|
|
231
|
-
} catch (err) {
|
|
232
|
-
this.state = "error";
|
|
233
|
-
this.stop();
|
|
234
|
-
return false;
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
/**
|
|
239
|
-
* Handle incoming stdout bytes (stdio framing: Content-Length: ...\r\n\r\n{JSON})
|
|
240
|
-
*/
|
|
241
|
-
private onData(chunk: Buffer): void {
|
|
242
|
-
this.touch();
|
|
243
|
-
this.buffer = Buffer.concat([this.buffer, chunk]);
|
|
244
|
-
|
|
245
|
-
if (this.buffer.length > StdioLspClient.MAX_BUFFER_SIZE) {
|
|
246
|
-
kernelDebug(new Error("LSP client buffer exceeded maximum allowed size. Clearing buffer."));
|
|
247
|
-
this.buffer = Buffer.alloc(0);
|
|
248
|
-
return;
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
while (true) {
|
|
252
|
-
// Resynchronize if buffer has leading garbage before Content-Length
|
|
253
|
-
const clIndex = this.buffer.indexOf("Content-Length:");
|
|
254
|
-
const lowerClIndex = clIndex === -1 ? this.buffer.indexOf("content-length:") : clIndex;
|
|
255
|
-
if (lowerClIndex > 0) {
|
|
256
|
-
this.buffer = this.buffer.subarray(lowerClIndex);
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
const headerEndIndex = this.buffer.indexOf("\r\n\r\n");
|
|
260
|
-
if (headerEndIndex === -1) {
|
|
261
|
-
if (this.buffer.length > StdioLspClient.MAX_HEADER_SIZE) {
|
|
262
|
-
kernelDebug(new Error("LSP header exceeds max allowable size without delimiter. Discarding corrupt stream."));
|
|
263
|
-
this.buffer = Buffer.alloc(0);
|
|
264
|
-
}
|
|
265
|
-
break;
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
const headerText = this.buffer
|
|
269
|
-
.subarray(0, headerEndIndex)
|
|
270
|
-
.toString("utf8");
|
|
271
|
-
const match = /(?:^|\r?\n)Content-Length:\s*(\d+)\s*(?:\r?\n|$)/i.exec(headerText);
|
|
272
|
-
if (!match) {
|
|
273
|
-
// Corrupted header, skip past \r\n\r\n
|
|
274
|
-
this.buffer = this.buffer.subarray(headerEndIndex + 4);
|
|
275
|
-
continue;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
const contentLengthStr = match[1];
|
|
279
|
-
const contentLength = Number(contentLengthStr);
|
|
280
|
-
|
|
281
|
-
if (
|
|
282
|
-
!Number.isSafeInteger(contentLength) ||
|
|
283
|
-
contentLength < 0 ||
|
|
284
|
-
contentLength > StdioLspClient.MAX_CONTENT_LENGTH
|
|
285
|
-
) {
|
|
286
|
-
kernelDebug(new Error(`Invalid or oversized LSP Content-Length: ${contentLengthStr}`));
|
|
287
|
-
this.buffer = Buffer.alloc(0);
|
|
288
|
-
break;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
const bodyStartIndex = headerEndIndex + 4;
|
|
292
|
-
const totalMessageLength = bodyStartIndex + contentLength;
|
|
293
|
-
|
|
294
|
-
if (this.buffer.length < totalMessageLength) {
|
|
295
|
-
// Incomplete body, wait for next data chunk
|
|
296
|
-
break;
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
const bodyBuffer = this.buffer.subarray(
|
|
300
|
-
bodyStartIndex,
|
|
301
|
-
totalMessageLength,
|
|
302
|
-
);
|
|
303
|
-
this.buffer = this.buffer.subarray(totalMessageLength);
|
|
304
|
-
|
|
305
|
-
try {
|
|
306
|
-
const messageJson = JSON.parse(bodyBuffer.toString("utf8"));
|
|
307
|
-
this.handleMessage(messageJson);
|
|
308
|
-
} catch (e) {
|
|
309
|
-
kernelDebug(e);
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
/**
|
|
315
|
-
* Dispatch parsed JSON-RPC message
|
|
316
|
-
*/
|
|
317
|
-
private handleMessage(msg: any): void {
|
|
318
|
-
if (msg.id !== undefined && this.pendingRequests.has(msg.id)) {
|
|
319
|
-
// It's a response to a request
|
|
320
|
-
const { resolve, reject, timer } = this.pendingRequests.get(msg.id)!;
|
|
321
|
-
clearTimeout(timer);
|
|
322
|
-
this.pendingRequests.delete(msg.id);
|
|
323
|
-
|
|
324
|
-
if (msg.error) {
|
|
325
|
-
reject(new Error(msg.error.message || `LSP Error ${msg.error.code}`));
|
|
326
|
-
} else {
|
|
327
|
-
resolve(msg.result);
|
|
328
|
-
}
|
|
329
|
-
return;
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
if (msg.method) {
|
|
333
|
-
// Servers may issue JSON-RPC requests of their own (most notably
|
|
334
|
-
// workspace/configuration). Replying is required or the server can stop
|
|
335
|
-
// processing subsequent document requests while waiting indefinitely.
|
|
336
|
-
if (msg.id !== undefined) {
|
|
337
|
-
this.handleServerRequest(msg);
|
|
338
|
-
} else {
|
|
339
|
-
this.handleNotification(msg);
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
/** Reply to server-initiated JSON-RPC requests with minimal safe defaults. */
|
|
345
|
-
private handleServerRequest(request: { id: number | string; method: string; params?: any }): void {
|
|
346
|
-
let result: any = this.adapter.handleServerRequest?.(
|
|
347
|
-
request.method,
|
|
348
|
-
request.params,
|
|
349
|
-
this.rootDir,
|
|
350
|
-
);
|
|
351
|
-
|
|
352
|
-
if (result === undefined || result === null) {
|
|
353
|
-
switch (request.method) {
|
|
354
|
-
case "workspace/configuration":
|
|
355
|
-
result = Array.isArray(request.params?.items)
|
|
356
|
-
? request.params.items.map(() => null)
|
|
357
|
-
: [];
|
|
358
|
-
break;
|
|
359
|
-
case "workspace/workspaceFolders":
|
|
360
|
-
result = [
|
|
361
|
-
{
|
|
362
|
-
uri: pathToUri(this.rootDir),
|
|
363
|
-
name: path.basename(this.rootDir),
|
|
364
|
-
},
|
|
365
|
-
];
|
|
366
|
-
break;
|
|
367
|
-
case "workspace/applyEdit":
|
|
368
|
-
result = { applied: false };
|
|
369
|
-
break;
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
this.sendRaw({ jsonrpc: "2.0", id: request.id, result });
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
/**
|
|
376
|
-
* Handle incoming notifications (e.g. textDocument/publishDiagnostics)
|
|
377
|
-
*/
|
|
378
|
-
private handleNotification(notif: LspNotification): void {
|
|
379
|
-
if (notif.method === "textDocument/publishDiagnostics") {
|
|
380
|
-
const rawUri = notif.params?.uri;
|
|
381
|
-
let diagnostics = notif.params?.diagnostics || [];
|
|
382
|
-
if (diagnostics.length > MAX_LSP_DIAGNOSTICS) {
|
|
383
|
-
diagnostics = diagnostics.slice(0, MAX_LSP_DIAGNOSTICS);
|
|
384
|
-
}
|
|
385
|
-
if (rawUri) {
|
|
386
|
-
const uri = normalizeUri(rawUri);
|
|
387
|
-
if (this.adapter.transformDiagnostics) {
|
|
388
|
-
diagnostics = this.adapter.transformDiagnostics(uri, diagnostics);
|
|
389
|
-
}
|
|
390
|
-
this.diagnosticsCache.set(uri, diagnostics);
|
|
391
|
-
const listeners = this.diagnosticListeners.get(uri);
|
|
392
|
-
if (listeners && listeners.length > 0) {
|
|
393
|
-
this.diagnosticListeners.delete(uri);
|
|
394
|
-
for (const listener of listeners) {
|
|
395
|
-
try {
|
|
396
|
-
listener(diagnostics);
|
|
397
|
-
} catch (e) {
|
|
398
|
-
kernelDebug(e);
|
|
399
|
-
}
|
|
400
|
-
}
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
/**
|
|
407
|
-
* Send JSON-RPC Request with timeout
|
|
408
|
-
*/
|
|
409
|
-
public sendRequest<T = any>(
|
|
410
|
-
method: string,
|
|
411
|
-
params?: any,
|
|
412
|
-
timeoutMs = 4000,
|
|
413
|
-
): Promise<T> {
|
|
414
|
-
this.touch();
|
|
415
|
-
const id = this.nextRequestId++;
|
|
416
|
-
const payload: LspRequest = {
|
|
417
|
-
jsonrpc: "2.0",
|
|
418
|
-
id,
|
|
419
|
-
method,
|
|
420
|
-
params,
|
|
421
|
-
};
|
|
422
|
-
|
|
423
|
-
return new Promise<T>((resolve, reject) => {
|
|
424
|
-
const timer = setTimeout(() => {
|
|
425
|
-
if (this.pendingRequests.has(id)) {
|
|
426
|
-
this.pendingRequests.delete(id);
|
|
427
|
-
reject(
|
|
428
|
-
new Error(`LSP Request '${method}' timed out after ${timeoutMs}ms`),
|
|
429
|
-
);
|
|
430
|
-
}
|
|
431
|
-
}, timeoutMs);
|
|
432
|
-
|
|
433
|
-
this.pendingRequests.set(id, { resolve, reject, timer });
|
|
434
|
-
this.sendRaw(payload);
|
|
435
|
-
});
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
/**
|
|
439
|
-
* Send JSON-RPC Notification (fire-and-forget)
|
|
440
|
-
*/
|
|
441
|
-
public sendNotification(method: string, params?: any): void {
|
|
442
|
-
this.touch();
|
|
443
|
-
const payload: LspNotification = {
|
|
444
|
-
jsonrpc: "2.0",
|
|
445
|
-
method,
|
|
446
|
-
params,
|
|
447
|
-
};
|
|
448
|
-
this.sendRaw(payload);
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
private sendRaw(obj: any): void {
|
|
452
|
-
if (!this.process || !this.process.stdin || this.process.stdin.destroyed) {
|
|
453
|
-
return;
|
|
454
|
-
}
|
|
455
|
-
const jsonStr = JSON.stringify(obj);
|
|
456
|
-
const byteLength = Buffer.byteLength(jsonStr, "utf8");
|
|
457
|
-
const frame = `Content-Length: ${byteLength}\r\n\r\n${jsonStr}`;
|
|
458
|
-
try {
|
|
459
|
-
this.process.stdin.write(frame);
|
|
460
|
-
} catch (e) {
|
|
461
|
-
kernelDebug(e);
|
|
462
|
-
}
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
/**
|
|
466
|
-
* Open document in LSP buffer tracking
|
|
467
|
-
*/
|
|
468
|
-
public async openDocument(filePath: string, content?: string): Promise<void> {
|
|
469
|
-
const uri = pathToUri(filePath);
|
|
470
|
-
const fileStat = fs.statSync(filePath);
|
|
471
|
-
if (!fileStat.isFile() || fileStat.size > MAX_LSP_DOCUMENT_BYTES) {
|
|
472
|
-
throw new Error(`LSP document exceeds the ${MAX_LSP_DOCUMENT_BYTES}-byte limit`);
|
|
473
|
-
}
|
|
474
|
-
const text = content === undefined ? fs.readFileSync(filePath, "utf8") : content;
|
|
475
|
-
if (Buffer.byteLength(text, "utf8") > MAX_LSP_DOCUMENT_BYTES) {
|
|
476
|
-
throw new Error(`LSP document exceeds the ${MAX_LSP_DOCUMENT_BYTES}-byte limit`);
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
if (this.openDocuments.has(uri)) {
|
|
480
|
-
const existing = this.openDocuments.get(uri);
|
|
481
|
-
if (existing && existing.text === text) {
|
|
482
|
-
return;
|
|
483
|
-
}
|
|
484
|
-
await this.changeDocument(filePath, text);
|
|
485
|
-
return;
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
this.openDocuments.set(uri, { version: 1, text });
|
|
489
|
-
this.diagnosticsCache.delete(uri);
|
|
490
|
-
this.sendNotification("textDocument/didOpen", {
|
|
491
|
-
textDocument: {
|
|
492
|
-
uri,
|
|
493
|
-
languageId: this.languageId,
|
|
494
|
-
version: 1,
|
|
495
|
-
text,
|
|
496
|
-
},
|
|
497
|
-
});
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
/**
|
|
501
|
-
* Send document change notification
|
|
502
|
-
*/
|
|
503
|
-
public async changeDocument(filePath: string, text: string): Promise<void> {
|
|
504
|
-
const uri = pathToUri(filePath);
|
|
505
|
-
const existing = this.openDocuments.get(uri);
|
|
506
|
-
const version = (existing?.version || 0) + 1;
|
|
507
|
-
this.openDocuments.set(uri, { version, text });
|
|
508
|
-
this.diagnosticsCache.delete(uri);
|
|
509
|
-
|
|
510
|
-
this.sendNotification("textDocument/didChange", {
|
|
511
|
-
textDocument: {
|
|
512
|
-
uri,
|
|
513
|
-
version,
|
|
514
|
-
},
|
|
515
|
-
contentChanges: [{ text }],
|
|
516
|
-
});
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
/**
|
|
520
|
-
* Send document saved notification
|
|
521
|
-
*/
|
|
522
|
-
public async saveDocument(filePath: string, text?: string): Promise<void> {
|
|
523
|
-
const uri = pathToUri(filePath);
|
|
524
|
-
this.sendNotification("textDocument/didSave", {
|
|
525
|
-
textDocument: { uri },
|
|
526
|
-
text,
|
|
527
|
-
});
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
/**
|
|
531
|
-
* Wait for a push diagnostic notification event for a specific document URI.
|
|
532
|
-
*/
|
|
533
|
-
private waitForPushDiagnostics(uri: string, timeoutMs: number): Promise<LspDiagnostic[] | null> {
|
|
534
|
-
return new Promise((resolve) => {
|
|
535
|
-
let timer: NodeJS.Timeout | null = null;
|
|
536
|
-
|
|
537
|
-
const onArrived = (diags: LspDiagnostic[]) => {
|
|
538
|
-
if (timer) clearTimeout(timer);
|
|
539
|
-
resolve(diags);
|
|
540
|
-
};
|
|
541
|
-
|
|
542
|
-
timer = setTimeout(() => {
|
|
543
|
-
const listeners = this.diagnosticListeners.get(uri) || [];
|
|
544
|
-
const filtered = listeners.filter((l) => l !== onArrived);
|
|
545
|
-
if (filtered.length > 0) {
|
|
546
|
-
this.diagnosticListeners.set(uri, filtered);
|
|
547
|
-
} else {
|
|
548
|
-
this.diagnosticListeners.delete(uri);
|
|
549
|
-
}
|
|
550
|
-
resolve(null);
|
|
551
|
-
}, timeoutMs);
|
|
552
|
-
|
|
553
|
-
const listeners = this.diagnosticListeners.get(uri) || [];
|
|
554
|
-
listeners.push(onArrived);
|
|
555
|
-
this.diagnosticListeners.set(uri, listeners);
|
|
556
|
-
});
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
/**
|
|
560
|
-
* Get diagnostics with an explicit uncertainty status.
|
|
561
|
-
* An empty result is only clean when the server positively reported it.
|
|
562
|
-
*/
|
|
563
|
-
public async getDiagnosticsResult(filePath: string, timeoutMsOverride?: number): Promise<{
|
|
564
|
-
status: "clean" | "findings" | "timeout" | "inconclusive";
|
|
565
|
-
diagnostics: LspDiagnostic[];
|
|
566
|
-
}> {
|
|
567
|
-
const uri = pathToUri(filePath);
|
|
568
|
-
// Clear any previous cache so newly triggered diagnostics from didSave are observed fresh
|
|
569
|
-
this.diagnosticsCache.delete(uri);
|
|
570
|
-
await this.openDocument(filePath);
|
|
571
|
-
await this.saveDocument(filePath);
|
|
572
|
-
|
|
573
|
-
// If push diagnostics were already published and cached, return them immediately.
|
|
574
|
-
if (this.diagnosticsCache.has(uri)) {
|
|
575
|
-
const cached = this.diagnosticsCache.get(uri) || [];
|
|
576
|
-
return {
|
|
577
|
-
status: cached.length > 0 ? "findings" : "clean",
|
|
578
|
-
diagnostics: cached,
|
|
579
|
-
};
|
|
580
|
-
}
|
|
581
|
-
|
|
582
|
-
const config = loadKernelConfig();
|
|
583
|
-
const timeoutMs = timeoutMsOverride ?? config.lsp.diagnostic_timeout_ms ?? 8000;
|
|
584
|
-
|
|
585
|
-
// Push-only servers (or servers like rust-analyzer that run cargo check on didSave/didOpen)
|
|
586
|
-
// emit textDocument/publishDiagnostics asynchronously.
|
|
587
|
-
// Event-driven wait: resolves as soon as the server publishes without sleep polling.
|
|
588
|
-
const pushResult = await this.waitForPushDiagnostics(uri, timeoutMs);
|
|
589
|
-
if (pushResult !== null) {
|
|
590
|
-
return {
|
|
591
|
-
status: pushResult.length > 0 ? "findings" : "clean",
|
|
592
|
-
diagnostics: pushResult,
|
|
593
|
-
};
|
|
594
|
-
}
|
|
595
|
-
|
|
596
|
-
// Pull diagnostics fallback if server supports LSP 3.17 diagnosticProvider
|
|
597
|
-
if (this.serverCapabilities.diagnosticProvider) {
|
|
598
|
-
try {
|
|
599
|
-
const pullRes = await this.sendRequest<any>(
|
|
600
|
-
"textDocument/diagnostic",
|
|
601
|
-
{
|
|
602
|
-
textDocument: { uri },
|
|
603
|
-
},
|
|
604
|
-
Math.min(timeoutMs, 4000),
|
|
605
|
-
);
|
|
606
|
-
if (pullRes?.items && Array.isArray(pullRes.items)) {
|
|
607
|
-
this.diagnosticsCache.set(uri, pullRes.items);
|
|
608
|
-
return {
|
|
609
|
-
status: pullRes.items.length > 0 ? "findings" : "clean",
|
|
610
|
-
diagnostics: pullRes.items,
|
|
611
|
-
};
|
|
612
|
-
}
|
|
613
|
-
} catch (e) {
|
|
614
|
-
kernelDebug(e);
|
|
615
|
-
}
|
|
616
|
-
}
|
|
617
|
-
|
|
618
|
-
return { status: "inconclusive", diagnostics: [] };
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
/**
|
|
622
|
-
* Backward-compatible diagnostics accessor for the LSP tool.
|
|
623
|
-
*/
|
|
624
|
-
public async getDiagnostics(filePath: string): Promise<LspDiagnostic[]> {
|
|
625
|
-
const result = await this.getDiagnosticsResult(filePath);
|
|
626
|
-
return result.diagnostics;
|
|
627
|
-
}
|
|
628
|
-
|
|
629
|
-
/**
|
|
630
|
-
* Jump to Definition
|
|
631
|
-
*/
|
|
632
|
-
public async gotoDefinition(
|
|
633
|
-
filePath: string,
|
|
634
|
-
line: number,
|
|
635
|
-
character: number,
|
|
636
|
-
): Promise<LspLocation[]> {
|
|
637
|
-
const uri = pathToUri(filePath);
|
|
638
|
-
await this.openDocument(filePath);
|
|
639
|
-
|
|
640
|
-
try {
|
|
641
|
-
const res = await this.sendRequest<any>("textDocument/definition", {
|
|
642
|
-
textDocument: { uri },
|
|
643
|
-
position: { line, character },
|
|
644
|
-
});
|
|
645
|
-
return normalizeLocations(res);
|
|
646
|
-
} catch {
|
|
647
|
-
return [];
|
|
648
|
-
}
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
/**
|
|
652
|
-
* Find References
|
|
653
|
-
*/
|
|
654
|
-
public async findReferences(
|
|
655
|
-
filePath: string,
|
|
656
|
-
line: number,
|
|
657
|
-
character: number,
|
|
658
|
-
): Promise<LspLocation[]> {
|
|
659
|
-
const uri = pathToUri(filePath);
|
|
660
|
-
await this.openDocument(filePath);
|
|
661
|
-
|
|
662
|
-
try {
|
|
663
|
-
const res = await this.sendRequest<any>("textDocument/references", {
|
|
664
|
-
textDocument: { uri },
|
|
665
|
-
position: { line, character },
|
|
666
|
-
context: { includeDeclaration: true },
|
|
667
|
-
});
|
|
668
|
-
return normalizeLocations(res);
|
|
669
|
-
} catch {
|
|
670
|
-
return [];
|
|
671
|
-
}
|
|
672
|
-
}
|
|
673
|
-
|
|
674
|
-
/**
|
|
675
|
-
* Hover (Type information / Docstrings)
|
|
676
|
-
*/
|
|
677
|
-
public async hover(
|
|
678
|
-
filePath: string,
|
|
679
|
-
line: number,
|
|
680
|
-
character: number,
|
|
681
|
-
): Promise<LspHover | null> {
|
|
682
|
-
const uri = pathToUri(filePath);
|
|
683
|
-
await this.openDocument(filePath);
|
|
684
|
-
|
|
685
|
-
try {
|
|
686
|
-
return await this.sendRequest<LspHover>("textDocument/hover", {
|
|
687
|
-
textDocument: { uri },
|
|
688
|
-
position: { line, character },
|
|
689
|
-
});
|
|
690
|
-
} catch {
|
|
691
|
-
return null;
|
|
692
|
-
}
|
|
693
|
-
}
|
|
694
|
-
|
|
695
|
-
/**
|
|
696
|
-
* Document Symbols
|
|
697
|
-
*/
|
|
698
|
-
public async documentSymbol(
|
|
699
|
-
filePath: string,
|
|
700
|
-
): Promise<(LspDocumentSymbol | LspSymbolInformation)[]> {
|
|
701
|
-
const uri = pathToUri(filePath);
|
|
702
|
-
await this.openDocument(filePath);
|
|
703
|
-
|
|
704
|
-
try {
|
|
705
|
-
const res = await this.sendRequest<any>("textDocument/documentSymbol", {
|
|
706
|
-
textDocument: { uri },
|
|
707
|
-
});
|
|
708
|
-
return Array.isArray(res) ? res : [];
|
|
709
|
-
} catch {
|
|
710
|
-
return [];
|
|
711
|
-
}
|
|
712
|
-
}
|
|
713
|
-
|
|
714
|
-
/**
|
|
715
|
-
* Graceful shutdown and termination
|
|
716
|
-
*/
|
|
717
|
-
public async stop(): Promise<void> {
|
|
718
|
-
if (this.state === "stopped" && !this.process) return;
|
|
719
|
-
this.state = "shutting_down";
|
|
720
|
-
const child = this.process;
|
|
721
|
-
|
|
722
|
-
try {
|
|
723
|
-
if (child) {
|
|
724
|
-
const exited = new Promise<void>((resolve) => {
|
|
725
|
-
child.once("exit", () => resolve());
|
|
726
|
-
child.once("error", () => resolve());
|
|
727
|
-
});
|
|
728
|
-
try {
|
|
729
|
-
await Promise.race([
|
|
730
|
-
this.sendRequest("shutdown", undefined, 1000).then(() => {
|
|
731
|
-
this.sendNotification("exit");
|
|
732
|
-
}),
|
|
733
|
-
new Promise((resolve) => setTimeout(resolve, 1000)),
|
|
734
|
-
]);
|
|
735
|
-
} catch (error) {
|
|
736
|
-
kernelDebug(error);
|
|
737
|
-
}
|
|
738
|
-
|
|
739
|
-
await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 250))]);
|
|
740
|
-
if (child.exitCode === null && child.signalCode === null && !child.killed) {
|
|
741
|
-
child.kill();
|
|
742
|
-
}
|
|
743
|
-
await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 2000))]);
|
|
744
|
-
if (child.exitCode === null && child.signalCode === null) {
|
|
745
|
-
child.kill("SIGKILL");
|
|
746
|
-
await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 1000))]);
|
|
747
|
-
}
|
|
748
|
-
}
|
|
749
|
-
} catch (e) {
|
|
750
|
-
kernelDebug(e);
|
|
751
|
-
}
|
|
752
|
-
|
|
753
|
-
this.state = "stopped";
|
|
754
|
-
this.process = null;
|
|
755
|
-
this.cleanupPending(new Error("LSP client stopped"));
|
|
756
|
-
}
|
|
757
|
-
|
|
758
|
-
private cleanupPending(err: Error): void {
|
|
759
|
-
for (const [id, req] of this.pendingRequests.entries()) {
|
|
760
|
-
clearTimeout(req.timer);
|
|
761
|
-
req.reject(err);
|
|
762
|
-
}
|
|
763
|
-
this.pendingRequests.clear();
|
|
764
|
-
}
|
|
765
|
-
}
|