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