holycodex 0.2.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/LICENSE.md +82 -0
- package/README.md +107 -0
- package/THIRD-PARTY-NOTICES.md +7 -0
- package/bin/holycodex.js +2 -0
- package/marketplace.json +12 -0
- package/package.json +59 -0
- package/plugin/.codex-plugin/plugin.json +29 -0
- package/plugin/.mcp.json +8 -0
- package/plugin/agents/explorer.toml +6 -0
- package/plugin/agents/librarian.toml +6 -0
- package/plugin/agents/worker.toml +6 -0
- package/plugin/hooks/hooks.json +93 -0
- package/plugin/runtime/bootstrap.js +23 -0
- package/plugin/runtime/cli.js +233 -0
- package/plugin/runtime/git-bash.js +359 -0
- package/plugin/runtime/lsp.js +3674 -0
- package/plugin/runtime/rules.js +146 -0
- package/plugin/runtime/src-tRIOClWZ.js +209 -0
- package/plugin/skills/ast-grep/LICENSE +21 -0
- package/plugin/skills/ast-grep/SKILL.md +20 -0
- package/plugin/skills/ast-grep/references/cli.md +3 -0
- package/plugin/skills/ast-grep/references/install.md +3 -0
- package/plugin/skills/ast-grep/references/patterns.md +3 -0
- package/plugin/skills/ast-grep/references/pitfalls.md +3 -0
- package/plugin/skills/ast-grep/references/recipes.md +9 -0
- package/plugin/skills/ast-grep/references/sgconfig.md +3 -0
- package/plugin/skills/ast-grep/references/yaml-rules.md +3 -0
- package/plugin/skills/caveman/LICENSE +21 -0
- package/plugin/skills/caveman/SKILL.md +84 -0
- package/plugin/skills/comment-checker/SKILL.md +16 -0
- package/plugin/skills/compress/SKILL.md +26 -0
- package/plugin/skills/debugging/SKILL.md +23 -0
- package/plugin/skills/debugging/references/runtimes/README.md +9 -0
- package/plugin/skills/debugging/references/tools/README.md +8 -0
- package/plugin/skills/define-goal/LICENSE.txt +201 -0
- package/plugin/skills/define-goal/SKILL.md +36 -0
- package/plugin/skills/frontend/ATTRIBUTION.md +218 -0
- package/plugin/skills/frontend/LICENSE-Apache-2.0.txt +201 -0
- package/plugin/skills/frontend/SKILL.md +42 -0
- package/plugin/skills/frontend/references/perfection/README.md +5 -0
- package/plugin/skills/frontend/references/perfection/react-perf-tooling.md +3 -0
- package/plugin/skills/frontend/references/ui-ux-db/README.md +5 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/charts.csv +26 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/colors.csv +162 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/icons.csv +106 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/landing.csv +35 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/products.csv +162 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/react-performance.csv +45 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/stacks/astro.csv +54 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/stacks/flutter.csv +53 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/stacks/html-tailwind.csv +56 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/stacks/jetpack-compose.csv +53 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/stacks/nextjs.csv +53 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/stacks/nuxt-ui.csv +51 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/stacks/nuxtjs.csv +59 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/stacks/react-native.csv +52 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/stacks/react.csv +54 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/stacks/shadcn.csv +61 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/stacks/svelte.csv +54 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/stacks/swiftui.csv +51 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/stacks/vue.csv +50 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/styles.csv +85 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/typography.csv +74 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/ui-reasoning.csv +162 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/ux-guidelines.csv +100 -0
- package/plugin/skills/frontend/references/ui-ux-db/data/web-interface.csv +31 -0
- package/plugin/skills/frontend/references/ui-ux-db/scripts/core.py +262 -0
- package/plugin/skills/frontend/references/ui-ux-db/scripts/design_system.py +1148 -0
- package/plugin/skills/frontend/references/ui-ux-db/scripts/search.py +114 -0
- package/plugin/skills/handoff/SKILL.md +10 -0
- package/plugin/skills/lsp/SKILL.md +35 -0
- package/plugin/skills/lsp-setup/SKILL.md +18 -0
- package/plugin/skills/lsp-setup/scripts/detect-lsp.ts +233 -0
- package/plugin/skills/lsp-setup/scripts/lsp-server-table.ts +188 -0
- package/plugin/skills/lsp-setup/scripts/tsconfig.json +17 -0
- package/plugin/skills/lsp-setup/scripts/verify-lsp.ts +166 -0
- package/plugin/skills/plan/SKILL.md +14 -0
- package/plugin/skills/plan-review/SKILL.md +12 -0
- package/plugin/skills/programming/SKILL.md +35 -0
- package/plugin/skills/programming/references/code-smells.md +3 -0
- package/plugin/skills/programming/references/go/README.md +3 -0
- package/plugin/skills/programming/references/logging.md +3 -0
- package/plugin/skills/programming/references/python/README.md +3 -0
- package/plugin/skills/programming/references/rust/README.md +3 -0
- package/plugin/skills/programming/references/rust-ub/README.md +3 -0
- package/plugin/skills/programming/references/typescript/README.md +3 -0
- package/plugin/skills/refactor/SKILL.md +21 -0
- package/plugin/skills/remove-ai-slops/SKILL.md +20 -0
- package/plugin/skills/rules/SKILL.md +16 -0
- package/plugin/skills/security-research/SKILL.md +38 -0
- package/plugin/skills/tdd/SKILL.md +24 -0
- package/plugin/skills/tdd/mocking.md +60 -0
- package/plugin/skills/tdd/tests.md +77 -0
|
@@ -0,0 +1,3674 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { a as successResponse, i as messageFromError, n as errorResponse, o as isPlainRecord, r as jsonRpcId, t as runJsonRpcStdioServer } from "./src-tRIOClWZ.js";
|
|
3
|
+
import { basename, delimiter, dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
|
|
4
|
+
import { argv, execPath, stderr } from "node:process";
|
|
5
|
+
import { homedir, tmpdir } from "node:os";
|
|
6
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
7
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
8
|
+
import { closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
|
|
9
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
10
|
+
import { connect, createServer } from "node:net";
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
12
|
+
import { createRequire } from "node:module";
|
|
13
|
+
//#region packages/lsp-core/src/request-context.ts
|
|
14
|
+
var storage = new AsyncLocalStorage();
|
|
15
|
+
function runWithRequestContext(context, fn) {
|
|
16
|
+
return storage.run(context, fn);
|
|
17
|
+
}
|
|
18
|
+
function contextCwd() {
|
|
19
|
+
return storage.getStore()?.cwd ?? process.cwd();
|
|
20
|
+
}
|
|
21
|
+
function contextEnv(key) {
|
|
22
|
+
const store = storage.getStore();
|
|
23
|
+
if (store?.env) return store.env[key];
|
|
24
|
+
return process.env[key];
|
|
25
|
+
}
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region packages/lsp-core/src/lsp/effective-extension.ts
|
|
28
|
+
var BASENAME_EXTENSIONS = {
|
|
29
|
+
Dockerfile: ".dockerfile",
|
|
30
|
+
Containerfile: ".dockerfile"
|
|
31
|
+
};
|
|
32
|
+
function effectiveExtension(filePath) {
|
|
33
|
+
return BASENAME_EXTENSIONS[basename(filePath)] ?? extname(filePath);
|
|
34
|
+
}
|
|
35
|
+
//#endregion
|
|
36
|
+
//#region packages/lsp-core/src/lsp/errors.ts
|
|
37
|
+
var LspConnectionClosedError = class extends Error {
|
|
38
|
+
constructor(serverId, root, message) {
|
|
39
|
+
super(message ?? `LSP connection closed for ${serverId} at ${root}`);
|
|
40
|
+
this.serverId = serverId;
|
|
41
|
+
this.root = root;
|
|
42
|
+
this.name = "LspConnectionClosedError";
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
var LspProcessExitedError = class extends Error {
|
|
46
|
+
constructor(serverId, root, exitCode, stderrTail) {
|
|
47
|
+
const stderrSuffix = stderrTail ? `\nstderr tail: ${stderrTail}` : "";
|
|
48
|
+
super(`LSP server ${serverId} at ${root} exited with code ${exitCode ?? "null"}${stderrSuffix}`);
|
|
49
|
+
this.serverId = serverId;
|
|
50
|
+
this.root = root;
|
|
51
|
+
this.exitCode = exitCode;
|
|
52
|
+
this.stderrTail = stderrTail;
|
|
53
|
+
this.name = "LspProcessExitedError";
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
var LspRequestTimeoutError = class extends Error {
|
|
57
|
+
constructor(method, stderrTail) {
|
|
58
|
+
const stderrSuffix = stderrTail ? `\nrecent stderr: ${stderrTail}` : "";
|
|
59
|
+
super(`LSP request timeout (method: ${method})${stderrSuffix}`);
|
|
60
|
+
this.method = method;
|
|
61
|
+
this.stderrTail = stderrTail;
|
|
62
|
+
this.name = "LspRequestTimeoutError";
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
var LspInvalidPathError = class extends Error {
|
|
66
|
+
constructor(..._args) {
|
|
67
|
+
super(..._args);
|
|
68
|
+
this.name = "LspInvalidPathError";
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
var LspServerLookupError = class extends Error {
|
|
72
|
+
constructor(..._args2) {
|
|
73
|
+
super(..._args2);
|
|
74
|
+
this.name = "LspServerLookupError";
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
var LspServerInitializingError = class extends Error {
|
|
78
|
+
constructor(originalError) {
|
|
79
|
+
super(`LSP server is still initializing. Please retry in a few seconds. Original error: ${originalError.message}`);
|
|
80
|
+
this.originalError = originalError;
|
|
81
|
+
this.name = "LspServerInitializingError";
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
var LspProcessSpawnError = class extends Error {
|
|
85
|
+
constructor(..._args3) {
|
|
86
|
+
super(..._args3);
|
|
87
|
+
this.name = "LspProcessSpawnError";
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
function isLspDeadConnectionError(err) {
|
|
91
|
+
return err instanceof LspConnectionClosedError || err instanceof LspProcessExitedError;
|
|
92
|
+
}
|
|
93
|
+
//#endregion
|
|
94
|
+
//#region packages/lsp-core/src/lsp/cleanup-errors.ts
|
|
95
|
+
function reportBestEffortCleanupError(operation, error) {
|
|
96
|
+
if (process.env["CODEX_LSP_DEBUG_CLEANUP"] !== "1") return;
|
|
97
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
98
|
+
console.error(`[codex-lsp] ignored ${operation} failure during cleanup: ${message}`);
|
|
99
|
+
}
|
|
100
|
+
var STOP_HARD_KILL_TIMEOUT_MS = 5e3;
|
|
101
|
+
var STOP_SIGKILL_GRACE_MS = 1e3;
|
|
102
|
+
//#endregion
|
|
103
|
+
//#region packages/lsp-core/src/lsp/json-rpc-connection.ts
|
|
104
|
+
var HEADER_SEPARATOR = "\r\n\r\n";
|
|
105
|
+
var PARSE_ERROR = -32700;
|
|
106
|
+
var INVALID_REQUEST = -32600;
|
|
107
|
+
var METHOD_NOT_FOUND = -32601;
|
|
108
|
+
var INTERNAL_ERROR = -32603;
|
|
109
|
+
var JsonRpcConnection = class {
|
|
110
|
+
constructor(reader, writer) {
|
|
111
|
+
this.reader = reader;
|
|
112
|
+
this.writer = writer;
|
|
113
|
+
this.pendingRequests = /* @__PURE__ */ new Map();
|
|
114
|
+
this.notificationHandlers = /* @__PURE__ */ new Map();
|
|
115
|
+
this.requestHandlers = /* @__PURE__ */ new Map();
|
|
116
|
+
this.closeHandlers = [];
|
|
117
|
+
this.errorHandlers = [];
|
|
118
|
+
this.inputBuffer = Buffer.alloc(0);
|
|
119
|
+
this.nextRequestId = 1;
|
|
120
|
+
this.listening = false;
|
|
121
|
+
this.disposed = false;
|
|
122
|
+
this.handleData = (chunk) => {
|
|
123
|
+
const chunkBuffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf8");
|
|
124
|
+
this.inputBuffer = Buffer.concat([this.inputBuffer, chunkBuffer]);
|
|
125
|
+
this.drainInputBuffer();
|
|
126
|
+
};
|
|
127
|
+
this.handleClose = () => {
|
|
128
|
+
for (const handler of this.closeHandlers) handler();
|
|
129
|
+
};
|
|
130
|
+
this.handleStreamError = (error) => {
|
|
131
|
+
this.emitError(error);
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
listen() {
|
|
135
|
+
if (this.listening) return;
|
|
136
|
+
this.listening = true;
|
|
137
|
+
this.reader.on("data", this.handleData);
|
|
138
|
+
this.reader.on("close", this.handleClose);
|
|
139
|
+
this.reader.on("end", this.handleClose);
|
|
140
|
+
this.reader.on("error", this.handleStreamError);
|
|
141
|
+
this.writer.on("error", this.handleStreamError);
|
|
142
|
+
}
|
|
143
|
+
onNotification(method, handler) {
|
|
144
|
+
this.notificationHandlers.set(method, handler);
|
|
145
|
+
}
|
|
146
|
+
onRequest(method, handler) {
|
|
147
|
+
this.requestHandlers.set(method, handler);
|
|
148
|
+
}
|
|
149
|
+
onClose(handler) {
|
|
150
|
+
this.closeHandlers.push(handler);
|
|
151
|
+
}
|
|
152
|
+
onError(handler) {
|
|
153
|
+
this.errorHandlers.push(handler);
|
|
154
|
+
}
|
|
155
|
+
async sendRequest(method, params) {
|
|
156
|
+
if (this.disposed) throw new Error("JSON-RPC connection is disposed");
|
|
157
|
+
const id = this.nextRequestId;
|
|
158
|
+
this.nextRequestId += 1;
|
|
159
|
+
const message = params === void 0 ? {
|
|
160
|
+
jsonrpc: "2.0",
|
|
161
|
+
id,
|
|
162
|
+
method
|
|
163
|
+
} : {
|
|
164
|
+
jsonrpc: "2.0",
|
|
165
|
+
id,
|
|
166
|
+
method,
|
|
167
|
+
params
|
|
168
|
+
};
|
|
169
|
+
const responsePromise = new Promise((resolve, reject) => {
|
|
170
|
+
this.pendingRequests.set(String(id), {
|
|
171
|
+
resolve(result) {
|
|
172
|
+
resolve(result);
|
|
173
|
+
},
|
|
174
|
+
reject
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
try {
|
|
178
|
+
await this.writeMessage(message);
|
|
179
|
+
} catch (error) {
|
|
180
|
+
this.pendingRequests.delete(String(id));
|
|
181
|
+
throw error;
|
|
182
|
+
}
|
|
183
|
+
return responsePromise;
|
|
184
|
+
}
|
|
185
|
+
async sendNotification(method, params) {
|
|
186
|
+
if (this.disposed) return;
|
|
187
|
+
const message = params === void 0 ? {
|
|
188
|
+
jsonrpc: "2.0",
|
|
189
|
+
method
|
|
190
|
+
} : {
|
|
191
|
+
jsonrpc: "2.0",
|
|
192
|
+
method,
|
|
193
|
+
params
|
|
194
|
+
};
|
|
195
|
+
await this.writeMessage(message);
|
|
196
|
+
}
|
|
197
|
+
dispose() {
|
|
198
|
+
if (this.disposed) return;
|
|
199
|
+
this.disposed = true;
|
|
200
|
+
this.reader.off("data", this.handleData);
|
|
201
|
+
this.reader.off("close", this.handleClose);
|
|
202
|
+
this.reader.off("end", this.handleClose);
|
|
203
|
+
this.reader.off("error", this.handleStreamError);
|
|
204
|
+
this.writer.off("error", this.handleStreamError);
|
|
205
|
+
for (const pending of this.pendingRequests.values()) pending.reject(/* @__PURE__ */ new Error("JSON-RPC connection disposed"));
|
|
206
|
+
this.pendingRequests.clear();
|
|
207
|
+
this.notificationHandlers.clear();
|
|
208
|
+
this.requestHandlers.clear();
|
|
209
|
+
}
|
|
210
|
+
drainInputBuffer() {
|
|
211
|
+
while (true) {
|
|
212
|
+
const headerEnd = this.inputBuffer.indexOf(HEADER_SEPARATOR);
|
|
213
|
+
if (headerEnd === -1) return;
|
|
214
|
+
const contentLength = parseContentLength(this.inputBuffer.subarray(0, headerEnd).toString("ascii"));
|
|
215
|
+
if (contentLength === null) {
|
|
216
|
+
this.inputBuffer = Buffer.alloc(0);
|
|
217
|
+
this.emitError(/* @__PURE__ */ new Error("JSON-RPC message is missing Content-Length header"));
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
const bodyStart = headerEnd + Buffer.byteLength(HEADER_SEPARATOR);
|
|
221
|
+
const bodyEnd = bodyStart + contentLength;
|
|
222
|
+
if (this.inputBuffer.length < bodyEnd) return;
|
|
223
|
+
const body = this.inputBuffer.subarray(bodyStart, bodyEnd).toString("utf8");
|
|
224
|
+
this.inputBuffer = this.inputBuffer.subarray(bodyEnd);
|
|
225
|
+
this.dispatchBody(body);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
dispatchBody(body) {
|
|
229
|
+
let parsed;
|
|
230
|
+
try {
|
|
231
|
+
parsed = JSON.parse(body);
|
|
232
|
+
} catch (error) {
|
|
233
|
+
this.writeError(null, PARSE_ERROR, error instanceof Error ? error.message : "Parse error").catch((writeError) => this.emitError(toError(writeError)));
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
if (!isJsonRpcObject(parsed)) {
|
|
237
|
+
this.writeError(null, INVALID_REQUEST, "Invalid JSON-RPC message").catch((error) => this.emitError(toError(error)));
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
if ("id" in parsed && ("result" in parsed || "error" in parsed)) {
|
|
241
|
+
this.handleResponse(parsed);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
if (typeof parsed["method"] !== "string") {
|
|
245
|
+
const id = getMessageId(parsed) ?? null;
|
|
246
|
+
this.writeError(id, INVALID_REQUEST, "Invalid JSON-RPC method").catch((error) => this.emitError(toError(error)));
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
if ("id" in parsed) {
|
|
250
|
+
this.handleRequest(parsed);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
this.handleNotification(parsed["method"], parsed["params"]);
|
|
254
|
+
}
|
|
255
|
+
handleResponse(message) {
|
|
256
|
+
const id = getMessageId(message);
|
|
257
|
+
if (id === void 0) return;
|
|
258
|
+
const pending = this.pendingRequests.get(String(id));
|
|
259
|
+
if (!pending) return;
|
|
260
|
+
this.pendingRequests.delete(String(id));
|
|
261
|
+
if ("error" in message) {
|
|
262
|
+
pending.reject(jsonRpcErrorToError(message["error"]));
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
pending.resolve(message["result"]);
|
|
266
|
+
}
|
|
267
|
+
handleNotification(method, params) {
|
|
268
|
+
const handler = this.notificationHandlers.get(method);
|
|
269
|
+
if (!handler) return;
|
|
270
|
+
try {
|
|
271
|
+
handler(params);
|
|
272
|
+
} catch (error) {
|
|
273
|
+
this.emitError(toError(error));
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
handleRequest(message) {
|
|
277
|
+
const id = getMessageId(message);
|
|
278
|
+
if (id === void 0) {
|
|
279
|
+
this.writeError(null, INVALID_REQUEST, "Invalid JSON-RPC id").catch((error) => this.emitError(toError(error)));
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
const method = typeof message["method"] === "string" ? message["method"] : "";
|
|
283
|
+
const handler = this.requestHandlers.get(method);
|
|
284
|
+
if (!handler) {
|
|
285
|
+
this.writeError(id, METHOD_NOT_FOUND, `Method not found: ${method}`).catch((error) => this.emitError(toError(error)));
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
Promise.resolve().then(() => handler(message["params"])).then((result) => this.writeMessage({
|
|
289
|
+
jsonrpc: "2.0",
|
|
290
|
+
id,
|
|
291
|
+
result
|
|
292
|
+
}), (error) => this.writeError(id, INTERNAL_ERROR, toError(error).message)).catch((error) => this.emitError(toError(error)));
|
|
293
|
+
}
|
|
294
|
+
async writeError(id, code, message) {
|
|
295
|
+
await this.writeMessage({
|
|
296
|
+
jsonrpc: "2.0",
|
|
297
|
+
id,
|
|
298
|
+
error: {
|
|
299
|
+
code,
|
|
300
|
+
message
|
|
301
|
+
}
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
writeMessage(message) {
|
|
305
|
+
const body = JSON.stringify(message);
|
|
306
|
+
const payload = `Content-Length: ${Buffer.byteLength(body, "utf8")}\r\n\r\n${body}`;
|
|
307
|
+
return new Promise((resolve, reject) => {
|
|
308
|
+
this.writer.write(payload, (error) => {
|
|
309
|
+
if (error) {
|
|
310
|
+
reject(error);
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
resolve();
|
|
314
|
+
});
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
emitError(error) {
|
|
318
|
+
for (const handler of this.errorHandlers) handler(error);
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
function parseContentLength(headers) {
|
|
322
|
+
for (const line of headers.split("\r\n")) {
|
|
323
|
+
const separatorIndex = line.indexOf(":");
|
|
324
|
+
if (separatorIndex === -1) continue;
|
|
325
|
+
if (line.slice(0, separatorIndex).trim().toLowerCase() !== "content-length") continue;
|
|
326
|
+
const value = Number.parseInt(line.slice(separatorIndex + 1).trim(), 10);
|
|
327
|
+
return Number.isFinite(value) && value >= 0 ? value : null;
|
|
328
|
+
}
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
function isJsonRpcObject(value) {
|
|
332
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
333
|
+
}
|
|
334
|
+
function getMessageId(message) {
|
|
335
|
+
const id = message["id"];
|
|
336
|
+
if (typeof id === "number" || typeof id === "string" || id === null) return id;
|
|
337
|
+
}
|
|
338
|
+
function jsonRpcErrorToError(value) {
|
|
339
|
+
if (!isJsonRpcObject(value)) return /* @__PURE__ */ new Error("JSON-RPC request failed");
|
|
340
|
+
const message = typeof value["message"] === "string" ? value["message"] : "JSON-RPC request failed";
|
|
341
|
+
const error = new Error(message);
|
|
342
|
+
if (typeof value["code"] === "number") error.name = `JsonRpcError(${value["code"]})`;
|
|
343
|
+
return error;
|
|
344
|
+
}
|
|
345
|
+
function toError(error) {
|
|
346
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
347
|
+
}
|
|
348
|
+
//#endregion
|
|
349
|
+
//#region packages/lsp-core/src/lsp/process.ts
|
|
350
|
+
function isMissingProcessError(error) {
|
|
351
|
+
if (!(error instanceof Error) || !("code" in error)) return false;
|
|
352
|
+
return error.code === "ESRCH";
|
|
353
|
+
}
|
|
354
|
+
function reportKillError(context, error) {
|
|
355
|
+
if (!isMissingProcessError(error)) reportBestEffortCleanupError(context, error);
|
|
356
|
+
}
|
|
357
|
+
function validateCwd(cwd) {
|
|
358
|
+
try {
|
|
359
|
+
if (!existsSync(cwd)) return {
|
|
360
|
+
valid: false,
|
|
361
|
+
error: `Working directory does not exist: ${cwd}`
|
|
362
|
+
};
|
|
363
|
+
if (!statSync(cwd).isDirectory()) return {
|
|
364
|
+
valid: false,
|
|
365
|
+
error: `Path is not a directory: ${cwd}`
|
|
366
|
+
};
|
|
367
|
+
return { valid: true };
|
|
368
|
+
} catch (err) {
|
|
369
|
+
return {
|
|
370
|
+
valid: false,
|
|
371
|
+
error: `Cannot access working directory: ${cwd} (${err instanceof Error ? err.message : String(err)})`
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
function wrap(proc) {
|
|
376
|
+
const exitedPromise = new Promise((resolve) => {
|
|
377
|
+
proc.once("close", (code) => resolve(code ?? 0));
|
|
378
|
+
proc.once("error", () => resolve(1));
|
|
379
|
+
});
|
|
380
|
+
if (!proc.stdin || !proc.stdout || !proc.stderr) throw new LspProcessSpawnError("Spawned process is missing one of stdin/stdout/stderr pipes");
|
|
381
|
+
return {
|
|
382
|
+
stdin: proc.stdin,
|
|
383
|
+
stdout: proc.stdout,
|
|
384
|
+
stderr: proc.stderr,
|
|
385
|
+
get pid() {
|
|
386
|
+
return proc.pid ?? void 0;
|
|
387
|
+
},
|
|
388
|
+
get exitCode() {
|
|
389
|
+
return proc.exitCode;
|
|
390
|
+
},
|
|
391
|
+
get killed() {
|
|
392
|
+
return proc.killed;
|
|
393
|
+
},
|
|
394
|
+
exited: exitedPromise,
|
|
395
|
+
kill(signal) {
|
|
396
|
+
killProcessTree(proc, signal ?? "SIGTERM");
|
|
397
|
+
}
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
function killProcessTree(proc, signal) {
|
|
401
|
+
if (process.platform === "win32" && proc.pid) {
|
|
402
|
+
const result = spawnSync("taskkill", [
|
|
403
|
+
"/pid",
|
|
404
|
+
String(proc.pid),
|
|
405
|
+
"/f",
|
|
406
|
+
"/t"
|
|
407
|
+
], {
|
|
408
|
+
stdio: "ignore",
|
|
409
|
+
windowsHide: true
|
|
410
|
+
});
|
|
411
|
+
if (!result.error && result.status === 0) return;
|
|
412
|
+
if (result.error) reportKillError("windows process tree kill", result.error);
|
|
413
|
+
}
|
|
414
|
+
if (process.platform !== "win32" && proc.pid) try {
|
|
415
|
+
process.kill(-proc.pid, signal);
|
|
416
|
+
return;
|
|
417
|
+
} catch (error) {
|
|
418
|
+
reportKillError("process group kill", error);
|
|
419
|
+
}
|
|
420
|
+
try {
|
|
421
|
+
proc.kill(signal);
|
|
422
|
+
} catch (error) {
|
|
423
|
+
reportKillError("process kill", error);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
function isWindowsShellShim(command) {
|
|
427
|
+
const lowerCommand = command.toLowerCase();
|
|
428
|
+
return lowerCommand.endsWith(".cmd") || lowerCommand.endsWith(".bat");
|
|
429
|
+
}
|
|
430
|
+
function splitPath(pathValue, platform) {
|
|
431
|
+
const separator = platform === "win32" ? ";" : delimiter;
|
|
432
|
+
return pathValue.split(separator).filter(Boolean);
|
|
433
|
+
}
|
|
434
|
+
function getWindowsPathExtensions(env) {
|
|
435
|
+
const extensions = (env["PATHEXT"] ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension) => extension.trim()).filter(Boolean).map((extension) => extension.startsWith(".") ? extension : `.${extension}`);
|
|
436
|
+
return [...new Set([
|
|
437
|
+
...extensions,
|
|
438
|
+
".exe",
|
|
439
|
+
".cmd",
|
|
440
|
+
".bat",
|
|
441
|
+
""
|
|
442
|
+
])];
|
|
443
|
+
}
|
|
444
|
+
function resolveWindowsCommand(command, env) {
|
|
445
|
+
const hasPathSeparator = command.includes("/") || command.includes("\\");
|
|
446
|
+
const pathValue = env["PATH"] ?? env["Path"] ?? "";
|
|
447
|
+
const baseDirectories = hasPathSeparator ? [""] : splitPath(pathValue, "win32");
|
|
448
|
+
const extensions = getWindowsPathExtensions(env);
|
|
449
|
+
for (const baseDirectory of baseDirectories) for (const extension of extensions) {
|
|
450
|
+
const candidate = baseDirectory ? join(baseDirectory, `${command}${extension}`) : `${command}${extension}`;
|
|
451
|
+
if (existsSync(candidate)) return candidate;
|
|
452
|
+
}
|
|
453
|
+
return command;
|
|
454
|
+
}
|
|
455
|
+
function createSpawnCommand(command, platform = process.platform, commandProcessor = process.env["ComSpec"] ?? "cmd.exe", env = process.env) {
|
|
456
|
+
const [cmd, ...args] = command;
|
|
457
|
+
if (!cmd) throw new LspProcessSpawnError("[lsp] empty command");
|
|
458
|
+
if (platform !== "win32") return {
|
|
459
|
+
command: cmd,
|
|
460
|
+
args,
|
|
461
|
+
shell: false
|
|
462
|
+
};
|
|
463
|
+
const resolvedCommand = resolveWindowsCommand(cmd, env);
|
|
464
|
+
if (!isWindowsShellShim(resolvedCommand)) return {
|
|
465
|
+
command: resolvedCommand,
|
|
466
|
+
args,
|
|
467
|
+
shell: false
|
|
468
|
+
};
|
|
469
|
+
return {
|
|
470
|
+
command: commandProcessor,
|
|
471
|
+
args: [
|
|
472
|
+
"/d",
|
|
473
|
+
"/s",
|
|
474
|
+
"/c",
|
|
475
|
+
resolvedCommand,
|
|
476
|
+
...args
|
|
477
|
+
],
|
|
478
|
+
shell: false
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
function spawnProcess(command, options) {
|
|
482
|
+
const cwdValidation = validateCwd(options.cwd);
|
|
483
|
+
if (!cwdValidation.valid) throw new LspInvalidPathError(`[lsp] ${cwdValidation.error}`);
|
|
484
|
+
const [cmd] = command;
|
|
485
|
+
if (!cmd) throw new LspProcessSpawnError("[lsp] empty command");
|
|
486
|
+
const preparedCommand = createSpawnCommand(command, process.platform, process.env["ComSpec"] ?? "cmd.exe", options.env);
|
|
487
|
+
return wrap(spawn(preparedCommand.command, preparedCommand.args, {
|
|
488
|
+
cwd: options.cwd,
|
|
489
|
+
env: options.env,
|
|
490
|
+
stdio: [
|
|
491
|
+
"pipe",
|
|
492
|
+
"pipe",
|
|
493
|
+
"pipe"
|
|
494
|
+
],
|
|
495
|
+
windowsHide: true,
|
|
496
|
+
shell: preparedCommand.shell,
|
|
497
|
+
detached: process.platform !== "win32"
|
|
498
|
+
}));
|
|
499
|
+
}
|
|
500
|
+
//#endregion
|
|
501
|
+
//#region packages/lsp-core/src/lsp/transport.ts
|
|
502
|
+
function isRecord$3(value) {
|
|
503
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
504
|
+
}
|
|
505
|
+
function parseConfigurationItems(params) {
|
|
506
|
+
if (!isRecord$3(params) || !Array.isArray(params["items"])) return [];
|
|
507
|
+
const items = [];
|
|
508
|
+
for (const item of params["items"]) {
|
|
509
|
+
if (!isRecord$3(item)) continue;
|
|
510
|
+
const section = item["section"];
|
|
511
|
+
items.push(section === void 0 || typeof section !== "string" ? {} : { section });
|
|
512
|
+
}
|
|
513
|
+
return items;
|
|
514
|
+
}
|
|
515
|
+
function parseDiagnosticsParams(params) {
|
|
516
|
+
if (!isRecord$3(params) || typeof params["uri"] !== "string") return null;
|
|
517
|
+
const diagnostics = Array.isArray(params["diagnostics"]) ? params["diagnostics"].filter(isDiagnostic) : [];
|
|
518
|
+
return {
|
|
519
|
+
uri: params["uri"],
|
|
520
|
+
diagnostics
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
var LspClientTransport = class {
|
|
524
|
+
constructor(root, server, timeouts = {}) {
|
|
525
|
+
this.root = root;
|
|
526
|
+
this.server = server;
|
|
527
|
+
this.proc = null;
|
|
528
|
+
this.connection = null;
|
|
529
|
+
this.stderrBuffer = [];
|
|
530
|
+
this.processExited = false;
|
|
531
|
+
this.diagnosticsStore = /* @__PURE__ */ new Map();
|
|
532
|
+
this.requestTimeoutMs = timeouts.requestTimeoutMs ?? 15e3;
|
|
533
|
+
this.initializeTimeoutMs = timeouts.initializeTimeoutMs ?? 6e4;
|
|
534
|
+
}
|
|
535
|
+
pid() {
|
|
536
|
+
return this.proc?.pid;
|
|
537
|
+
}
|
|
538
|
+
command() {
|
|
539
|
+
return [...this.server.command];
|
|
540
|
+
}
|
|
541
|
+
async start() {
|
|
542
|
+
const env = createLspSpawnEnv(this.root, {
|
|
543
|
+
...process.env,
|
|
544
|
+
...this.server.env
|
|
545
|
+
});
|
|
546
|
+
this.proc = spawnProcess(this.server.command, {
|
|
547
|
+
cwd: this.root,
|
|
548
|
+
env
|
|
549
|
+
});
|
|
550
|
+
this.startStderrReading();
|
|
551
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
552
|
+
if (this.proc.exitCode !== null) {
|
|
553
|
+
const stderr = this.stderrBuffer.join("\n");
|
|
554
|
+
throw new LspProcessExitedError(this.server.id, this.root, this.proc.exitCode, stderr.slice(-2e3));
|
|
555
|
+
}
|
|
556
|
+
this.connection = new JsonRpcConnection(this.proc.stdout, this.proc.stdin);
|
|
557
|
+
this.connection.onNotification("textDocument/publishDiagnostics", (params) => {
|
|
558
|
+
const diagnosticsParams = parseDiagnosticsParams(params);
|
|
559
|
+
if (diagnosticsParams?.uri) this.diagnosticsStore.set(diagnosticsParams.uri, diagnosticsParams.diagnostics);
|
|
560
|
+
});
|
|
561
|
+
this.connection.onRequest("workspace/configuration", (params) => {
|
|
562
|
+
return parseConfigurationItems(params).map((item) => {
|
|
563
|
+
if (item.section === "json") return { validate: { enable: true } };
|
|
564
|
+
return {};
|
|
565
|
+
});
|
|
566
|
+
});
|
|
567
|
+
this.connection.onRequest("client/registerCapability", () => null);
|
|
568
|
+
this.connection.onRequest("window/workDoneProgress/create", () => null);
|
|
569
|
+
this.connection.onClose(() => {
|
|
570
|
+
this.processExited = true;
|
|
571
|
+
});
|
|
572
|
+
this.connection.onError((error) => {
|
|
573
|
+
reportBestEffortCleanupError("connection error notification", error);
|
|
574
|
+
});
|
|
575
|
+
this.connection.listen();
|
|
576
|
+
}
|
|
577
|
+
startStderrReading() {
|
|
578
|
+
if (!this.proc) return;
|
|
579
|
+
this.proc.stderr.setEncoding("utf-8");
|
|
580
|
+
this.proc.stderr.on("data", (chunk) => {
|
|
581
|
+
this.stderrBuffer.push(chunk);
|
|
582
|
+
if (this.stderrBuffer.length > 100) this.stderrBuffer.shift();
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
isConnectionClosedError(error) {
|
|
586
|
+
if (!(error instanceof Error)) return false;
|
|
587
|
+
return ("code" in error && typeof error.code === "string" ? error.code : void 0) === "ERR_STREAM_DESTROYED" || /connection closed|connection is disposed|stream was destroyed/i.test(error.message);
|
|
588
|
+
}
|
|
589
|
+
async sendRequest(method, ...args) {
|
|
590
|
+
if (!this.connection) throw new Error("LSP client not started");
|
|
591
|
+
if (this.processExited || this.proc && this.proc.exitCode !== null) {
|
|
592
|
+
const stderrTail = this.stderrBuffer.slice(-10).join("\n");
|
|
593
|
+
throw new LspProcessExitedError(this.server.id, this.root, this.proc?.exitCode ?? null, stderrTail || void 0);
|
|
594
|
+
}
|
|
595
|
+
const timeoutMs = args[1]?.timeoutMs ?? this.requestTimeoutMs;
|
|
596
|
+
let timeoutHandle = null;
|
|
597
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
598
|
+
timeoutHandle = setTimeout(() => {
|
|
599
|
+
reject(new LspRequestTimeoutError(method, this.stderrBuffer.slice(-5).join("\n") || void 0));
|
|
600
|
+
}, timeoutMs);
|
|
601
|
+
});
|
|
602
|
+
try {
|
|
603
|
+
const requestPromise = args.length === 0 ? this.connection.sendRequest(method) : this.connection.sendRequest(method, args[0]);
|
|
604
|
+
const result = await Promise.race([requestPromise, timeoutPromise]);
|
|
605
|
+
if (timeoutHandle !== null) clearTimeout(timeoutHandle);
|
|
606
|
+
return result;
|
|
607
|
+
} catch (error) {
|
|
608
|
+
if (timeoutHandle !== null) clearTimeout(timeoutHandle);
|
|
609
|
+
if (this.processExited || this.proc && this.proc.exitCode !== null) throw new LspProcessExitedError(this.server.id, this.root, this.proc?.exitCode ?? null, this.stderrBuffer.slice(-10).join("\n") || void 0);
|
|
610
|
+
if (this.isConnectionClosedError(error)) throw new LspConnectionClosedError(this.server.id, this.root, error.message);
|
|
611
|
+
throw error;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
async sendNotification(method, ...args) {
|
|
615
|
+
if (!this.connection) return;
|
|
616
|
+
if (this.processExited || this.proc && this.proc.exitCode !== null) return;
|
|
617
|
+
try {
|
|
618
|
+
if (args.length === 0) await this.connection.sendNotification(method);
|
|
619
|
+
else await this.connection.sendNotification(method, args[0]);
|
|
620
|
+
} catch (error) {
|
|
621
|
+
if (this.isConnectionClosedError(error)) throw new LspConnectionClosedError(this.server.id, this.root, error.message);
|
|
622
|
+
throw error;
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
isAlive() {
|
|
626
|
+
return this.proc !== null && !this.processExited && this.proc.exitCode === null;
|
|
627
|
+
}
|
|
628
|
+
async stop() {
|
|
629
|
+
if (this.connection) {
|
|
630
|
+
try {
|
|
631
|
+
await this.sendRequest("shutdown");
|
|
632
|
+
} catch (error) {
|
|
633
|
+
reportBestEffortCleanupError("shutdown request", error);
|
|
634
|
+
}
|
|
635
|
+
try {
|
|
636
|
+
await this.sendNotification("exit");
|
|
637
|
+
} catch (error) {
|
|
638
|
+
reportBestEffortCleanupError("exit notification", error);
|
|
639
|
+
}
|
|
640
|
+
try {
|
|
641
|
+
this.connection.dispose();
|
|
642
|
+
} catch (error) {
|
|
643
|
+
reportBestEffortCleanupError("connection dispose", error);
|
|
644
|
+
}
|
|
645
|
+
this.connection = null;
|
|
646
|
+
}
|
|
647
|
+
const proc = this.proc;
|
|
648
|
+
if (proc) {
|
|
649
|
+
this.proc = null;
|
|
650
|
+
let exitedBeforeTimeout = false;
|
|
651
|
+
try {
|
|
652
|
+
proc.kill();
|
|
653
|
+
let timeoutId;
|
|
654
|
+
const timeoutPromise = new Promise((resolve) => {
|
|
655
|
+
timeoutId = setTimeout(resolve, STOP_HARD_KILL_TIMEOUT_MS);
|
|
656
|
+
});
|
|
657
|
+
await Promise.race([proc.exited.then(() => {
|
|
658
|
+
exitedBeforeTimeout = true;
|
|
659
|
+
}).finally(() => {
|
|
660
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
661
|
+
}), timeoutPromise]);
|
|
662
|
+
if (!exitedBeforeTimeout) try {
|
|
663
|
+
proc.kill("SIGKILL");
|
|
664
|
+
await Promise.race([proc.exited, new Promise((resolve) => setTimeout(resolve, STOP_SIGKILL_GRACE_MS))]);
|
|
665
|
+
} catch (error) {
|
|
666
|
+
reportBestEffortCleanupError("hard process kill", error);
|
|
667
|
+
}
|
|
668
|
+
} catch (error) {
|
|
669
|
+
reportBestEffortCleanupError("process stop", error);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
this.processExited = true;
|
|
673
|
+
this.diagnosticsStore.clear();
|
|
674
|
+
}
|
|
675
|
+
getStoredDiagnostics(uri) {
|
|
676
|
+
return this.diagnosticsStore.get(uri) ?? [];
|
|
677
|
+
}
|
|
678
|
+
};
|
|
679
|
+
function createLspSpawnEnv(_root, input) {
|
|
680
|
+
return { ...input };
|
|
681
|
+
}
|
|
682
|
+
function isDiagnostic(value) {
|
|
683
|
+
return isRecord$3(value) && isRange(value["range"]) && typeof value["message"] === "string";
|
|
684
|
+
}
|
|
685
|
+
function isRange(value) {
|
|
686
|
+
return isRecord$3(value) && isPosition(value["start"]) && isPosition(value["end"]);
|
|
687
|
+
}
|
|
688
|
+
function isPosition(value) {
|
|
689
|
+
return isRecord$3(value) && typeof value["line"] === "number" && typeof value["character"] === "number";
|
|
690
|
+
}
|
|
691
|
+
//#endregion
|
|
692
|
+
//#region packages/lsp-core/src/lsp/connection.ts
|
|
693
|
+
var INITIALIZE_SETTLE_MS = 300;
|
|
694
|
+
var LspClientConnection = class extends LspClientTransport {
|
|
695
|
+
async initialize() {
|
|
696
|
+
const rootUri = pathToFileURL(this.root).href;
|
|
697
|
+
await this.sendRequest("initialize", {
|
|
698
|
+
processId: process.pid,
|
|
699
|
+
rootUri,
|
|
700
|
+
rootPath: this.root,
|
|
701
|
+
workspaceFolders: [{
|
|
702
|
+
uri: rootUri,
|
|
703
|
+
name: "workspace"
|
|
704
|
+
}],
|
|
705
|
+
capabilities: {
|
|
706
|
+
textDocument: {
|
|
707
|
+
hover: { contentFormat: ["markdown", "plaintext"] },
|
|
708
|
+
definition: { linkSupport: true },
|
|
709
|
+
references: {},
|
|
710
|
+
documentSymbol: { hierarchicalDocumentSymbolSupport: true },
|
|
711
|
+
publishDiagnostics: {},
|
|
712
|
+
rename: {
|
|
713
|
+
prepareSupport: true,
|
|
714
|
+
prepareSupportDefaultBehavior: 1,
|
|
715
|
+
honorsChangeAnnotations: true
|
|
716
|
+
},
|
|
717
|
+
codeAction: {
|
|
718
|
+
codeActionLiteralSupport: { codeActionKind: { valueSet: [
|
|
719
|
+
"quickfix",
|
|
720
|
+
"refactor",
|
|
721
|
+
"refactor.extract",
|
|
722
|
+
"refactor.inline",
|
|
723
|
+
"refactor.rewrite",
|
|
724
|
+
"source",
|
|
725
|
+
"source.organizeImports",
|
|
726
|
+
"source.fixAll"
|
|
727
|
+
] } },
|
|
728
|
+
isPreferredSupport: true,
|
|
729
|
+
disabledSupport: true,
|
|
730
|
+
dataSupport: true,
|
|
731
|
+
resolveSupport: { properties: ["edit", "command"] }
|
|
732
|
+
}
|
|
733
|
+
},
|
|
734
|
+
workspace: {
|
|
735
|
+
symbol: {},
|
|
736
|
+
workspaceFolders: true,
|
|
737
|
+
configuration: true,
|
|
738
|
+
applyEdit: true,
|
|
739
|
+
workspaceEdit: { documentChanges: true }
|
|
740
|
+
}
|
|
741
|
+
},
|
|
742
|
+
initializationOptions: this.server.initialization
|
|
743
|
+
}, { timeoutMs: this.initializeTimeoutMs });
|
|
744
|
+
await this.sendNotification("initialized");
|
|
745
|
+
await this.sendNotification("workspace/didChangeConfiguration", { settings: { json: { validate: { enable: true } } } });
|
|
746
|
+
await new Promise((r) => setTimeout(r, INITIALIZE_SETTLE_MS));
|
|
747
|
+
}
|
|
748
|
+
};
|
|
749
|
+
//#endregion
|
|
750
|
+
//#region packages/lsp-core/src/lsp/language-mappings.ts
|
|
751
|
+
var SYMBOL_KIND_MAP = {
|
|
752
|
+
1: "File",
|
|
753
|
+
2: "Module",
|
|
754
|
+
3: "Namespace",
|
|
755
|
+
4: "Package",
|
|
756
|
+
5: "Class",
|
|
757
|
+
6: "Method",
|
|
758
|
+
7: "Property",
|
|
759
|
+
8: "Field",
|
|
760
|
+
9: "Constructor",
|
|
761
|
+
10: "Enum",
|
|
762
|
+
11: "Interface",
|
|
763
|
+
12: "Function",
|
|
764
|
+
13: "Variable",
|
|
765
|
+
14: "Constant",
|
|
766
|
+
15: "String",
|
|
767
|
+
16: "Number",
|
|
768
|
+
17: "Boolean",
|
|
769
|
+
18: "Array",
|
|
770
|
+
19: "Object",
|
|
771
|
+
20: "Key",
|
|
772
|
+
21: "Null",
|
|
773
|
+
22: "EnumMember",
|
|
774
|
+
23: "Struct",
|
|
775
|
+
24: "Event",
|
|
776
|
+
25: "Operator",
|
|
777
|
+
26: "TypeParameter"
|
|
778
|
+
};
|
|
779
|
+
var SEVERITY_MAP = {
|
|
780
|
+
1: "error",
|
|
781
|
+
2: "warning",
|
|
782
|
+
3: "information",
|
|
783
|
+
4: "hint"
|
|
784
|
+
};
|
|
785
|
+
var EXT_TO_LANG = {
|
|
786
|
+
".abap": "abap",
|
|
787
|
+
".bat": "bat",
|
|
788
|
+
".bib": "bibtex",
|
|
789
|
+
".bibtex": "bibtex",
|
|
790
|
+
".clj": "clojure",
|
|
791
|
+
".cljs": "clojure",
|
|
792
|
+
".cljc": "clojure",
|
|
793
|
+
".edn": "clojure",
|
|
794
|
+
".coffee": "coffeescript",
|
|
795
|
+
".c": "c",
|
|
796
|
+
".cpp": "cpp",
|
|
797
|
+
".cxx": "cpp",
|
|
798
|
+
".cc": "cpp",
|
|
799
|
+
".c++": "cpp",
|
|
800
|
+
".cs": "csharp",
|
|
801
|
+
".css": "css",
|
|
802
|
+
".d": "d",
|
|
803
|
+
".pas": "pascal",
|
|
804
|
+
".pascal": "pascal",
|
|
805
|
+
".diff": "diff",
|
|
806
|
+
".patch": "diff",
|
|
807
|
+
".dart": "dart",
|
|
808
|
+
".dockerfile": "dockerfile",
|
|
809
|
+
".ex": "elixir",
|
|
810
|
+
".exs": "elixir",
|
|
811
|
+
".erl": "erlang",
|
|
812
|
+
".hrl": "erlang",
|
|
813
|
+
".fs": "fsharp",
|
|
814
|
+
".fsi": "fsharp",
|
|
815
|
+
".fsx": "fsharp",
|
|
816
|
+
".fsscript": "fsharp",
|
|
817
|
+
".gitcommit": "git-commit",
|
|
818
|
+
".gitrebase": "git-rebase",
|
|
819
|
+
".go": "go",
|
|
820
|
+
".groovy": "groovy",
|
|
821
|
+
".gleam": "gleam",
|
|
822
|
+
".hbs": "handlebars",
|
|
823
|
+
".handlebars": "handlebars",
|
|
824
|
+
".hs": "haskell",
|
|
825
|
+
".html": "html",
|
|
826
|
+
".htm": "html",
|
|
827
|
+
".ini": "ini",
|
|
828
|
+
".java": "java",
|
|
829
|
+
".jl": "julia",
|
|
830
|
+
".js": "javascript",
|
|
831
|
+
".jsx": "javascriptreact",
|
|
832
|
+
".json": "json",
|
|
833
|
+
".jsonc": "jsonc",
|
|
834
|
+
".tex": "latex",
|
|
835
|
+
".latex": "latex",
|
|
836
|
+
".less": "less",
|
|
837
|
+
".lua": "lua",
|
|
838
|
+
".makefile": "makefile",
|
|
839
|
+
makefile: "makefile",
|
|
840
|
+
".md": "markdown",
|
|
841
|
+
".markdown": "markdown",
|
|
842
|
+
".m": "objective-c",
|
|
843
|
+
".mm": "objective-cpp",
|
|
844
|
+
".pl": "perl",
|
|
845
|
+
".pm": "perl",
|
|
846
|
+
".pm6": "perl6",
|
|
847
|
+
".php": "php",
|
|
848
|
+
".ps1": "powershell",
|
|
849
|
+
".psm1": "powershell",
|
|
850
|
+
".pug": "jade",
|
|
851
|
+
".jade": "jade",
|
|
852
|
+
".py": "python",
|
|
853
|
+
".pyi": "python",
|
|
854
|
+
".r": "r",
|
|
855
|
+
".cshtml": "razor",
|
|
856
|
+
".razor": "razor",
|
|
857
|
+
".rb": "ruby",
|
|
858
|
+
".rake": "ruby",
|
|
859
|
+
".gemspec": "ruby",
|
|
860
|
+
".ru": "ruby",
|
|
861
|
+
".erb": "erb",
|
|
862
|
+
".html.erb": "erb",
|
|
863
|
+
".js.erb": "erb",
|
|
864
|
+
".css.erb": "erb",
|
|
865
|
+
".json.erb": "erb",
|
|
866
|
+
".rs": "rust",
|
|
867
|
+
".scss": "scss",
|
|
868
|
+
".sass": "sass",
|
|
869
|
+
".scala": "scala",
|
|
870
|
+
".shader": "shaderlab",
|
|
871
|
+
".sh": "shellscript",
|
|
872
|
+
".bash": "shellscript",
|
|
873
|
+
".zsh": "shellscript",
|
|
874
|
+
".ksh": "shellscript",
|
|
875
|
+
".sql": "sql",
|
|
876
|
+
".svelte": "svelte",
|
|
877
|
+
".swift": "swift",
|
|
878
|
+
".ts": "typescript",
|
|
879
|
+
".tsx": "typescriptreact",
|
|
880
|
+
".mts": "typescript",
|
|
881
|
+
".cts": "typescript",
|
|
882
|
+
".mtsx": "typescriptreact",
|
|
883
|
+
".ctsx": "typescriptreact",
|
|
884
|
+
".xml": "xml",
|
|
885
|
+
".xsl": "xsl",
|
|
886
|
+
".yaml": "yaml",
|
|
887
|
+
".yml": "yaml",
|
|
888
|
+
".mjs": "javascript",
|
|
889
|
+
".cjs": "javascript",
|
|
890
|
+
".vue": "vue",
|
|
891
|
+
".zig": "zig",
|
|
892
|
+
".zon": "zig",
|
|
893
|
+
".astro": "astro",
|
|
894
|
+
".ml": "ocaml",
|
|
895
|
+
".mli": "ocaml",
|
|
896
|
+
".tf": "terraform",
|
|
897
|
+
".tfvars": "terraform-vars",
|
|
898
|
+
".hcl": "hcl",
|
|
899
|
+
".nix": "nix",
|
|
900
|
+
".typ": "typst",
|
|
901
|
+
".typc": "typst",
|
|
902
|
+
".ets": "typescript",
|
|
903
|
+
".lhs": "haskell",
|
|
904
|
+
".kt": "kotlin",
|
|
905
|
+
".kts": "kotlin",
|
|
906
|
+
".prisma": "prisma",
|
|
907
|
+
".h": "c",
|
|
908
|
+
".hpp": "cpp",
|
|
909
|
+
".hh": "cpp",
|
|
910
|
+
".hxx": "cpp",
|
|
911
|
+
".h++": "cpp",
|
|
912
|
+
".objc": "objective-c",
|
|
913
|
+
".objcpp": "objective-cpp",
|
|
914
|
+
".fish": "fish",
|
|
915
|
+
".graphql": "graphql",
|
|
916
|
+
".gql": "graphql"
|
|
917
|
+
};
|
|
918
|
+
function getLanguageId(ext) {
|
|
919
|
+
return EXT_TO_LANG[ext] ?? "plaintext";
|
|
920
|
+
}
|
|
921
|
+
//#endregion
|
|
922
|
+
//#region packages/lsp-core/src/lsp/client.ts
|
|
923
|
+
var POST_OPEN_DELAY_MS = 1e3;
|
|
924
|
+
var POST_DIAGNOSTICS_WAIT_MS = 500;
|
|
925
|
+
var LspClient = class extends LspClientConnection {
|
|
926
|
+
constructor(..._args) {
|
|
927
|
+
super(..._args);
|
|
928
|
+
this.openedFiles = /* @__PURE__ */ new Set();
|
|
929
|
+
this.documentVersions = /* @__PURE__ */ new Map();
|
|
930
|
+
this.lastSyncedText = /* @__PURE__ */ new Map();
|
|
931
|
+
this.diagnosticPullErrors = [];
|
|
932
|
+
}
|
|
933
|
+
getDiagnosticPullErrors() {
|
|
934
|
+
return this.diagnosticPullErrors;
|
|
935
|
+
}
|
|
936
|
+
async openFile(filePath) {
|
|
937
|
+
const absPath = resolve(contextCwd(), filePath);
|
|
938
|
+
const uri = pathToFileURL(absPath).href;
|
|
939
|
+
const text = readFileSync(absPath, "utf-8");
|
|
940
|
+
if (!this.openedFiles.has(absPath)) {
|
|
941
|
+
const languageId = getLanguageId(effectiveExtension(absPath));
|
|
942
|
+
const version = 1;
|
|
943
|
+
await this.sendNotification("textDocument/didOpen", { textDocument: {
|
|
944
|
+
uri,
|
|
945
|
+
languageId,
|
|
946
|
+
version,
|
|
947
|
+
text
|
|
948
|
+
} });
|
|
949
|
+
this.openedFiles.add(absPath);
|
|
950
|
+
this.documentVersions.set(uri, version);
|
|
951
|
+
this.lastSyncedText.set(uri, text);
|
|
952
|
+
await new Promise((r) => setTimeout(r, POST_OPEN_DELAY_MS));
|
|
953
|
+
return;
|
|
954
|
+
}
|
|
955
|
+
if (this.lastSyncedText.get(uri) === text) return;
|
|
956
|
+
const nextVersion = (this.documentVersions.get(uri) ?? 1) + 1;
|
|
957
|
+
this.documentVersions.set(uri, nextVersion);
|
|
958
|
+
this.lastSyncedText.set(uri, text);
|
|
959
|
+
await this.sendNotification("textDocument/didChange", {
|
|
960
|
+
textDocument: {
|
|
961
|
+
uri,
|
|
962
|
+
version: nextVersion
|
|
963
|
+
},
|
|
964
|
+
contentChanges: [{ text }]
|
|
965
|
+
});
|
|
966
|
+
await this.sendNotification("textDocument/didSave", {
|
|
967
|
+
textDocument: { uri },
|
|
968
|
+
text
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
async definition(filePath, line, character) {
|
|
972
|
+
const absPath = resolve(contextCwd(), filePath);
|
|
973
|
+
await this.openFile(absPath);
|
|
974
|
+
return this.sendRequest("textDocument/definition", {
|
|
975
|
+
textDocument: { uri: pathToFileURL(absPath).href },
|
|
976
|
+
position: {
|
|
977
|
+
line: line - 1,
|
|
978
|
+
character
|
|
979
|
+
}
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
async references(filePath, line, character, includeDeclaration = true) {
|
|
983
|
+
const absPath = resolve(contextCwd(), filePath);
|
|
984
|
+
await this.openFile(absPath);
|
|
985
|
+
return this.sendRequest("textDocument/references", {
|
|
986
|
+
textDocument: { uri: pathToFileURL(absPath).href },
|
|
987
|
+
position: {
|
|
988
|
+
line: line - 1,
|
|
989
|
+
character
|
|
990
|
+
},
|
|
991
|
+
context: { includeDeclaration }
|
|
992
|
+
});
|
|
993
|
+
}
|
|
994
|
+
async documentSymbols(filePath) {
|
|
995
|
+
const absPath = resolve(contextCwd(), filePath);
|
|
996
|
+
await this.openFile(absPath);
|
|
997
|
+
return this.sendRequest("textDocument/documentSymbol", { textDocument: { uri: pathToFileURL(absPath).href } });
|
|
998
|
+
}
|
|
999
|
+
async workspaceSymbols(query) {
|
|
1000
|
+
return this.sendRequest("workspace/symbol", { query });
|
|
1001
|
+
}
|
|
1002
|
+
isUnsupportedDiagnosticPullError(error) {
|
|
1003
|
+
if (!(error instanceof Error)) return false;
|
|
1004
|
+
if (("code" in error && typeof error.code === "number" ? error.code : void 0) === -32601) return true;
|
|
1005
|
+
return /unsupported|not supported|method not found|unknown request/i.test(error.message);
|
|
1006
|
+
}
|
|
1007
|
+
async diagnostics(filePath) {
|
|
1008
|
+
const absPath = resolve(contextCwd(), filePath);
|
|
1009
|
+
const uri = pathToFileURL(absPath).href;
|
|
1010
|
+
await this.openFile(absPath);
|
|
1011
|
+
await new Promise((r) => setTimeout(r, POST_DIAGNOSTICS_WAIT_MS));
|
|
1012
|
+
try {
|
|
1013
|
+
const result = await this.sendRequest("textDocument/diagnostic", { textDocument: { uri } });
|
|
1014
|
+
if (result.items) return { items: result.items };
|
|
1015
|
+
} catch (error) {
|
|
1016
|
+
if (!this.isUnsupportedDiagnosticPullError(error)) this.diagnosticPullErrors.push(error instanceof Error ? error : new Error(String(error)));
|
|
1017
|
+
}
|
|
1018
|
+
return { items: this.getStoredDiagnostics(uri) };
|
|
1019
|
+
}
|
|
1020
|
+
async prepareRename(filePath, line, character) {
|
|
1021
|
+
const absPath = resolve(contextCwd(), filePath);
|
|
1022
|
+
await this.openFile(absPath);
|
|
1023
|
+
return this.sendRequest("textDocument/prepareRename", {
|
|
1024
|
+
textDocument: { uri: pathToFileURL(absPath).href },
|
|
1025
|
+
position: {
|
|
1026
|
+
line: line - 1,
|
|
1027
|
+
character
|
|
1028
|
+
}
|
|
1029
|
+
});
|
|
1030
|
+
}
|
|
1031
|
+
async rename(filePath, line, character, newName) {
|
|
1032
|
+
const absPath = resolve(contextCwd(), filePath);
|
|
1033
|
+
await this.openFile(absPath);
|
|
1034
|
+
return this.sendRequest("textDocument/rename", {
|
|
1035
|
+
textDocument: { uri: pathToFileURL(absPath).href },
|
|
1036
|
+
position: {
|
|
1037
|
+
line: line - 1,
|
|
1038
|
+
character
|
|
1039
|
+
},
|
|
1040
|
+
newName
|
|
1041
|
+
});
|
|
1042
|
+
}
|
|
1043
|
+
};
|
|
1044
|
+
//#endregion
|
|
1045
|
+
//#region packages/lsp-core/src/lsp/process-signal-cleanup.ts
|
|
1046
|
+
function installProcessSignalCleanup(cleanup) {
|
|
1047
|
+
const signals = process.platform === "win32" ? [
|
|
1048
|
+
"SIGINT",
|
|
1049
|
+
"SIGTERM",
|
|
1050
|
+
"SIGBREAK"
|
|
1051
|
+
] : ["SIGINT", "SIGTERM"];
|
|
1052
|
+
const handler = () => {
|
|
1053
|
+
cleanup().catch((error) => {
|
|
1054
|
+
reportBestEffortCleanupError("signal cleanup", error);
|
|
1055
|
+
});
|
|
1056
|
+
};
|
|
1057
|
+
for (const signal of signals) process.on(signal, handler);
|
|
1058
|
+
return () => {
|
|
1059
|
+
for (const signal of signals) process.removeListener(signal, handler);
|
|
1060
|
+
};
|
|
1061
|
+
}
|
|
1062
|
+
//#endregion
|
|
1063
|
+
//#region packages/lsp-core/src/lsp/manager.ts
|
|
1064
|
+
async function stopClientBestEffort(client) {
|
|
1065
|
+
try {
|
|
1066
|
+
await client.stop();
|
|
1067
|
+
} catch (error) {
|
|
1068
|
+
reportBestEffortCleanupError("client stop", error);
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
function awaitWithSignal(promise, signal) {
|
|
1072
|
+
if (!signal) return promise;
|
|
1073
|
+
return new Promise((resolve, reject) => {
|
|
1074
|
+
let settled = false;
|
|
1075
|
+
const onAbort = () => {
|
|
1076
|
+
if (settled) return;
|
|
1077
|
+
settled = true;
|
|
1078
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
1079
|
+
};
|
|
1080
|
+
if (signal.aborted) {
|
|
1081
|
+
onAbort();
|
|
1082
|
+
return;
|
|
1083
|
+
}
|
|
1084
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1085
|
+
promise.then((value) => {
|
|
1086
|
+
if (settled) return;
|
|
1087
|
+
settled = true;
|
|
1088
|
+
signal.removeEventListener("abort", onAbort);
|
|
1089
|
+
resolve(value);
|
|
1090
|
+
}, (err) => {
|
|
1091
|
+
if (settled) return;
|
|
1092
|
+
settled = true;
|
|
1093
|
+
signal.removeEventListener("abort", onAbort);
|
|
1094
|
+
reject(err);
|
|
1095
|
+
});
|
|
1096
|
+
});
|
|
1097
|
+
}
|
|
1098
|
+
var LspManager = class {
|
|
1099
|
+
constructor(options = {}) {
|
|
1100
|
+
this.clients = /* @__PURE__ */ new Map();
|
|
1101
|
+
this.reaperHandle = null;
|
|
1102
|
+
this.signalDisposer = null;
|
|
1103
|
+
this.disposed = false;
|
|
1104
|
+
this.idleTimeoutMs = options.idleTimeoutMs ?? 3e5;
|
|
1105
|
+
this.initTimeoutMs = options.initTimeoutMs ?? 6e4;
|
|
1106
|
+
this.reaperIntervalMs = options.reaperIntervalMs ?? 6e4;
|
|
1107
|
+
this.clientFactory = options.clientFactory ?? ((root, server) => new LspClient(root, server));
|
|
1108
|
+
this.now = options.now ?? (() => Date.now());
|
|
1109
|
+
this.startReaper();
|
|
1110
|
+
this.signalDisposer = installProcessSignalCleanup(() => this.stopAll());
|
|
1111
|
+
}
|
|
1112
|
+
startReaper() {
|
|
1113
|
+
if (this.reaperHandle) return;
|
|
1114
|
+
this.reaperHandle = setInterval(() => {
|
|
1115
|
+
this.reapStale();
|
|
1116
|
+
}, this.reaperIntervalMs);
|
|
1117
|
+
if (typeof this.reaperHandle.unref === "function") this.reaperHandle.unref();
|
|
1118
|
+
}
|
|
1119
|
+
getKey(root, serverId) {
|
|
1120
|
+
return `${root}::${serverId}`;
|
|
1121
|
+
}
|
|
1122
|
+
reapStale() {
|
|
1123
|
+
const t = this.now();
|
|
1124
|
+
for (const [key, managed] of this.clients) {
|
|
1125
|
+
if (managed.isInitializing && managed.initializingSince !== null && t - managed.initializingSince > this.initTimeoutMs) {
|
|
1126
|
+
stopClientBestEffort(managed.client);
|
|
1127
|
+
this.clients.delete(key);
|
|
1128
|
+
continue;
|
|
1129
|
+
}
|
|
1130
|
+
if (!managed.isInitializing && managed.refCount === 0 && managed.pendingWaiters === 0 && t - managed.lastUsedAt > this.idleTimeoutMs) {
|
|
1131
|
+
stopClientBestEffort(managed.client);
|
|
1132
|
+
this.clients.delete(key);
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
async tryDeleteIfOrphaned(key, managed) {
|
|
1137
|
+
if (managed.refCount === 0 && managed.pendingWaiters === 0 && !managed.isInitializing && this.clients.get(key) === managed) {
|
|
1138
|
+
this.clients.delete(key);
|
|
1139
|
+
await stopClientBestEffort(managed.client);
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
async getClient(root, server, signal) {
|
|
1143
|
+
if (this.disposed) throw new Error("LspManager has been disposed");
|
|
1144
|
+
signal?.throwIfAborted();
|
|
1145
|
+
const key = this.getKey(root, server.id);
|
|
1146
|
+
let managed = this.clients.get(key);
|
|
1147
|
+
if (managed) {
|
|
1148
|
+
const t = this.now();
|
|
1149
|
+
if (managed.isInitializing && managed.initializingSince !== null && t - managed.initializingSince > this.initTimeoutMs) {
|
|
1150
|
+
await stopClientBestEffort(managed.client);
|
|
1151
|
+
this.clients.delete(key);
|
|
1152
|
+
managed = void 0;
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
if (managed) {
|
|
1156
|
+
if (managed.initPromise) {
|
|
1157
|
+
managed.pendingWaiters++;
|
|
1158
|
+
try {
|
|
1159
|
+
await awaitWithSignal(managed.initPromise, signal);
|
|
1160
|
+
} catch (err) {
|
|
1161
|
+
managed.pendingWaiters--;
|
|
1162
|
+
await this.tryDeleteIfOrphaned(key, managed);
|
|
1163
|
+
throw err;
|
|
1164
|
+
}
|
|
1165
|
+
managed.pendingWaiters--;
|
|
1166
|
+
}
|
|
1167
|
+
if (signal?.aborted) {
|
|
1168
|
+
await this.tryDeleteIfOrphaned(key, managed);
|
|
1169
|
+
signal.throwIfAborted();
|
|
1170
|
+
}
|
|
1171
|
+
if (!managed.client.isAlive()) {
|
|
1172
|
+
await stopClientBestEffort(managed.client);
|
|
1173
|
+
this.clients.delete(key);
|
|
1174
|
+
return this.getClient(root, server, signal);
|
|
1175
|
+
}
|
|
1176
|
+
managed.refCount++;
|
|
1177
|
+
managed.lastUsedAt = this.now();
|
|
1178
|
+
return managed.client;
|
|
1179
|
+
}
|
|
1180
|
+
const client = this.clientFactory(root, server);
|
|
1181
|
+
const initStartedAt = this.now();
|
|
1182
|
+
const initPromise = (async () => {
|
|
1183
|
+
await client.start();
|
|
1184
|
+
await client.initialize();
|
|
1185
|
+
})();
|
|
1186
|
+
const newManaged = {
|
|
1187
|
+
client,
|
|
1188
|
+
refCount: 0,
|
|
1189
|
+
pendingWaiters: 1,
|
|
1190
|
+
lastUsedAt: initStartedAt,
|
|
1191
|
+
initPromise,
|
|
1192
|
+
isInitializing: true,
|
|
1193
|
+
initializingSince: initStartedAt
|
|
1194
|
+
};
|
|
1195
|
+
this.clients.set(key, newManaged);
|
|
1196
|
+
try {
|
|
1197
|
+
await awaitWithSignal(initPromise, signal);
|
|
1198
|
+
} catch (err) {
|
|
1199
|
+
newManaged.pendingWaiters--;
|
|
1200
|
+
if (this.clients.get(key) === newManaged) this.clients.delete(key);
|
|
1201
|
+
await stopClientBestEffort(client);
|
|
1202
|
+
throw err;
|
|
1203
|
+
}
|
|
1204
|
+
newManaged.pendingWaiters--;
|
|
1205
|
+
newManaged.isInitializing = false;
|
|
1206
|
+
newManaged.initializingSince = null;
|
|
1207
|
+
newManaged.initPromise = null;
|
|
1208
|
+
if (signal?.aborted) {
|
|
1209
|
+
await this.tryDeleteIfOrphaned(key, newManaged);
|
|
1210
|
+
signal.throwIfAborted();
|
|
1211
|
+
}
|
|
1212
|
+
newManaged.refCount++;
|
|
1213
|
+
newManaged.lastUsedAt = this.now();
|
|
1214
|
+
return client;
|
|
1215
|
+
}
|
|
1216
|
+
releaseClient(root, serverId) {
|
|
1217
|
+
const key = this.getKey(root, serverId);
|
|
1218
|
+
const managed = this.clients.get(key);
|
|
1219
|
+
if (managed && managed.refCount > 0) {
|
|
1220
|
+
managed.refCount--;
|
|
1221
|
+
managed.lastUsedAt = this.now();
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
invalidateClient(root, serverId, client) {
|
|
1225
|
+
const key = this.getKey(root, serverId);
|
|
1226
|
+
const managed = this.clients.get(key);
|
|
1227
|
+
if (!managed) return;
|
|
1228
|
+
if (client && managed.client !== client) return;
|
|
1229
|
+
this.clients.delete(key);
|
|
1230
|
+
stopClientBestEffort(managed.client);
|
|
1231
|
+
}
|
|
1232
|
+
warmupClient(root, server) {
|
|
1233
|
+
if (this.disposed) return;
|
|
1234
|
+
const key = this.getKey(root, server.id);
|
|
1235
|
+
if (this.clients.has(key)) return;
|
|
1236
|
+
const client = this.clientFactory(root, server);
|
|
1237
|
+
const initStartedAt = this.now();
|
|
1238
|
+
const initPromise = (async () => {
|
|
1239
|
+
await client.start();
|
|
1240
|
+
await client.initialize();
|
|
1241
|
+
})();
|
|
1242
|
+
const managed = {
|
|
1243
|
+
client,
|
|
1244
|
+
refCount: 0,
|
|
1245
|
+
pendingWaiters: 0,
|
|
1246
|
+
lastUsedAt: initStartedAt,
|
|
1247
|
+
initPromise,
|
|
1248
|
+
isInitializing: true,
|
|
1249
|
+
initializingSince: initStartedAt
|
|
1250
|
+
};
|
|
1251
|
+
this.clients.set(key, managed);
|
|
1252
|
+
initPromise.then(() => {
|
|
1253
|
+
managed.isInitializing = false;
|
|
1254
|
+
managed.initializingSince = null;
|
|
1255
|
+
managed.initPromise = null;
|
|
1256
|
+
managed.lastUsedAt = this.now();
|
|
1257
|
+
}, () => {
|
|
1258
|
+
if (this.clients.get(key) === managed) this.clients.delete(key);
|
|
1259
|
+
stopClientBestEffort(client);
|
|
1260
|
+
});
|
|
1261
|
+
}
|
|
1262
|
+
isServerInitializing(root, serverId) {
|
|
1263
|
+
return this.clients.get(this.getKey(root, serverId))?.isInitializing ?? false;
|
|
1264
|
+
}
|
|
1265
|
+
getSnapshot() {
|
|
1266
|
+
const snapshots = [];
|
|
1267
|
+
for (const [key, managed] of this.clients) {
|
|
1268
|
+
const [root, serverId] = key.split("::");
|
|
1269
|
+
snapshots.push({
|
|
1270
|
+
root,
|
|
1271
|
+
serverId,
|
|
1272
|
+
refCount: managed.refCount,
|
|
1273
|
+
pendingWaiters: managed.pendingWaiters,
|
|
1274
|
+
lastUsedAt: managed.lastUsedAt,
|
|
1275
|
+
isInitializing: managed.isInitializing,
|
|
1276
|
+
alive: managed.client.isAlive(),
|
|
1277
|
+
command: managed.client.command()
|
|
1278
|
+
});
|
|
1279
|
+
}
|
|
1280
|
+
return snapshots;
|
|
1281
|
+
}
|
|
1282
|
+
hasClient(root, serverId) {
|
|
1283
|
+
return this.clients.has(this.getKey(root, serverId));
|
|
1284
|
+
}
|
|
1285
|
+
clientCount() {
|
|
1286
|
+
return this.clients.size;
|
|
1287
|
+
}
|
|
1288
|
+
async stopAll() {
|
|
1289
|
+
this.disposed = true;
|
|
1290
|
+
if (this.reaperHandle) {
|
|
1291
|
+
clearInterval(this.reaperHandle);
|
|
1292
|
+
this.reaperHandle = null;
|
|
1293
|
+
}
|
|
1294
|
+
if (this.signalDisposer) {
|
|
1295
|
+
this.signalDisposer();
|
|
1296
|
+
this.signalDisposer = null;
|
|
1297
|
+
}
|
|
1298
|
+
const stopPromises = [];
|
|
1299
|
+
for (const managed of this.clients.values()) stopPromises.push(stopClientBestEffort(managed.client));
|
|
1300
|
+
this.clients.clear();
|
|
1301
|
+
await Promise.allSettled(stopPromises);
|
|
1302
|
+
}
|
|
1303
|
+
};
|
|
1304
|
+
var _defaultInstance = null;
|
|
1305
|
+
function getLspManager() {
|
|
1306
|
+
if (!_defaultInstance) _defaultInstance = new LspManager();
|
|
1307
|
+
return _defaultInstance;
|
|
1308
|
+
}
|
|
1309
|
+
async function disposeDefaultLspManager() {
|
|
1310
|
+
if (_defaultInstance) {
|
|
1311
|
+
const m = _defaultInstance;
|
|
1312
|
+
_defaultInstance = null;
|
|
1313
|
+
await m.stopAll();
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
//#endregion
|
|
1317
|
+
//#region packages/lsp-core/src/lsp/server-install-state.ts
|
|
1318
|
+
function getInstallDecisionsPath() {
|
|
1319
|
+
const override = contextEnv("LSP_TOOLS_MCP_INSTALL_DECISIONS");
|
|
1320
|
+
if (!override) return join(homedir(), ".codex", "lsp-install-decisions.json");
|
|
1321
|
+
return isAbsolute(override) ? override : join(homedir(), override);
|
|
1322
|
+
}
|
|
1323
|
+
function loadInstallDecisions() {
|
|
1324
|
+
const path = getInstallDecisionsPath();
|
|
1325
|
+
if (!existsSync(path)) return {};
|
|
1326
|
+
try {
|
|
1327
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
1328
|
+
return isInstallDecisions(parsed) ? parsed : {};
|
|
1329
|
+
} catch {
|
|
1330
|
+
return {};
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
function loadInstallDecision(serverId) {
|
|
1334
|
+
return loadInstallDecisions()[serverId];
|
|
1335
|
+
}
|
|
1336
|
+
function recordInstallDecision(serverId, decision, decidedAt = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
1337
|
+
const decisions = loadInstallDecisions();
|
|
1338
|
+
decisions[serverId] = {
|
|
1339
|
+
decision,
|
|
1340
|
+
decidedAt
|
|
1341
|
+
};
|
|
1342
|
+
writeInstallDecisions(decisions);
|
|
1343
|
+
}
|
|
1344
|
+
function isInstallDecision(value) {
|
|
1345
|
+
return value === "declined" || value === "allowed";
|
|
1346
|
+
}
|
|
1347
|
+
function writeInstallDecisions(decisions) {
|
|
1348
|
+
const path = getInstallDecisionsPath();
|
|
1349
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
1350
|
+
const tmpPath = `${path}.tmp`;
|
|
1351
|
+
writeFileSync(tmpPath, `${JSON.stringify(decisions, null, 2)}\n`, "utf8");
|
|
1352
|
+
renameSync(tmpPath, path);
|
|
1353
|
+
}
|
|
1354
|
+
function isInstallDecisions(value) {
|
|
1355
|
+
return isRecord$2(value) && Object.values(value).every(isInstallDecisionRecord);
|
|
1356
|
+
}
|
|
1357
|
+
function isInstallDecisionRecord(value) {
|
|
1358
|
+
if (!isRecord$2(value)) return false;
|
|
1359
|
+
return isInstallDecision(value["decision"]) && typeof value["decidedAt"] === "string";
|
|
1360
|
+
}
|
|
1361
|
+
function isRecord$2(value) {
|
|
1362
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1363
|
+
}
|
|
1364
|
+
//#endregion
|
|
1365
|
+
//#region packages/lsp-core/src/lsp/server-definitions.ts
|
|
1366
|
+
var LSP_INSTALL_HINTS = {
|
|
1367
|
+
typescript: "npm install -g typescript-language-server typescript",
|
|
1368
|
+
deno: "Install Deno from https://deno.land",
|
|
1369
|
+
vue: "npm install -g @vue/language-server",
|
|
1370
|
+
eslint: "npm install -g vscode-langservers-extracted",
|
|
1371
|
+
oxlint: "npm install -g oxlint",
|
|
1372
|
+
biome: "npm install -g @biomejs/biome",
|
|
1373
|
+
gopls: "go install golang.org/x/tools/gopls@latest",
|
|
1374
|
+
"ruby-lsp": "gem install ruby-lsp",
|
|
1375
|
+
basedpyright: "pip install basedpyright",
|
|
1376
|
+
pyright: "pip install pyright",
|
|
1377
|
+
ty: "pip install ty",
|
|
1378
|
+
ruff: "pip install ruff",
|
|
1379
|
+
"elixir-ls": "See https://github.com/elixir-lsp/elixir-ls",
|
|
1380
|
+
zls: "See https://github.com/zigtools/zls",
|
|
1381
|
+
csharp: "dotnet tool install -g csharp-ls",
|
|
1382
|
+
fsharp: "dotnet tool install -g fsautocomplete",
|
|
1383
|
+
"sourcekit-lsp": "Included with Xcode or Swift toolchain",
|
|
1384
|
+
rust: "Install rust-analyzer and ensure it is in PATH. If using rustup: rustup component add rust-analyzer. If rust-analyzer exits while loading rust-src: rustup component remove rust-src && rustup component add rust-src.",
|
|
1385
|
+
clangd: "See https://clangd.llvm.org/installation",
|
|
1386
|
+
svelte: "npm install -g svelte-language-server",
|
|
1387
|
+
astro: "npm install -g @astrojs/language-server",
|
|
1388
|
+
"bash-ls": "npm install -g bash-language-server",
|
|
1389
|
+
jdtls: "See https://github.com/eclipse-jdtls/eclipse.jdt.ls",
|
|
1390
|
+
"yaml-ls": "npm install -g yaml-language-server",
|
|
1391
|
+
"lua-ls": "See https://github.com/LuaLS/lua-language-server",
|
|
1392
|
+
php: "npm install -g intelephense",
|
|
1393
|
+
dart: "Included with Dart SDK",
|
|
1394
|
+
"terraform-ls": "See https://github.com/hashicorp/terraform-ls",
|
|
1395
|
+
terraform: "See https://github.com/hashicorp/terraform-ls",
|
|
1396
|
+
prisma: "npm install -g prisma",
|
|
1397
|
+
"ocaml-lsp": "opam install ocaml-lsp-server",
|
|
1398
|
+
texlab: "See https://github.com/latex-lsp/texlab",
|
|
1399
|
+
dockerfile: "npm install -g dockerfile-language-server-nodejs",
|
|
1400
|
+
gleam: "See https://gleam.run/getting-started/installing/",
|
|
1401
|
+
"clojure-lsp": "See https://clojure-lsp.io/installation/",
|
|
1402
|
+
nixd: "nix profile install nixpkgs#nixd",
|
|
1403
|
+
tinymist: "See https://github.com/Myriad-Dreamin/tinymist",
|
|
1404
|
+
"haskell-language-server": "ghcup install hls",
|
|
1405
|
+
bash: "npm install -g bash-language-server",
|
|
1406
|
+
"kotlin-ls": "See https://github.com/Kotlin/kotlin-lsp",
|
|
1407
|
+
julials: "julia -e 'using Pkg; Pkg.add(\"LanguageServer\")'",
|
|
1408
|
+
razor: "Razor runs through the Roslyn language server (cohosting). Install: dotnet tool install -g roslyn-language-server --prerelease (requires v5.8.0+). See https://github.com/dotnet/razor"
|
|
1409
|
+
};
|
|
1410
|
+
var BUILTIN_SERVERS = {
|
|
1411
|
+
typescript: {
|
|
1412
|
+
command: ["typescript-language-server", "--stdio"],
|
|
1413
|
+
extensions: [
|
|
1414
|
+
".ts",
|
|
1415
|
+
".tsx",
|
|
1416
|
+
".js",
|
|
1417
|
+
".jsx",
|
|
1418
|
+
".mjs",
|
|
1419
|
+
".cjs",
|
|
1420
|
+
".mts",
|
|
1421
|
+
".cts"
|
|
1422
|
+
]
|
|
1423
|
+
},
|
|
1424
|
+
deno: {
|
|
1425
|
+
command: ["deno", "lsp"],
|
|
1426
|
+
extensions: [
|
|
1427
|
+
".ts",
|
|
1428
|
+
".tsx",
|
|
1429
|
+
".js",
|
|
1430
|
+
".jsx",
|
|
1431
|
+
".mjs"
|
|
1432
|
+
]
|
|
1433
|
+
},
|
|
1434
|
+
vue: {
|
|
1435
|
+
command: ["vue-language-server", "--stdio"],
|
|
1436
|
+
extensions: [".vue"]
|
|
1437
|
+
},
|
|
1438
|
+
eslint: {
|
|
1439
|
+
command: ["vscode-eslint-language-server", "--stdio"],
|
|
1440
|
+
extensions: [
|
|
1441
|
+
".ts",
|
|
1442
|
+
".tsx",
|
|
1443
|
+
".js",
|
|
1444
|
+
".jsx",
|
|
1445
|
+
".mjs",
|
|
1446
|
+
".cjs",
|
|
1447
|
+
".mts",
|
|
1448
|
+
".cts",
|
|
1449
|
+
".vue"
|
|
1450
|
+
]
|
|
1451
|
+
},
|
|
1452
|
+
oxlint: {
|
|
1453
|
+
command: ["oxlint", "--lsp"],
|
|
1454
|
+
extensions: [
|
|
1455
|
+
".ts",
|
|
1456
|
+
".tsx",
|
|
1457
|
+
".js",
|
|
1458
|
+
".jsx",
|
|
1459
|
+
".mjs",
|
|
1460
|
+
".cjs",
|
|
1461
|
+
".mts",
|
|
1462
|
+
".cts",
|
|
1463
|
+
".vue",
|
|
1464
|
+
".astro",
|
|
1465
|
+
".svelte"
|
|
1466
|
+
]
|
|
1467
|
+
},
|
|
1468
|
+
biome: {
|
|
1469
|
+
command: [
|
|
1470
|
+
"biome",
|
|
1471
|
+
"lsp-proxy",
|
|
1472
|
+
"--stdio"
|
|
1473
|
+
],
|
|
1474
|
+
extensions: [
|
|
1475
|
+
".ts",
|
|
1476
|
+
".tsx",
|
|
1477
|
+
".js",
|
|
1478
|
+
".jsx",
|
|
1479
|
+
".mjs",
|
|
1480
|
+
".cjs",
|
|
1481
|
+
".mts",
|
|
1482
|
+
".cts",
|
|
1483
|
+
".json",
|
|
1484
|
+
".jsonc",
|
|
1485
|
+
".vue",
|
|
1486
|
+
".astro",
|
|
1487
|
+
".svelte",
|
|
1488
|
+
".css",
|
|
1489
|
+
".graphql",
|
|
1490
|
+
".gql",
|
|
1491
|
+
".html"
|
|
1492
|
+
]
|
|
1493
|
+
},
|
|
1494
|
+
gopls: {
|
|
1495
|
+
command: ["gopls"],
|
|
1496
|
+
extensions: [".go"]
|
|
1497
|
+
},
|
|
1498
|
+
"ruby-lsp": {
|
|
1499
|
+
command: ["rubocop", "--lsp"],
|
|
1500
|
+
extensions: [
|
|
1501
|
+
".rb",
|
|
1502
|
+
".rake",
|
|
1503
|
+
".gemspec",
|
|
1504
|
+
".ru"
|
|
1505
|
+
]
|
|
1506
|
+
},
|
|
1507
|
+
basedpyright: {
|
|
1508
|
+
command: ["basedpyright-langserver", "--stdio"],
|
|
1509
|
+
extensions: [".py", ".pyi"]
|
|
1510
|
+
},
|
|
1511
|
+
pyright: {
|
|
1512
|
+
command: ["pyright-langserver", "--stdio"],
|
|
1513
|
+
extensions: [".py", ".pyi"]
|
|
1514
|
+
},
|
|
1515
|
+
ty: {
|
|
1516
|
+
command: ["ty", "server"],
|
|
1517
|
+
extensions: [".py", ".pyi"]
|
|
1518
|
+
},
|
|
1519
|
+
ruff: {
|
|
1520
|
+
command: ["ruff", "server"],
|
|
1521
|
+
extensions: [".py", ".pyi"]
|
|
1522
|
+
},
|
|
1523
|
+
"elixir-ls": {
|
|
1524
|
+
command: ["elixir-ls"],
|
|
1525
|
+
extensions: [".ex", ".exs"]
|
|
1526
|
+
},
|
|
1527
|
+
zls: {
|
|
1528
|
+
command: ["zls"],
|
|
1529
|
+
extensions: [".zig", ".zon"]
|
|
1530
|
+
},
|
|
1531
|
+
csharp: {
|
|
1532
|
+
command: ["csharp-ls"],
|
|
1533
|
+
extensions: [".cs"]
|
|
1534
|
+
},
|
|
1535
|
+
fsharp: {
|
|
1536
|
+
command: ["fsautocomplete"],
|
|
1537
|
+
extensions: [
|
|
1538
|
+
".fs",
|
|
1539
|
+
".fsi",
|
|
1540
|
+
".fsx",
|
|
1541
|
+
".fsscript"
|
|
1542
|
+
]
|
|
1543
|
+
},
|
|
1544
|
+
"sourcekit-lsp": {
|
|
1545
|
+
command: ["sourcekit-lsp"],
|
|
1546
|
+
extensions: [
|
|
1547
|
+
".swift",
|
|
1548
|
+
".m",
|
|
1549
|
+
".mm"
|
|
1550
|
+
]
|
|
1551
|
+
},
|
|
1552
|
+
rust: {
|
|
1553
|
+
command: ["rust-analyzer"],
|
|
1554
|
+
extensions: [".rs"]
|
|
1555
|
+
},
|
|
1556
|
+
clangd: {
|
|
1557
|
+
command: [
|
|
1558
|
+
"clangd",
|
|
1559
|
+
"--background-index",
|
|
1560
|
+
"--clang-tidy"
|
|
1561
|
+
],
|
|
1562
|
+
extensions: [
|
|
1563
|
+
".c",
|
|
1564
|
+
".cpp",
|
|
1565
|
+
".cc",
|
|
1566
|
+
".cxx",
|
|
1567
|
+
".c++",
|
|
1568
|
+
".h",
|
|
1569
|
+
".hpp",
|
|
1570
|
+
".hh",
|
|
1571
|
+
".hxx",
|
|
1572
|
+
".h++"
|
|
1573
|
+
]
|
|
1574
|
+
},
|
|
1575
|
+
svelte: {
|
|
1576
|
+
command: ["svelteserver", "--stdio"],
|
|
1577
|
+
extensions: [".svelte"]
|
|
1578
|
+
},
|
|
1579
|
+
astro: {
|
|
1580
|
+
command: ["astro-ls", "--stdio"],
|
|
1581
|
+
extensions: [".astro"]
|
|
1582
|
+
},
|
|
1583
|
+
bash: {
|
|
1584
|
+
command: ["bash-language-server", "start"],
|
|
1585
|
+
extensions: [
|
|
1586
|
+
".sh",
|
|
1587
|
+
".bash",
|
|
1588
|
+
".zsh",
|
|
1589
|
+
".ksh"
|
|
1590
|
+
]
|
|
1591
|
+
},
|
|
1592
|
+
"bash-ls": {
|
|
1593
|
+
command: ["bash-language-server", "start"],
|
|
1594
|
+
extensions: [
|
|
1595
|
+
".sh",
|
|
1596
|
+
".bash",
|
|
1597
|
+
".zsh",
|
|
1598
|
+
".ksh"
|
|
1599
|
+
]
|
|
1600
|
+
},
|
|
1601
|
+
jdtls: {
|
|
1602
|
+
command: ["jdtls"],
|
|
1603
|
+
extensions: [".java"]
|
|
1604
|
+
},
|
|
1605
|
+
"yaml-ls": {
|
|
1606
|
+
command: ["yaml-language-server", "--stdio"],
|
|
1607
|
+
extensions: [".yaml", ".yml"]
|
|
1608
|
+
},
|
|
1609
|
+
"lua-ls": {
|
|
1610
|
+
command: ["lua-language-server"],
|
|
1611
|
+
extensions: [".lua"]
|
|
1612
|
+
},
|
|
1613
|
+
php: {
|
|
1614
|
+
command: ["intelephense", "--stdio"],
|
|
1615
|
+
extensions: [".php"]
|
|
1616
|
+
},
|
|
1617
|
+
dart: {
|
|
1618
|
+
command: [
|
|
1619
|
+
"dart",
|
|
1620
|
+
"language-server",
|
|
1621
|
+
"--lsp"
|
|
1622
|
+
],
|
|
1623
|
+
extensions: [".dart"]
|
|
1624
|
+
},
|
|
1625
|
+
terraform: {
|
|
1626
|
+
command: ["terraform-ls", "serve"],
|
|
1627
|
+
extensions: [".tf", ".tfvars"]
|
|
1628
|
+
},
|
|
1629
|
+
"terraform-ls": {
|
|
1630
|
+
command: ["terraform-ls", "serve"],
|
|
1631
|
+
extensions: [".tf", ".tfvars"]
|
|
1632
|
+
},
|
|
1633
|
+
prisma: {
|
|
1634
|
+
command: ["prisma", "language-server"],
|
|
1635
|
+
extensions: [".prisma"]
|
|
1636
|
+
},
|
|
1637
|
+
"ocaml-lsp": {
|
|
1638
|
+
command: ["ocamllsp"],
|
|
1639
|
+
extensions: [".ml", ".mli"]
|
|
1640
|
+
},
|
|
1641
|
+
texlab: {
|
|
1642
|
+
command: ["texlab"],
|
|
1643
|
+
extensions: [".tex", ".bib"]
|
|
1644
|
+
},
|
|
1645
|
+
dockerfile: {
|
|
1646
|
+
command: ["docker-langserver", "--stdio"],
|
|
1647
|
+
extensions: [".dockerfile"]
|
|
1648
|
+
},
|
|
1649
|
+
gleam: {
|
|
1650
|
+
command: ["gleam", "lsp"],
|
|
1651
|
+
extensions: [".gleam"]
|
|
1652
|
+
},
|
|
1653
|
+
"clojure-lsp": {
|
|
1654
|
+
command: ["clojure-lsp", "listen"],
|
|
1655
|
+
extensions: [
|
|
1656
|
+
".clj",
|
|
1657
|
+
".cljs",
|
|
1658
|
+
".cljc",
|
|
1659
|
+
".edn"
|
|
1660
|
+
]
|
|
1661
|
+
},
|
|
1662
|
+
nixd: {
|
|
1663
|
+
command: ["nixd"],
|
|
1664
|
+
extensions: [".nix"]
|
|
1665
|
+
},
|
|
1666
|
+
tinymist: {
|
|
1667
|
+
command: ["tinymist"],
|
|
1668
|
+
extensions: [".typ", ".typc"]
|
|
1669
|
+
},
|
|
1670
|
+
"haskell-language-server": {
|
|
1671
|
+
command: ["haskell-language-server-wrapper", "--lsp"],
|
|
1672
|
+
extensions: [".hs", ".lhs"]
|
|
1673
|
+
},
|
|
1674
|
+
"kotlin-ls": {
|
|
1675
|
+
command: ["kotlin-lsp", "--stdio"],
|
|
1676
|
+
extensions: [".kt", ".kts"]
|
|
1677
|
+
},
|
|
1678
|
+
julials: {
|
|
1679
|
+
command: [
|
|
1680
|
+
"julia",
|
|
1681
|
+
"--startup-file=no",
|
|
1682
|
+
"--history-file=no",
|
|
1683
|
+
"-e",
|
|
1684
|
+
"using LanguageServer; runserver()"
|
|
1685
|
+
],
|
|
1686
|
+
extensions: [".jl"]
|
|
1687
|
+
},
|
|
1688
|
+
razor: {
|
|
1689
|
+
command: ["roslyn-language-server", "--stdio"],
|
|
1690
|
+
extensions: [".razor", ".cshtml"]
|
|
1691
|
+
}
|
|
1692
|
+
};
|
|
1693
|
+
//#endregion
|
|
1694
|
+
//#region packages/lsp-core/src/lsp/config-loader.ts
|
|
1695
|
+
function resolveProjectConfigPath(path) {
|
|
1696
|
+
return isAbsolute(path) ? path : join(contextCwd(), path);
|
|
1697
|
+
}
|
|
1698
|
+
function getProjectConfigPaths() {
|
|
1699
|
+
const projectOverride = contextEnv("LSP_TOOLS_MCP_PROJECT_CONFIG");
|
|
1700
|
+
if (projectOverride) return projectOverride.split(delimiter).filter(Boolean).map(resolveProjectConfigPath);
|
|
1701
|
+
return [join(contextCwd(), ".codex", "lsp-client.json")];
|
|
1702
|
+
}
|
|
1703
|
+
function getUserConfigPath() {
|
|
1704
|
+
const userOverride = contextEnv("LSP_TOOLS_MCP_USER_CONFIG");
|
|
1705
|
+
if (!userOverride) return join(homedir(), ".codex", "lsp-client.json");
|
|
1706
|
+
return isAbsolute(userOverride) ? userOverride : join(homedir(), userOverride);
|
|
1707
|
+
}
|
|
1708
|
+
function loadJsonFile(path) {
|
|
1709
|
+
if (!existsSync(path)) return null;
|
|
1710
|
+
try {
|
|
1711
|
+
const parsed = JSON.parse(readFileSync(path, "utf-8"));
|
|
1712
|
+
return isConfigJson(parsed) ? parsed : null;
|
|
1713
|
+
} catch {
|
|
1714
|
+
return null;
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
function loadAllConfigs() {
|
|
1718
|
+
const configs = /* @__PURE__ */ new Map();
|
|
1719
|
+
const project = loadFirstJsonFile(getProjectConfigPaths());
|
|
1720
|
+
if (project) configs.set("project", project);
|
|
1721
|
+
const user = loadJsonFile(getUserConfigPath());
|
|
1722
|
+
if (user) configs.set("user", user);
|
|
1723
|
+
return configs;
|
|
1724
|
+
}
|
|
1725
|
+
function loadFirstJsonFile(paths) {
|
|
1726
|
+
for (const path of paths) {
|
|
1727
|
+
const config = loadJsonFile(path);
|
|
1728
|
+
if (config) return config;
|
|
1729
|
+
}
|
|
1730
|
+
return null;
|
|
1731
|
+
}
|
|
1732
|
+
function getMergedServers() {
|
|
1733
|
+
const configs = loadAllConfigs();
|
|
1734
|
+
const servers = [];
|
|
1735
|
+
const disabled = /* @__PURE__ */ new Set();
|
|
1736
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1737
|
+
for (const source of ["project", "user"]) {
|
|
1738
|
+
const config = configs.get(source);
|
|
1739
|
+
if (!config?.lsp) continue;
|
|
1740
|
+
for (const [id, rawEntry] of Object.entries(config.lsp)) {
|
|
1741
|
+
const entry = parseLspEntry(rawEntry);
|
|
1742
|
+
if (!entry) continue;
|
|
1743
|
+
if (entry.disabled) {
|
|
1744
|
+
disabled.add(id);
|
|
1745
|
+
continue;
|
|
1746
|
+
}
|
|
1747
|
+
if (seen.has(id)) continue;
|
|
1748
|
+
const server = createServerFromEntry(id, entry, source);
|
|
1749
|
+
if (!server) continue;
|
|
1750
|
+
servers.push(server);
|
|
1751
|
+
seen.add(id);
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
for (const [id, config] of Object.entries(BUILTIN_SERVERS)) {
|
|
1755
|
+
if (disabled.has(id) || seen.has(id)) continue;
|
|
1756
|
+
servers.push({
|
|
1757
|
+
id,
|
|
1758
|
+
command: config.command,
|
|
1759
|
+
extensions: config.extensions,
|
|
1760
|
+
priority: -100,
|
|
1761
|
+
source: "builtin"
|
|
1762
|
+
});
|
|
1763
|
+
}
|
|
1764
|
+
return servers.sort((a, b) => {
|
|
1765
|
+
if (a.source !== b.source) {
|
|
1766
|
+
const order = {
|
|
1767
|
+
project: 0,
|
|
1768
|
+
user: 1,
|
|
1769
|
+
builtin: 2
|
|
1770
|
+
};
|
|
1771
|
+
return order[a.source] - order[b.source];
|
|
1772
|
+
}
|
|
1773
|
+
return b.priority - a.priority;
|
|
1774
|
+
});
|
|
1775
|
+
}
|
|
1776
|
+
function createServerFromEntry(id, entry, source) {
|
|
1777
|
+
const builtin = BUILTIN_SERVERS[id];
|
|
1778
|
+
if (source === "project") {
|
|
1779
|
+
if (!builtin) return null;
|
|
1780
|
+
const server = createServer$1({
|
|
1781
|
+
id,
|
|
1782
|
+
command: builtin.command,
|
|
1783
|
+
extensions: entry.extensions ?? builtin.extensions,
|
|
1784
|
+
priority: entry.priority ?? 0,
|
|
1785
|
+
source
|
|
1786
|
+
});
|
|
1787
|
+
if (entry.initialization !== void 0) server.initialization = entry.initialization;
|
|
1788
|
+
return server;
|
|
1789
|
+
}
|
|
1790
|
+
if (entry.command && entry.extensions) {
|
|
1791
|
+
const server = createServer$1({
|
|
1792
|
+
id,
|
|
1793
|
+
command: entry.command,
|
|
1794
|
+
extensions: entry.extensions,
|
|
1795
|
+
priority: entry.priority ?? 0,
|
|
1796
|
+
source
|
|
1797
|
+
});
|
|
1798
|
+
applyOptionalServerFields(server, entry);
|
|
1799
|
+
return server;
|
|
1800
|
+
}
|
|
1801
|
+
if (!builtin) return null;
|
|
1802
|
+
const server = createServer$1({
|
|
1803
|
+
id,
|
|
1804
|
+
command: entry.command ?? builtin.command,
|
|
1805
|
+
extensions: entry.extensions ?? builtin.extensions,
|
|
1806
|
+
priority: entry.priority ?? 0,
|
|
1807
|
+
source
|
|
1808
|
+
});
|
|
1809
|
+
applyOptionalServerFields(server, entry);
|
|
1810
|
+
return server;
|
|
1811
|
+
}
|
|
1812
|
+
function createServer$1(input) {
|
|
1813
|
+
const server = {
|
|
1814
|
+
id: input.id,
|
|
1815
|
+
command: input.command,
|
|
1816
|
+
extensions: input.extensions,
|
|
1817
|
+
priority: input.priority,
|
|
1818
|
+
source: input.source
|
|
1819
|
+
};
|
|
1820
|
+
if (input.env !== void 0) server.env = input.env;
|
|
1821
|
+
if (input.initialization !== void 0) server.initialization = input.initialization;
|
|
1822
|
+
return server;
|
|
1823
|
+
}
|
|
1824
|
+
function applyOptionalServerFields(server, entry) {
|
|
1825
|
+
if (entry.env !== void 0) server.env = entry.env;
|
|
1826
|
+
if (entry.initialization !== void 0) server.initialization = entry.initialization;
|
|
1827
|
+
}
|
|
1828
|
+
function isConfigJson(value) {
|
|
1829
|
+
if (!isRecord$1(value)) return false;
|
|
1830
|
+
const lsp = value["lsp"];
|
|
1831
|
+
return lsp === void 0 || isRecord$1(lsp);
|
|
1832
|
+
}
|
|
1833
|
+
function parseLspEntry(value) {
|
|
1834
|
+
return isLspEntry(value) ? value : null;
|
|
1835
|
+
}
|
|
1836
|
+
function isLspEntry(value) {
|
|
1837
|
+
if (!isRecord$1(value)) return false;
|
|
1838
|
+
const disabled = value["disabled"];
|
|
1839
|
+
const command = value["command"];
|
|
1840
|
+
const extensions = value["extensions"];
|
|
1841
|
+
const priority = value["priority"];
|
|
1842
|
+
const env = value["env"];
|
|
1843
|
+
const initialization = value["initialization"];
|
|
1844
|
+
return (disabled === void 0 || typeof disabled === "boolean") && (command === void 0 || isStringArray(command)) && (extensions === void 0 || isStringArray(extensions)) && (priority === void 0 || typeof priority === "number") && (env === void 0 || isStringRecord$1(env)) && (initialization === void 0 || isRecord$1(initialization));
|
|
1845
|
+
}
|
|
1846
|
+
function isStringArray(value) {
|
|
1847
|
+
return Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
1848
|
+
}
|
|
1849
|
+
function isStringRecord$1(value) {
|
|
1850
|
+
return isRecord$1(value) && Object.values(value).every((item) => typeof item === "string");
|
|
1851
|
+
}
|
|
1852
|
+
function isRecord$1(value) {
|
|
1853
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1854
|
+
}
|
|
1855
|
+
function getDisabledServerIds() {
|
|
1856
|
+
const configs = loadAllConfigs();
|
|
1857
|
+
const disabled = /* @__PURE__ */ new Set();
|
|
1858
|
+
for (const config of configs.values()) {
|
|
1859
|
+
if (!config.lsp) continue;
|
|
1860
|
+
for (const [id, rawEntry] of Object.entries(config.lsp)) {
|
|
1861
|
+
const entry = parseLspEntry(rawEntry);
|
|
1862
|
+
if (!entry) continue;
|
|
1863
|
+
if (entry.disabled) disabled.add(id);
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
return disabled;
|
|
1867
|
+
}
|
|
1868
|
+
//#endregion
|
|
1869
|
+
//#region packages/lsp-core/src/lsp/server-installation.ts
|
|
1870
|
+
function isServerInstalled(command, _workingDirectory) {
|
|
1871
|
+
if (command.length === 0) return false;
|
|
1872
|
+
const [cmd] = command;
|
|
1873
|
+
if (!cmd) return false;
|
|
1874
|
+
if (cmd.includes("/") || cmd.includes("\\")) {
|
|
1875
|
+
if (existsSync(cmd)) return true;
|
|
1876
|
+
}
|
|
1877
|
+
const isWindows = process.platform === "win32";
|
|
1878
|
+
let exts = [""];
|
|
1879
|
+
if (isWindows) {
|
|
1880
|
+
const pathExt = process.env["PATHEXT"] ?? "";
|
|
1881
|
+
if (pathExt) {
|
|
1882
|
+
const systemExts = pathExt.split(";").filter(Boolean);
|
|
1883
|
+
exts = [...new Set([
|
|
1884
|
+
...exts,
|
|
1885
|
+
...systemExts,
|
|
1886
|
+
".exe",
|
|
1887
|
+
".cmd",
|
|
1888
|
+
".bat",
|
|
1889
|
+
".ps1"
|
|
1890
|
+
])];
|
|
1891
|
+
} else exts = [
|
|
1892
|
+
"",
|
|
1893
|
+
".exe",
|
|
1894
|
+
".cmd",
|
|
1895
|
+
".bat",
|
|
1896
|
+
".ps1"
|
|
1897
|
+
];
|
|
1898
|
+
}
|
|
1899
|
+
let pathEnv = process.env["PATH"] ?? "";
|
|
1900
|
+
if (isWindows && !pathEnv) pathEnv = process.env["Path"] ?? "";
|
|
1901
|
+
const paths = pathEnv.split(delimiter);
|
|
1902
|
+
for (const p of paths) for (const suffix of exts) if (existsSync(join(p, cmd + suffix))) return true;
|
|
1903
|
+
if (cmd === "node") return true;
|
|
1904
|
+
return false;
|
|
1905
|
+
}
|
|
1906
|
+
//#endregion
|
|
1907
|
+
//#region packages/lsp-core/src/lsp/server-resolution.ts
|
|
1908
|
+
function findServerForExtension(ext) {
|
|
1909
|
+
const servers = getMergedServers();
|
|
1910
|
+
for (const server of servers) if (server.extensions.includes(ext) && isServerInstalled(server.command)) {
|
|
1911
|
+
const resolvedServer = {
|
|
1912
|
+
id: server.id,
|
|
1913
|
+
command: server.command,
|
|
1914
|
+
extensions: server.extensions,
|
|
1915
|
+
priority: server.priority
|
|
1916
|
+
};
|
|
1917
|
+
if (server.env !== void 0) return {
|
|
1918
|
+
status: "found",
|
|
1919
|
+
server: {
|
|
1920
|
+
...resolvedServer,
|
|
1921
|
+
env: server.env,
|
|
1922
|
+
...server.initialization === void 0 ? {} : { initialization: server.initialization }
|
|
1923
|
+
}
|
|
1924
|
+
};
|
|
1925
|
+
return {
|
|
1926
|
+
status: "found",
|
|
1927
|
+
server: {
|
|
1928
|
+
...resolvedServer,
|
|
1929
|
+
...server.initialization === void 0 ? {} : { initialization: server.initialization }
|
|
1930
|
+
}
|
|
1931
|
+
};
|
|
1932
|
+
}
|
|
1933
|
+
for (const server of servers) if (server.extensions.includes(ext)) {
|
|
1934
|
+
const installHint = LSP_INSTALL_HINTS[server.id] ?? `Install '${server.command[0]}' and ensure it's in your PATH`;
|
|
1935
|
+
return {
|
|
1936
|
+
status: "not_installed",
|
|
1937
|
+
server: {
|
|
1938
|
+
id: server.id,
|
|
1939
|
+
command: server.command,
|
|
1940
|
+
extensions: server.extensions
|
|
1941
|
+
},
|
|
1942
|
+
installHint
|
|
1943
|
+
};
|
|
1944
|
+
}
|
|
1945
|
+
return {
|
|
1946
|
+
status: "not_configured",
|
|
1947
|
+
extension: ext,
|
|
1948
|
+
availableServers: [...new Set(servers.map((s) => s.id))]
|
|
1949
|
+
};
|
|
1950
|
+
}
|
|
1951
|
+
function getAllServers() {
|
|
1952
|
+
const servers = getMergedServers();
|
|
1953
|
+
const disabled = getDisabledServerIds();
|
|
1954
|
+
const result = [];
|
|
1955
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1956
|
+
for (const server of servers) {
|
|
1957
|
+
if (seen.has(server.id)) continue;
|
|
1958
|
+
result.push({
|
|
1959
|
+
id: server.id,
|
|
1960
|
+
installed: isServerInstalled(server.command),
|
|
1961
|
+
extensions: server.extensions,
|
|
1962
|
+
disabled: false,
|
|
1963
|
+
source: server.source,
|
|
1964
|
+
priority: server.priority
|
|
1965
|
+
});
|
|
1966
|
+
seen.add(server.id);
|
|
1967
|
+
}
|
|
1968
|
+
for (const id of disabled) {
|
|
1969
|
+
if (seen.has(id)) continue;
|
|
1970
|
+
const builtin = BUILTIN_SERVERS[id];
|
|
1971
|
+
result.push({
|
|
1972
|
+
id,
|
|
1973
|
+
installed: builtin ? isServerInstalled(builtin.command) : false,
|
|
1974
|
+
extensions: builtin?.extensions ?? [],
|
|
1975
|
+
disabled: true,
|
|
1976
|
+
source: "disabled",
|
|
1977
|
+
priority: 0
|
|
1978
|
+
});
|
|
1979
|
+
}
|
|
1980
|
+
return result;
|
|
1981
|
+
}
|
|
1982
|
+
//#endregion
|
|
1983
|
+
//#region packages/lsp-core/src/lsp/client-wrapper.ts
|
|
1984
|
+
var WORKSPACE_MARKERS = [
|
|
1985
|
+
".git",
|
|
1986
|
+
"package.json",
|
|
1987
|
+
"pyproject.toml",
|
|
1988
|
+
"Cargo.toml",
|
|
1989
|
+
"go.mod",
|
|
1990
|
+
"pom.xml",
|
|
1991
|
+
"build.gradle"
|
|
1992
|
+
];
|
|
1993
|
+
function isDirectoryPath(filePath) {
|
|
1994
|
+
try {
|
|
1995
|
+
return statSync(filePath).isDirectory();
|
|
1996
|
+
} catch {
|
|
1997
|
+
return false;
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
function findWorkspaceRoot(filePath) {
|
|
2001
|
+
const abs = resolve(contextCwd(), filePath);
|
|
2002
|
+
let dir = abs;
|
|
2003
|
+
if (!isDirectoryPath(dir)) dir = dirname(dir);
|
|
2004
|
+
let prevDir = "";
|
|
2005
|
+
while (dir !== prevDir) {
|
|
2006
|
+
for (const marker of WORKSPACE_MARKERS) if (existsSync(join(dir, marker))) return dir;
|
|
2007
|
+
prevDir = dir;
|
|
2008
|
+
dir = dirname(dir);
|
|
2009
|
+
}
|
|
2010
|
+
return dirname(abs);
|
|
2011
|
+
}
|
|
2012
|
+
function formatServerLookupError(result) {
|
|
2013
|
+
if (result.status === "not_installed") return formatNotInstalled(result);
|
|
2014
|
+
return [
|
|
2015
|
+
`No LSP server configured for extension: ${result.extension}`,
|
|
2016
|
+
"",
|
|
2017
|
+
`Available servers: ${result.availableServers.slice(0, 10).join(", ")}${result.availableServers.length > 10 ? "..." : ""}`,
|
|
2018
|
+
"",
|
|
2019
|
+
"Configure a custom server in '.codex/lsp-client.json':",
|
|
2020
|
+
" {",
|
|
2021
|
+
" \"lsp\": {",
|
|
2022
|
+
" \"my-server\": {",
|
|
2023
|
+
" \"command\": [\"my-lsp\", \"--stdio\"],",
|
|
2024
|
+
` "extensions": ["${result.extension}"]`,
|
|
2025
|
+
" }",
|
|
2026
|
+
" }",
|
|
2027
|
+
" }"
|
|
2028
|
+
].join("\n");
|
|
2029
|
+
}
|
|
2030
|
+
function formatNotInstalled(result) {
|
|
2031
|
+
const { server, installHint } = result;
|
|
2032
|
+
const extensions = server.extensions.join(", ");
|
|
2033
|
+
const decision = loadInstallDecision(server.id)?.decision;
|
|
2034
|
+
if (decision === "declined") return `LSP server '${server.id}' (${extensions}) is NOT INSTALLED; user previously declined installation — proceed without LSP.`;
|
|
2035
|
+
const header = [
|
|
2036
|
+
`LSP server '${server.id}' for ${extensions} is NOT INSTALLED.`,
|
|
2037
|
+
"",
|
|
2038
|
+
`Command not found: ${server.command[0]}`,
|
|
2039
|
+
""
|
|
2040
|
+
];
|
|
2041
|
+
if (decision === "allowed") return [
|
|
2042
|
+
...header,
|
|
2043
|
+
"The user has pre-authorized LSP installation. Run the install command, then retry this tool:",
|
|
2044
|
+
` ${installHint}`
|
|
2045
|
+
].join("\n");
|
|
2046
|
+
return [
|
|
2047
|
+
...header,
|
|
2048
|
+
"To install, run:",
|
|
2049
|
+
` ${installHint}`,
|
|
2050
|
+
"",
|
|
2051
|
+
"ACTION REQUIRED — ASK THE USER whether to install this LSP server.",
|
|
2052
|
+
"- If the user agrees: run the install command above, then retry this tool.",
|
|
2053
|
+
"- If the user declines, OR has NOT explicitly asked for LSP installation:",
|
|
2054
|
+
` call lsp_install_decision { server_id: "${server.id}", decision: "declined" },`,
|
|
2055
|
+
" then ignore this message and proceed WITHOUT LSP."
|
|
2056
|
+
].join("\n");
|
|
2057
|
+
}
|
|
2058
|
+
var READ_ONLY_RETRY_TOOLS = new Set([
|
|
2059
|
+
"diagnostics",
|
|
2060
|
+
"definition",
|
|
2061
|
+
"references",
|
|
2062
|
+
"documentSymbols",
|
|
2063
|
+
"workspaceSymbols",
|
|
2064
|
+
"prepareRename"
|
|
2065
|
+
]);
|
|
2066
|
+
async function withLspClient(filePath, fn, toolName, options = {}) {
|
|
2067
|
+
const absPath = resolve(contextCwd(), filePath);
|
|
2068
|
+
if (isDirectoryPath(absPath)) throw new LspInvalidPathError("Directory paths are not supported by this LSP tool. Use lsp.diagnostics with a directory path for directory diagnostics.");
|
|
2069
|
+
const result = findServerForExtension(effectiveExtension(absPath));
|
|
2070
|
+
if (result.status !== "found") throw new LspServerLookupError(formatServerLookupError(result));
|
|
2071
|
+
const server = result.server;
|
|
2072
|
+
const root = findWorkspaceRoot(absPath);
|
|
2073
|
+
const manager = options.manager ?? getLspManager();
|
|
2074
|
+
const acquireAndCall = async (allowRetry) => {
|
|
2075
|
+
const client = await manager.getClient(root, server, options.signal);
|
|
2076
|
+
try {
|
|
2077
|
+
return await fn(client, root);
|
|
2078
|
+
} catch (err) {
|
|
2079
|
+
if (allowRetry && READ_ONLY_RETRY_TOOLS.has(toolName) && isLspDeadConnectionError(err)) {
|
|
2080
|
+
manager.invalidateClient(root, server.id, client);
|
|
2081
|
+
return acquireAndCall(false);
|
|
2082
|
+
}
|
|
2083
|
+
if (err instanceof LspRequestTimeoutError) {
|
|
2084
|
+
if (manager.isServerInitializing(root, server.id)) throw new LspServerInitializingError(err);
|
|
2085
|
+
}
|
|
2086
|
+
throw err;
|
|
2087
|
+
} finally {
|
|
2088
|
+
manager.releaseClient(root, server.id);
|
|
2089
|
+
}
|
|
2090
|
+
};
|
|
2091
|
+
return acquireAndCall(true);
|
|
2092
|
+
}
|
|
2093
|
+
//#endregion
|
|
2094
|
+
//#region packages/lsp-core/src/lsp/formatters.ts
|
|
2095
|
+
var DIAGNOSTIC_SEVERITY_FILTERS = {
|
|
2096
|
+
error: 1,
|
|
2097
|
+
warning: 2,
|
|
2098
|
+
information: 3,
|
|
2099
|
+
hint: 4
|
|
2100
|
+
};
|
|
2101
|
+
function uriToPath(uri) {
|
|
2102
|
+
return fileURLToPath(uri);
|
|
2103
|
+
}
|
|
2104
|
+
function formatLocation(loc) {
|
|
2105
|
+
if ("targetUri" in loc) return `${uriToPath(loc.targetUri)}:${loc.targetRange.start.line + 1}:${loc.targetRange.start.character}`;
|
|
2106
|
+
return `${uriToPath(loc.uri)}:${loc.range.start.line + 1}:${loc.range.start.character}`;
|
|
2107
|
+
}
|
|
2108
|
+
function formatSymbolKind(kind) {
|
|
2109
|
+
return SYMBOL_KIND_MAP[kind] ?? `Unknown(${kind})`;
|
|
2110
|
+
}
|
|
2111
|
+
function formatSeverity(severity) {
|
|
2112
|
+
if (!severity) return "unknown";
|
|
2113
|
+
return SEVERITY_MAP[severity] ?? `unknown(${severity})`;
|
|
2114
|
+
}
|
|
2115
|
+
function formatDocumentSymbol(symbol, indent = 0) {
|
|
2116
|
+
const prefix = " ".repeat(indent);
|
|
2117
|
+
const kind = formatSymbolKind(symbol.kind);
|
|
2118
|
+
const line = symbol.range.start.line + 1;
|
|
2119
|
+
let result = `${prefix}${symbol.name} (${kind}) - line ${line}`;
|
|
2120
|
+
if (symbol.children && symbol.children.length > 0) for (const child of symbol.children) result += `\n${formatDocumentSymbol(child, indent + 1)}`;
|
|
2121
|
+
return result;
|
|
2122
|
+
}
|
|
2123
|
+
function formatSymbolInfo(symbol) {
|
|
2124
|
+
const kind = formatSymbolKind(symbol.kind);
|
|
2125
|
+
const loc = formatLocation(symbol.location);
|
|
2126
|
+
const container = symbol.containerName ? ` (in ${symbol.containerName})` : "";
|
|
2127
|
+
return `${symbol.name} (${kind})${container} - ${loc}`;
|
|
2128
|
+
}
|
|
2129
|
+
function formatDiagnostic(diag) {
|
|
2130
|
+
const severity = formatSeverity(diag.severity);
|
|
2131
|
+
const line = diag.range.start.line + 1;
|
|
2132
|
+
const char = diag.range.start.character;
|
|
2133
|
+
return `${severity}${diag.source ? `[${diag.source}]` : ""}${diag.code ? ` (${diag.code})` : ""} at ${line}:${char}: ${diag.message}`;
|
|
2134
|
+
}
|
|
2135
|
+
function filterDiagnosticsBySeverity(diagnostics, severityFilter) {
|
|
2136
|
+
if (!severityFilter || severityFilter === "all") return diagnostics;
|
|
2137
|
+
const targetSeverity = DIAGNOSTIC_SEVERITY_FILTERS[severityFilter];
|
|
2138
|
+
return diagnostics.filter((d) => d.severity === targetSeverity);
|
|
2139
|
+
}
|
|
2140
|
+
function formatPrepareRenameResult(result) {
|
|
2141
|
+
if (!result) return "Cannot rename at this position";
|
|
2142
|
+
if ("defaultBehavior" in result) return result.defaultBehavior ? "Rename supported (using default behavior)" : "Cannot rename at this position";
|
|
2143
|
+
if ("range" in result && result.range) return `Rename available at ${result.range.start.line + 1}:${result.range.start.character}-${result.range.end.line + 1}:${result.range.end.character}${result.placeholder ? ` (current: "${result.placeholder}")` : ""}`;
|
|
2144
|
+
if ("start" in result && "end" in result) return `Rename available at ${result.start.line + 1}:${result.start.character}-${result.end.line + 1}:${result.end.character}`;
|
|
2145
|
+
return "Cannot rename at this position";
|
|
2146
|
+
}
|
|
2147
|
+
function formatApplyResult(result) {
|
|
2148
|
+
const lines = [];
|
|
2149
|
+
if (result.success) {
|
|
2150
|
+
lines.push(`Applied ${result.totalEdits} edit(s) to ${result.filesModified.length} file(s):`);
|
|
2151
|
+
for (const file of result.filesModified) lines.push(` - ${file}`);
|
|
2152
|
+
} else {
|
|
2153
|
+
lines.push("Failed to apply some changes:");
|
|
2154
|
+
for (const err of result.errors) lines.push(` Error: ${err}`);
|
|
2155
|
+
if (result.filesModified.length > 0) lines.push(`Successfully modified: ${result.filesModified.join(", ")}`);
|
|
2156
|
+
}
|
|
2157
|
+
return lines.join("\n");
|
|
2158
|
+
}
|
|
2159
|
+
//#endregion
|
|
2160
|
+
//#region packages/lsp-core/src/lsp/directory-diagnostics.ts
|
|
2161
|
+
var SKIP_DIRECTORIES$1 = new Set([
|
|
2162
|
+
"node_modules",
|
|
2163
|
+
".git",
|
|
2164
|
+
"dist",
|
|
2165
|
+
"build",
|
|
2166
|
+
".next",
|
|
2167
|
+
"out"
|
|
2168
|
+
]);
|
|
2169
|
+
function collectFilesWithExtension(dir, extension, maxFiles) {
|
|
2170
|
+
const files = [];
|
|
2171
|
+
function walk(currentDir) {
|
|
2172
|
+
if (files.length >= maxFiles) return;
|
|
2173
|
+
let entries = [];
|
|
2174
|
+
try {
|
|
2175
|
+
entries = readdirSync(currentDir);
|
|
2176
|
+
} catch {
|
|
2177
|
+
return;
|
|
2178
|
+
}
|
|
2179
|
+
for (const entry of entries) {
|
|
2180
|
+
if (files.length >= maxFiles) return;
|
|
2181
|
+
const fullPath = join(currentDir, entry);
|
|
2182
|
+
let stat;
|
|
2183
|
+
try {
|
|
2184
|
+
stat = lstatSync(fullPath);
|
|
2185
|
+
} catch {
|
|
2186
|
+
continue;
|
|
2187
|
+
}
|
|
2188
|
+
if (!stat || stat.isSymbolicLink()) continue;
|
|
2189
|
+
if (stat.isDirectory()) {
|
|
2190
|
+
if (!SKIP_DIRECTORIES$1.has(entry)) walk(fullPath);
|
|
2191
|
+
} else if (stat.isFile() && effectiveExtension(fullPath) === extension) files.push(fullPath);
|
|
2192
|
+
}
|
|
2193
|
+
}
|
|
2194
|
+
walk(dir);
|
|
2195
|
+
return files;
|
|
2196
|
+
}
|
|
2197
|
+
async function aggregateDiagnosticsForDirectory(directory, extension, severity, maxFiles = 50) {
|
|
2198
|
+
if (!extension.startsWith(".")) throw new LspInvalidPathError(`Extension must start with a dot (e.g., ".ts", not "${extension}"). Use ".${extension}" instead.`);
|
|
2199
|
+
const absDir = resolve(contextCwd(), directory);
|
|
2200
|
+
if (!existsSync(absDir)) throw new LspInvalidPathError(`Directory does not exist: ${absDir}`);
|
|
2201
|
+
const serverResult = findServerForExtension(extension);
|
|
2202
|
+
if (serverResult.status !== "found") throw new LspServerLookupError(formatServerLookupError(serverResult));
|
|
2203
|
+
const server = serverResult.server;
|
|
2204
|
+
const allFiles = collectFilesWithExtension(absDir, extension, maxFiles + 1);
|
|
2205
|
+
const wasCapped = allFiles.length > maxFiles;
|
|
2206
|
+
const filesToProcess = allFiles.slice(0, maxFiles);
|
|
2207
|
+
if (filesToProcess.length === 0) return [
|
|
2208
|
+
`Directory: ${absDir}`,
|
|
2209
|
+
`Extension: ${extension}`,
|
|
2210
|
+
"Files scanned: 0",
|
|
2211
|
+
`No files found with extension "${extension}".`
|
|
2212
|
+
].join("\n");
|
|
2213
|
+
const root = findWorkspaceRoot(absDir);
|
|
2214
|
+
const manager = getLspManager();
|
|
2215
|
+
const allDiagnostics = [];
|
|
2216
|
+
const fileErrors = [];
|
|
2217
|
+
const client = await manager.getClient(root, server);
|
|
2218
|
+
try {
|
|
2219
|
+
for (const file of filesToProcess) try {
|
|
2220
|
+
const filtered = filterDiagnosticsBySeverity((await client.diagnostics(file)).items, severity);
|
|
2221
|
+
allDiagnostics.push(...filtered.map((diagnostic) => ({
|
|
2222
|
+
filePath: file,
|
|
2223
|
+
diagnostic
|
|
2224
|
+
})));
|
|
2225
|
+
} catch (e) {
|
|
2226
|
+
fileErrors.push({
|
|
2227
|
+
file,
|
|
2228
|
+
error: e instanceof Error ? e.message : String(e)
|
|
2229
|
+
});
|
|
2230
|
+
}
|
|
2231
|
+
} finally {
|
|
2232
|
+
manager.releaseClient(root, server.id);
|
|
2233
|
+
}
|
|
2234
|
+
const displayDiagnostics = allDiagnostics.slice(0, 200);
|
|
2235
|
+
const wasDiagCapped = allDiagnostics.length > 200;
|
|
2236
|
+
const lines = [
|
|
2237
|
+
`Directory: ${absDir}`,
|
|
2238
|
+
`Extension: ${extension}`,
|
|
2239
|
+
`Files scanned: ${filesToProcess.length}${wasCapped ? ` (capped at ${maxFiles})` : ""}`,
|
|
2240
|
+
`Files with errors: ${fileErrors.length}`,
|
|
2241
|
+
`Total diagnostics: ${allDiagnostics.length}`
|
|
2242
|
+
];
|
|
2243
|
+
if (fileErrors.length > 0) {
|
|
2244
|
+
lines.push("", "File processing errors:");
|
|
2245
|
+
for (const { file, error } of fileErrors) lines.push(` ${file}: ${error}`);
|
|
2246
|
+
}
|
|
2247
|
+
if (displayDiagnostics.length > 0) {
|
|
2248
|
+
lines.push("");
|
|
2249
|
+
for (const { filePath, diagnostic } of displayDiagnostics) lines.push(`${filePath}: ${formatDiagnostic(diagnostic)}`);
|
|
2250
|
+
if (wasDiagCapped) lines.push("", `... (${allDiagnostics.length - 200} more diagnostics not shown)`);
|
|
2251
|
+
}
|
|
2252
|
+
return lines.join("\n");
|
|
2253
|
+
}
|
|
2254
|
+
//#endregion
|
|
2255
|
+
//#region packages/lsp-core/src/lsp/infer-extension.ts
|
|
2256
|
+
var SKIP_DIRECTORIES = new Set([
|
|
2257
|
+
"node_modules",
|
|
2258
|
+
".git",
|
|
2259
|
+
"dist",
|
|
2260
|
+
"build",
|
|
2261
|
+
".next",
|
|
2262
|
+
"out"
|
|
2263
|
+
]);
|
|
2264
|
+
var MAX_SCAN_ENTRIES = 500;
|
|
2265
|
+
function inferExtensionFromDirectory(directory) {
|
|
2266
|
+
const extensionCounts = /* @__PURE__ */ new Map();
|
|
2267
|
+
let scanned = 0;
|
|
2268
|
+
function walk(dir) {
|
|
2269
|
+
if (scanned >= MAX_SCAN_ENTRIES) return;
|
|
2270
|
+
let entries;
|
|
2271
|
+
try {
|
|
2272
|
+
entries = readdirSync(dir);
|
|
2273
|
+
} catch {
|
|
2274
|
+
return;
|
|
2275
|
+
}
|
|
2276
|
+
for (const entry of entries) {
|
|
2277
|
+
if (scanned >= MAX_SCAN_ENTRIES) return;
|
|
2278
|
+
const fullPath = join(dir, entry);
|
|
2279
|
+
let stat;
|
|
2280
|
+
try {
|
|
2281
|
+
stat = lstatSync(fullPath);
|
|
2282
|
+
} catch {
|
|
2283
|
+
continue;
|
|
2284
|
+
}
|
|
2285
|
+
if (stat.isSymbolicLink()) continue;
|
|
2286
|
+
scanned++;
|
|
2287
|
+
if (stat.isDirectory()) {
|
|
2288
|
+
if (!SKIP_DIRECTORIES.has(entry)) walk(fullPath);
|
|
2289
|
+
} else if (stat.isFile()) {
|
|
2290
|
+
const ext = effectiveExtension(fullPath);
|
|
2291
|
+
if (ext && ext in EXT_TO_LANG) extensionCounts.set(ext, (extensionCounts.get(ext) ?? 0) + 1);
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2295
|
+
walk(directory);
|
|
2296
|
+
if (extensionCounts.size === 0) return null;
|
|
2297
|
+
let maxExt = "";
|
|
2298
|
+
let maxCount = 0;
|
|
2299
|
+
for (const [ext, count] of extensionCounts) if (count > maxCount) {
|
|
2300
|
+
maxCount = count;
|
|
2301
|
+
maxExt = ext;
|
|
2302
|
+
}
|
|
2303
|
+
return maxExt || null;
|
|
2304
|
+
}
|
|
2305
|
+
//#endregion
|
|
2306
|
+
//#region packages/lsp-core/src/lsp/utils.ts
|
|
2307
|
+
var RUST_SRC_REPAIR_MESSAGE = [
|
|
2308
|
+
"rust-analyzer exited while loading Rust standard library sources.",
|
|
2309
|
+
"",
|
|
2310
|
+
"Repair rust-src for the active toolchain:",
|
|
2311
|
+
" rustup component remove rust-src",
|
|
2312
|
+
" rustup component add rust-src"
|
|
2313
|
+
];
|
|
2314
|
+
function errorMessage$1(error) {
|
|
2315
|
+
return error instanceof Error ? error.message : String(error);
|
|
2316
|
+
}
|
|
2317
|
+
function formatKnownLspStartupFailure(error) {
|
|
2318
|
+
if (!(error instanceof LspProcessExitedError)) return null;
|
|
2319
|
+
if (error.serverId !== "rust") return null;
|
|
2320
|
+
const details = error.stderrTail ?? error.message;
|
|
2321
|
+
const lowerDetails = details.toLowerCase();
|
|
2322
|
+
if (!(lowerDetails.includes("rust-src") && (lowerDetails.includes("failed to install component") || lowerDetails.includes("detected conflict") || lowerDetails.includes("can't load standard library") || lowerDetails.includes("try installing") || lowerDetails.includes("sysroot")))) return null;
|
|
2323
|
+
return [
|
|
2324
|
+
...RUST_SRC_REPAIR_MESSAGE,
|
|
2325
|
+
"",
|
|
2326
|
+
"Original stderr tail:",
|
|
2327
|
+
details
|
|
2328
|
+
].join("\n");
|
|
2329
|
+
}
|
|
2330
|
+
function handleMissingDependencyError(error) {
|
|
2331
|
+
const knownStartupFailure = formatKnownLspStartupFailure(error);
|
|
2332
|
+
if (knownStartupFailure) return knownStartupFailure;
|
|
2333
|
+
const message = errorMessage$1(error);
|
|
2334
|
+
return message.includes("NOT INSTALLED") || message.includes("No LSP server configured") ? message : null;
|
|
2335
|
+
}
|
|
2336
|
+
//#endregion
|
|
2337
|
+
//#region packages/lsp-core/src/missing-dependency-result.ts
|
|
2338
|
+
function missingDependencyResult(error, details) {
|
|
2339
|
+
const message = handleMissingDependencyError(error);
|
|
2340
|
+
if (!message) return null;
|
|
2341
|
+
return {
|
|
2342
|
+
content: [{
|
|
2343
|
+
type: "text",
|
|
2344
|
+
text: message
|
|
2345
|
+
}],
|
|
2346
|
+
details: {
|
|
2347
|
+
...details,
|
|
2348
|
+
error: message,
|
|
2349
|
+
errorKind: "missing_dependency"
|
|
2350
|
+
}
|
|
2351
|
+
};
|
|
2352
|
+
}
|
|
2353
|
+
//#endregion
|
|
2354
|
+
//#region packages/lsp-core/src/tools/parameters.ts
|
|
2355
|
+
function isRecord(value) {
|
|
2356
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2357
|
+
}
|
|
2358
|
+
function requireString(params, key) {
|
|
2359
|
+
const value = params[key];
|
|
2360
|
+
if (typeof value !== "string" || value.length === 0) throw new Error(`Missing required string parameter '${key}'`);
|
|
2361
|
+
return value;
|
|
2362
|
+
}
|
|
2363
|
+
function optionalString(params, key) {
|
|
2364
|
+
const value = params[key];
|
|
2365
|
+
return typeof value === "string" ? value : void 0;
|
|
2366
|
+
}
|
|
2367
|
+
function requireNumber(params, key) {
|
|
2368
|
+
const value = params[key];
|
|
2369
|
+
if (typeof value !== "number" || !Number.isFinite(value)) throw new Error(`Missing required number parameter '${key}'`);
|
|
2370
|
+
return value;
|
|
2371
|
+
}
|
|
2372
|
+
function optionalNumber(params, key) {
|
|
2373
|
+
const value = params[key];
|
|
2374
|
+
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
2375
|
+
}
|
|
2376
|
+
function optionalBoolean(params, key) {
|
|
2377
|
+
const value = params[key];
|
|
2378
|
+
return typeof value === "boolean" ? value : void 0;
|
|
2379
|
+
}
|
|
2380
|
+
function severityFilter(params) {
|
|
2381
|
+
const value = params["severity"];
|
|
2382
|
+
if (value === "error" || value === "warning" || value === "information" || value === "hint" || value === "all") return value;
|
|
2383
|
+
return "all";
|
|
2384
|
+
}
|
|
2385
|
+
function clientOptions(signal) {
|
|
2386
|
+
return signal === void 0 ? {} : { signal };
|
|
2387
|
+
}
|
|
2388
|
+
//#endregion
|
|
2389
|
+
//#region packages/lsp-core/src/tools/result.ts
|
|
2390
|
+
function text(text, details, isError = false) {
|
|
2391
|
+
return {
|
|
2392
|
+
content: [{
|
|
2393
|
+
type: "text",
|
|
2394
|
+
text
|
|
2395
|
+
}],
|
|
2396
|
+
details,
|
|
2397
|
+
isError
|
|
2398
|
+
};
|
|
2399
|
+
}
|
|
2400
|
+
//#endregion
|
|
2401
|
+
//#region packages/lsp-core/src/tools/diagnostics.ts
|
|
2402
|
+
function asDiagnosticArray(result) {
|
|
2403
|
+
if (!result) return [];
|
|
2404
|
+
if (Array.isArray(result)) return result;
|
|
2405
|
+
return result.items ?? [];
|
|
2406
|
+
}
|
|
2407
|
+
async function executeLspDiagnostics(params, signal) {
|
|
2408
|
+
const filePath = requireString(params, "filePath");
|
|
2409
|
+
const severity = severityFilter(params);
|
|
2410
|
+
try {
|
|
2411
|
+
const absPath = resolve(contextCwd(), filePath);
|
|
2412
|
+
if (isDirectoryPath(absPath)) {
|
|
2413
|
+
const extension = inferExtensionFromDirectory(absPath);
|
|
2414
|
+
if (!extension) {
|
|
2415
|
+
const message = `No supported source files found in directory: ${absPath}`;
|
|
2416
|
+
return text(message, {
|
|
2417
|
+
filePath,
|
|
2418
|
+
severity,
|
|
2419
|
+
mode: "directory",
|
|
2420
|
+
diagnostics: [],
|
|
2421
|
+
totalDiagnostics: 0,
|
|
2422
|
+
truncated: false,
|
|
2423
|
+
error: message,
|
|
2424
|
+
errorKind: "no_files"
|
|
2425
|
+
});
|
|
2426
|
+
}
|
|
2427
|
+
return text(await aggregateDiagnosticsForDirectory(absPath, extension, severity), {
|
|
2428
|
+
filePath,
|
|
2429
|
+
severity,
|
|
2430
|
+
mode: "directory",
|
|
2431
|
+
diagnostics: [],
|
|
2432
|
+
totalDiagnostics: 0,
|
|
2433
|
+
truncated: false
|
|
2434
|
+
});
|
|
2435
|
+
}
|
|
2436
|
+
const diagnostics = filterDiagnosticsBySeverity(asDiagnosticArray(await withLspClient(filePath, async (client) => client.diagnostics(filePath), "diagnostics", clientOptions(signal))), severity);
|
|
2437
|
+
const total = diagnostics.length;
|
|
2438
|
+
const truncated = total > 200;
|
|
2439
|
+
const limited = truncated ? diagnostics.slice(0, 200) : diagnostics;
|
|
2440
|
+
return text(total === 0 ? "No diagnostics found" : [...truncated ? [`Found ${total} diagnostics (showing first 200):`] : [], ...limited.map(formatDiagnostic)].join("\n"), {
|
|
2441
|
+
filePath,
|
|
2442
|
+
severity,
|
|
2443
|
+
mode: "file",
|
|
2444
|
+
diagnostics: diagnostics.map((diagnostic) => ({
|
|
2445
|
+
file: absPath,
|
|
2446
|
+
diagnostic
|
|
2447
|
+
})),
|
|
2448
|
+
totalDiagnostics: total,
|
|
2449
|
+
truncated
|
|
2450
|
+
});
|
|
2451
|
+
} catch (error) {
|
|
2452
|
+
const missingDependency = missingDependencyResult(error, {
|
|
2453
|
+
filePath,
|
|
2454
|
+
severity,
|
|
2455
|
+
mode: "file",
|
|
2456
|
+
diagnostics: [],
|
|
2457
|
+
totalDiagnostics: 0,
|
|
2458
|
+
truncated: false
|
|
2459
|
+
});
|
|
2460
|
+
if (missingDependency) return missingDependency;
|
|
2461
|
+
throw error;
|
|
2462
|
+
}
|
|
2463
|
+
}
|
|
2464
|
+
//#endregion
|
|
2465
|
+
//#region packages/lsp-core/src/tools/install-decision.ts
|
|
2466
|
+
async function executeLspInstallDecision(params) {
|
|
2467
|
+
const serverId = requireString(params, "server_id");
|
|
2468
|
+
const decision = params["decision"];
|
|
2469
|
+
if (!isInstallDecision(decision)) return text(`Invalid decision '${String(decision)}'. Expected "declined" or "allowed".`, {
|
|
2470
|
+
serverId,
|
|
2471
|
+
errorKind: "invalid_decision"
|
|
2472
|
+
}, true);
|
|
2473
|
+
const serverIds = [...new Set(getMergedServers().map((server) => server.id))];
|
|
2474
|
+
if (!serverIds.includes(serverId)) return text(`Unknown LSP server '${serverId}'. Known servers: ${serverIds.slice(0, 20).join(", ")}${serverIds.length > 20 ? "..." : ""}`, {
|
|
2475
|
+
serverId,
|
|
2476
|
+
errorKind: "unknown_server"
|
|
2477
|
+
}, true);
|
|
2478
|
+
recordInstallDecision(serverId, decision);
|
|
2479
|
+
return text(`Recorded install decision for '${serverId}': ${decision}. ${decisionFollowUp(decision)}`, {
|
|
2480
|
+
serverId,
|
|
2481
|
+
decision
|
|
2482
|
+
});
|
|
2483
|
+
}
|
|
2484
|
+
function decisionFollowUp(decision) {
|
|
2485
|
+
return decision === "declined" ? "Future LSP lookups for this server stay quiet; proceed without LSP." : "Future LSP lookups keep install instructions without asking the user.";
|
|
2486
|
+
}
|
|
2487
|
+
//#endregion
|
|
2488
|
+
//#region packages/lsp-core/src/tools/navigation.ts
|
|
2489
|
+
async function executeLspGotoDefinition(params, signal) {
|
|
2490
|
+
const filePath = requireString(params, "filePath");
|
|
2491
|
+
const line = requireNumber(params, "line");
|
|
2492
|
+
const character = requireNumber(params, "character");
|
|
2493
|
+
try {
|
|
2494
|
+
const result = await withLspClient(filePath, async (client) => client.definition(filePath, line, character), "definition", clientOptions(signal));
|
|
2495
|
+
const locations = !result ? [] : Array.isArray(result) ? result : [result];
|
|
2496
|
+
const details = {
|
|
2497
|
+
filePath,
|
|
2498
|
+
line,
|
|
2499
|
+
character,
|
|
2500
|
+
locations
|
|
2501
|
+
};
|
|
2502
|
+
if (locations.length === 0) return text("No definition found", details);
|
|
2503
|
+
return text(locations.map(formatLocation).join("\n"), details);
|
|
2504
|
+
} catch (error) {
|
|
2505
|
+
const missingDependency = missingDependencyResult(error, {
|
|
2506
|
+
filePath,
|
|
2507
|
+
line,
|
|
2508
|
+
character,
|
|
2509
|
+
locations: []
|
|
2510
|
+
});
|
|
2511
|
+
if (missingDependency) return missingDependency;
|
|
2512
|
+
throw error;
|
|
2513
|
+
}
|
|
2514
|
+
}
|
|
2515
|
+
async function executeLspFindReferences(params, signal) {
|
|
2516
|
+
const filePath = requireString(params, "filePath");
|
|
2517
|
+
const line = requireNumber(params, "line");
|
|
2518
|
+
const character = requireNumber(params, "character");
|
|
2519
|
+
const includeDeclaration = optionalBoolean(params, "includeDeclaration") ?? true;
|
|
2520
|
+
try {
|
|
2521
|
+
const result = await withLspClient(filePath, async (client) => client.references(filePath, line, character, includeDeclaration), "references", clientOptions(signal));
|
|
2522
|
+
const references = Array.isArray(result) ? result : [];
|
|
2523
|
+
const total = references.length;
|
|
2524
|
+
const truncated = total > 200;
|
|
2525
|
+
const limited = truncated ? references.slice(0, 200) : references;
|
|
2526
|
+
const details = {
|
|
2527
|
+
filePath,
|
|
2528
|
+
line,
|
|
2529
|
+
character,
|
|
2530
|
+
references,
|
|
2531
|
+
totalReferences: total,
|
|
2532
|
+
truncated
|
|
2533
|
+
};
|
|
2534
|
+
if (total === 0) return text("No references found", details);
|
|
2535
|
+
return text([...truncated ? [`Found ${total} references (showing first 200):`] : [], ...limited.map(formatLocation)].join("\n"), details);
|
|
2536
|
+
} catch (error) {
|
|
2537
|
+
const missingDependency = missingDependencyResult(error, {
|
|
2538
|
+
filePath,
|
|
2539
|
+
line,
|
|
2540
|
+
character,
|
|
2541
|
+
references: [],
|
|
2542
|
+
totalReferences: 0,
|
|
2543
|
+
truncated: false
|
|
2544
|
+
});
|
|
2545
|
+
if (missingDependency) return missingDependency;
|
|
2546
|
+
throw error;
|
|
2547
|
+
}
|
|
2548
|
+
}
|
|
2549
|
+
//#endregion
|
|
2550
|
+
//#region packages/lsp-core/src/lsp/workspace-edit.ts
|
|
2551
|
+
function errorMessage(error) {
|
|
2552
|
+
return error instanceof Error ? error.message : String(error);
|
|
2553
|
+
}
|
|
2554
|
+
function isPathInsideWorkspace(filePath, workspaceRoot) {
|
|
2555
|
+
const relativePath = relative(workspaceRoot, filePath);
|
|
2556
|
+
return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute(relativePath);
|
|
2557
|
+
}
|
|
2558
|
+
function realpathForValidation(filePath) {
|
|
2559
|
+
if (existsSync(filePath)) return realpathSync(filePath);
|
|
2560
|
+
const parent = dirname(filePath);
|
|
2561
|
+
return resolve(realpathSync(parent), relative(parent, filePath));
|
|
2562
|
+
}
|
|
2563
|
+
function uriToWorkspacePath(uri, workspaceRoot) {
|
|
2564
|
+
let filePath;
|
|
2565
|
+
try {
|
|
2566
|
+
filePath = fileURLToPath(uri);
|
|
2567
|
+
} catch (error) {
|
|
2568
|
+
return {
|
|
2569
|
+
success: false,
|
|
2570
|
+
error: `non-file URI ${uri}: ${errorMessage(error)}`
|
|
2571
|
+
};
|
|
2572
|
+
}
|
|
2573
|
+
let validatedPath;
|
|
2574
|
+
try {
|
|
2575
|
+
validatedPath = realpathForValidation(filePath);
|
|
2576
|
+
} catch (error) {
|
|
2577
|
+
return {
|
|
2578
|
+
success: false,
|
|
2579
|
+
error: `${filePath}: ${errorMessage(error)}`
|
|
2580
|
+
};
|
|
2581
|
+
}
|
|
2582
|
+
if (!isPathInsideWorkspace(validatedPath, workspaceRoot)) return {
|
|
2583
|
+
success: false,
|
|
2584
|
+
error: `${filePath}: outside workspace ${workspaceRoot}`
|
|
2585
|
+
};
|
|
2586
|
+
return {
|
|
2587
|
+
success: true,
|
|
2588
|
+
path: filePath
|
|
2589
|
+
};
|
|
2590
|
+
}
|
|
2591
|
+
function applyTextEditsToFile(filePath, edits) {
|
|
2592
|
+
try {
|
|
2593
|
+
const lines = readFileSync(filePath, "utf-8").split("\n");
|
|
2594
|
+
const sortedEdits = [...edits].sort((a, b) => {
|
|
2595
|
+
if (b.range.start.line !== a.range.start.line) return b.range.start.line - a.range.start.line;
|
|
2596
|
+
return b.range.start.character - a.range.start.character;
|
|
2597
|
+
});
|
|
2598
|
+
for (const edit of sortedEdits) {
|
|
2599
|
+
const startLine = edit.range.start.line;
|
|
2600
|
+
const startChar = edit.range.start.character;
|
|
2601
|
+
const endLine = edit.range.end.line;
|
|
2602
|
+
const endChar = edit.range.end.character;
|
|
2603
|
+
if (startLine === endLine) {
|
|
2604
|
+
const line = lines[startLine] ?? "";
|
|
2605
|
+
lines[startLine] = line.substring(0, startChar) + edit.newText + line.substring(endChar);
|
|
2606
|
+
} else {
|
|
2607
|
+
const firstLine = lines[startLine] ?? "";
|
|
2608
|
+
const lastLine = lines[endLine] ?? "";
|
|
2609
|
+
const newContent = firstLine.substring(0, startChar) + edit.newText + lastLine.substring(endChar);
|
|
2610
|
+
lines.splice(startLine, endLine - startLine + 1, ...newContent.split("\n"));
|
|
2611
|
+
}
|
|
2612
|
+
}
|
|
2613
|
+
writeFileSync(filePath, lines.join("\n"), "utf-8");
|
|
2614
|
+
return {
|
|
2615
|
+
success: true,
|
|
2616
|
+
editCount: edits.length
|
|
2617
|
+
};
|
|
2618
|
+
} catch (err) {
|
|
2619
|
+
return {
|
|
2620
|
+
success: false,
|
|
2621
|
+
editCount: 0,
|
|
2622
|
+
error: err instanceof Error ? err.message : String(err)
|
|
2623
|
+
};
|
|
2624
|
+
}
|
|
2625
|
+
}
|
|
2626
|
+
function applyWorkspaceEdit(edit, options = {}) {
|
|
2627
|
+
if (!edit) return {
|
|
2628
|
+
success: false,
|
|
2629
|
+
filesModified: [],
|
|
2630
|
+
totalEdits: 0,
|
|
2631
|
+
errors: ["No edit provided"]
|
|
2632
|
+
};
|
|
2633
|
+
const result = {
|
|
2634
|
+
success: true,
|
|
2635
|
+
filesModified: [],
|
|
2636
|
+
totalEdits: 0,
|
|
2637
|
+
errors: []
|
|
2638
|
+
};
|
|
2639
|
+
const workspaceRoot = realpathSync(options.workspaceRoot ?? contextCwd());
|
|
2640
|
+
if (edit.changes) for (const [uri, edits] of Object.entries(edit.changes)) {
|
|
2641
|
+
const validatedPath = uriToWorkspacePath(uri, workspaceRoot);
|
|
2642
|
+
if (!validatedPath.success) {
|
|
2643
|
+
result.success = false;
|
|
2644
|
+
result.errors.push(validatedPath.error);
|
|
2645
|
+
continue;
|
|
2646
|
+
}
|
|
2647
|
+
const applyResult = applyTextEditsToFile(validatedPath.path, edits);
|
|
2648
|
+
if (applyResult.success) {
|
|
2649
|
+
result.filesModified.push(validatedPath.path);
|
|
2650
|
+
result.totalEdits += applyResult.editCount;
|
|
2651
|
+
} else {
|
|
2652
|
+
result.success = false;
|
|
2653
|
+
result.errors.push(`${validatedPath.path}: ${applyResult.error}`);
|
|
2654
|
+
}
|
|
2655
|
+
}
|
|
2656
|
+
if (edit.documentChanges) for (const change of edit.documentChanges) {
|
|
2657
|
+
if (!("kind" in change)) {
|
|
2658
|
+
const validatedPath = uriToWorkspacePath(change.textDocument.uri, workspaceRoot);
|
|
2659
|
+
if (!validatedPath.success) {
|
|
2660
|
+
result.success = false;
|
|
2661
|
+
result.errors.push(validatedPath.error);
|
|
2662
|
+
continue;
|
|
2663
|
+
}
|
|
2664
|
+
const applyResult = applyTextEditsToFile(validatedPath.path, change.edits);
|
|
2665
|
+
if (applyResult.success) {
|
|
2666
|
+
result.filesModified.push(validatedPath.path);
|
|
2667
|
+
result.totalEdits += applyResult.editCount;
|
|
2668
|
+
} else {
|
|
2669
|
+
result.success = false;
|
|
2670
|
+
result.errors.push(`${validatedPath.path}: ${applyResult.error}`);
|
|
2671
|
+
}
|
|
2672
|
+
continue;
|
|
2673
|
+
}
|
|
2674
|
+
if (change.kind === "create") try {
|
|
2675
|
+
const validatedPath = uriToWorkspacePath(change.uri, workspaceRoot);
|
|
2676
|
+
if (!validatedPath.success) {
|
|
2677
|
+
result.success = false;
|
|
2678
|
+
result.errors.push(`Create ${change.uri}: ${validatedPath.error}`);
|
|
2679
|
+
continue;
|
|
2680
|
+
}
|
|
2681
|
+
writeFileSync(validatedPath.path, "", "utf-8");
|
|
2682
|
+
result.filesModified.push(validatedPath.path);
|
|
2683
|
+
} catch (err) {
|
|
2684
|
+
result.success = false;
|
|
2685
|
+
result.errors.push(`Create ${change.uri}: ${String(err)}`);
|
|
2686
|
+
}
|
|
2687
|
+
else if (change.kind === "rename") try {
|
|
2688
|
+
const oldPath = uriToWorkspacePath(change.oldUri, workspaceRoot);
|
|
2689
|
+
const newPath = uriToWorkspacePath(change.newUri, workspaceRoot);
|
|
2690
|
+
if (!oldPath.success || !newPath.success) {
|
|
2691
|
+
const error = oldPath.success ? newPath.success ? "invalid URI" : newPath.error : oldPath.error;
|
|
2692
|
+
result.success = false;
|
|
2693
|
+
result.errors.push(`Rename ${change.oldUri}: ${error}`);
|
|
2694
|
+
continue;
|
|
2695
|
+
}
|
|
2696
|
+
const content = readFileSync(oldPath.path, "utf-8");
|
|
2697
|
+
writeFileSync(newPath.path, content, "utf-8");
|
|
2698
|
+
unlinkSync(oldPath.path);
|
|
2699
|
+
result.filesModified.push(newPath.path);
|
|
2700
|
+
} catch (err) {
|
|
2701
|
+
result.success = false;
|
|
2702
|
+
result.errors.push(`Rename ${change.oldUri}: ${String(err)}`);
|
|
2703
|
+
}
|
|
2704
|
+
else if (change.kind === "delete") try {
|
|
2705
|
+
const validatedPath = uriToWorkspacePath(change.uri, workspaceRoot);
|
|
2706
|
+
if (!validatedPath.success) {
|
|
2707
|
+
result.success = false;
|
|
2708
|
+
result.errors.push(`Delete ${change.uri}: ${validatedPath.error}`);
|
|
2709
|
+
continue;
|
|
2710
|
+
}
|
|
2711
|
+
unlinkSync(validatedPath.path);
|
|
2712
|
+
result.filesModified.push(validatedPath.path);
|
|
2713
|
+
} catch (err) {
|
|
2714
|
+
result.success = false;
|
|
2715
|
+
result.errors.push(`Delete ${change.uri}: ${String(err)}`);
|
|
2716
|
+
}
|
|
2717
|
+
}
|
|
2718
|
+
return result;
|
|
2719
|
+
}
|
|
2720
|
+
//#endregion
|
|
2721
|
+
//#region packages/lsp-core/src/tools/rename.ts
|
|
2722
|
+
async function executeLspPrepareRename(params, signal) {
|
|
2723
|
+
const filePath = requireString(params, "filePath");
|
|
2724
|
+
const line = requireNumber(params, "line");
|
|
2725
|
+
const character = requireNumber(params, "character");
|
|
2726
|
+
try {
|
|
2727
|
+
const result = await withLspClient(filePath, async (client) => client.prepareRename(filePath, line, character), "prepareRename", clientOptions(signal));
|
|
2728
|
+
const details = {
|
|
2729
|
+
filePath,
|
|
2730
|
+
line,
|
|
2731
|
+
character,
|
|
2732
|
+
result
|
|
2733
|
+
};
|
|
2734
|
+
return text(formatPrepareRenameResult(result), details);
|
|
2735
|
+
} catch (error) {
|
|
2736
|
+
const missingDependency = missingDependencyResult(error, {
|
|
2737
|
+
filePath,
|
|
2738
|
+
line,
|
|
2739
|
+
character,
|
|
2740
|
+
result: null
|
|
2741
|
+
});
|
|
2742
|
+
if (missingDependency) return missingDependency;
|
|
2743
|
+
throw error;
|
|
2744
|
+
}
|
|
2745
|
+
}
|
|
2746
|
+
async function executeLspRename(params, signal) {
|
|
2747
|
+
const filePath = requireString(params, "filePath");
|
|
2748
|
+
const line = requireNumber(params, "line");
|
|
2749
|
+
const character = requireNumber(params, "character");
|
|
2750
|
+
const newName = requireString(params, "newName");
|
|
2751
|
+
try {
|
|
2752
|
+
const edit = await withLspClient(filePath, async (client, workspaceRoot) => ({
|
|
2753
|
+
edit: await client.rename(filePath, line, character, newName),
|
|
2754
|
+
workspaceRoot
|
|
2755
|
+
}), "rename", clientOptions(signal));
|
|
2756
|
+
const apply = applyWorkspaceEdit(edit.edit, { workspaceRoot: edit.workspaceRoot });
|
|
2757
|
+
const details = {
|
|
2758
|
+
filePath,
|
|
2759
|
+
line,
|
|
2760
|
+
character,
|
|
2761
|
+
newName,
|
|
2762
|
+
apply,
|
|
2763
|
+
edit: edit.edit
|
|
2764
|
+
};
|
|
2765
|
+
return text(formatApplyResult(apply), details, !apply.success);
|
|
2766
|
+
} catch (error) {
|
|
2767
|
+
const missingDependency = missingDependencyResult(error, {
|
|
2768
|
+
filePath,
|
|
2769
|
+
line,
|
|
2770
|
+
character,
|
|
2771
|
+
newName,
|
|
2772
|
+
apply: null,
|
|
2773
|
+
edit: null
|
|
2774
|
+
});
|
|
2775
|
+
if (missingDependency) return missingDependency;
|
|
2776
|
+
throw error;
|
|
2777
|
+
}
|
|
2778
|
+
}
|
|
2779
|
+
//#endregion
|
|
2780
|
+
//#region packages/lsp-core/src/tools/schema.ts
|
|
2781
|
+
function objectSchema(properties, required = []) {
|
|
2782
|
+
return {
|
|
2783
|
+
type: "object",
|
|
2784
|
+
properties,
|
|
2785
|
+
required
|
|
2786
|
+
};
|
|
2787
|
+
}
|
|
2788
|
+
//#endregion
|
|
2789
|
+
//#region packages/lsp-core/src/tools/status.ts
|
|
2790
|
+
async function executeLspStatus() {
|
|
2791
|
+
const servers = getAllServers();
|
|
2792
|
+
const snapshots = getLspManager().getSnapshot();
|
|
2793
|
+
const installed = servers.filter((server) => server.installed && !server.disabled);
|
|
2794
|
+
const configuredLines = servers.map((server) => {
|
|
2795
|
+
const state = server.disabled ? "disabled" : server.installed ? "installed" : "missing";
|
|
2796
|
+
return `- ${server.id}: ${state}; source=${server.source}; extensions=${server.extensions.join(", ")}`;
|
|
2797
|
+
});
|
|
2798
|
+
const activeLines = snapshots.map((snapshot) => {
|
|
2799
|
+
const state = snapshot.alive ? snapshot.isInitializing ? "initializing" : "alive" : "dead";
|
|
2800
|
+
return `- ${snapshot.serverId}: ${state}; root=${snapshot.root}; refs=${snapshot.refCount}`;
|
|
2801
|
+
});
|
|
2802
|
+
return text([
|
|
2803
|
+
`Configured LSP servers: ${servers.length}`,
|
|
2804
|
+
`Installed LSP servers: ${installed.length}`,
|
|
2805
|
+
"",
|
|
2806
|
+
...configuredLines,
|
|
2807
|
+
"",
|
|
2808
|
+
`Active LSP clients: ${snapshots.length}`,
|
|
2809
|
+
...activeLines
|
|
2810
|
+
].join("\n"), {
|
|
2811
|
+
servers,
|
|
2812
|
+
snapshots
|
|
2813
|
+
});
|
|
2814
|
+
}
|
|
2815
|
+
//#endregion
|
|
2816
|
+
//#region packages/lsp-core/src/tools/symbols.ts
|
|
2817
|
+
function isDocumentSymbol(symbol) {
|
|
2818
|
+
return "range" in symbol;
|
|
2819
|
+
}
|
|
2820
|
+
async function executeLspSymbols(params, signal) {
|
|
2821
|
+
const filePath = requireString(params, "filePath");
|
|
2822
|
+
const scope = (optionalString(params, "scope") ?? "document") === "workspace" ? "workspace" : "document";
|
|
2823
|
+
const limit = Math.min(optionalNumber(params, "limit") ?? 200, 200);
|
|
2824
|
+
try {
|
|
2825
|
+
if (scope === "workspace") {
|
|
2826
|
+
const query = optionalString(params, "query");
|
|
2827
|
+
if (!query) {
|
|
2828
|
+
const message = "Error: 'query' is required for workspace scope";
|
|
2829
|
+
return text(message, {
|
|
2830
|
+
filePath,
|
|
2831
|
+
scope,
|
|
2832
|
+
symbols: [],
|
|
2833
|
+
totalSymbols: 0,
|
|
2834
|
+
truncated: false,
|
|
2835
|
+
error: message,
|
|
2836
|
+
errorKind: "missing_query"
|
|
2837
|
+
});
|
|
2838
|
+
}
|
|
2839
|
+
return formatSymbolsResult(filePath, scope, await withLspClient(filePath, async (client) => client.workspaceSymbols(query), "workspaceSymbols", clientOptions(signal)), limit, query);
|
|
2840
|
+
}
|
|
2841
|
+
return formatSymbolsResult(filePath, scope, await withLspClient(filePath, async (client) => client.documentSymbols(filePath), "documentSymbols", clientOptions(signal)), limit);
|
|
2842
|
+
} catch (error) {
|
|
2843
|
+
const query = optionalString(params, "query");
|
|
2844
|
+
const missingDependency = missingDependencyResult(error, {
|
|
2845
|
+
filePath,
|
|
2846
|
+
scope,
|
|
2847
|
+
symbols: [],
|
|
2848
|
+
totalSymbols: 0,
|
|
2849
|
+
truncated: false,
|
|
2850
|
+
...query === void 0 ? {} : { query }
|
|
2851
|
+
});
|
|
2852
|
+
if (missingDependency) return missingDependency;
|
|
2853
|
+
throw error;
|
|
2854
|
+
}
|
|
2855
|
+
}
|
|
2856
|
+
function formatSymbolsResult(filePath, scope, symbols, limit, query) {
|
|
2857
|
+
const total = symbols.length;
|
|
2858
|
+
const truncated = total > limit;
|
|
2859
|
+
const limited = truncated ? symbols.slice(0, limit) : symbols;
|
|
2860
|
+
const details = {
|
|
2861
|
+
filePath,
|
|
2862
|
+
scope,
|
|
2863
|
+
symbols,
|
|
2864
|
+
totalSymbols: total,
|
|
2865
|
+
truncated,
|
|
2866
|
+
...query === void 0 ? {} : { query }
|
|
2867
|
+
};
|
|
2868
|
+
if (total === 0) return text("No symbols found", details);
|
|
2869
|
+
const lines = [];
|
|
2870
|
+
if (truncated) lines.push(`Found ${total} symbols (showing first ${limit}):`);
|
|
2871
|
+
const documentSymbols = limited.filter(isDocumentSymbol);
|
|
2872
|
+
if (documentSymbols.length === limited.length) lines.push(...documentSymbols.map((symbol) => formatDocumentSymbol(symbol)));
|
|
2873
|
+
else lines.push(...limited.filter((symbol) => !isDocumentSymbol(symbol)).map(formatSymbolInfo));
|
|
2874
|
+
return text(lines.join("\n"), details);
|
|
2875
|
+
}
|
|
2876
|
+
//#endregion
|
|
2877
|
+
//#region packages/lsp-core/src/tools/definitions.ts
|
|
2878
|
+
var LSP_MCP_TOOLS = [
|
|
2879
|
+
{
|
|
2880
|
+
name: "status",
|
|
2881
|
+
aliases: ["lsp_status"],
|
|
2882
|
+
title: "LSP Status",
|
|
2883
|
+
description: "Use to inspect configured and active LSP servers without starting one.",
|
|
2884
|
+
inputSchema: objectSchema({}),
|
|
2885
|
+
execute: executeLspStatus
|
|
2886
|
+
},
|
|
2887
|
+
{
|
|
2888
|
+
name: "diagnostics",
|
|
2889
|
+
aliases: ["lsp_diagnostics"],
|
|
2890
|
+
title: "LSP Diagnostics",
|
|
2891
|
+
description: "Use after code edits or during diagnosis to get errors, warnings, and hints for a file or directory.",
|
|
2892
|
+
inputSchema: objectSchema({
|
|
2893
|
+
filePath: {
|
|
2894
|
+
type: "string",
|
|
2895
|
+
description: "File or directory path to check."
|
|
2896
|
+
},
|
|
2897
|
+
severity: {
|
|
2898
|
+
type: "string",
|
|
2899
|
+
enum: [
|
|
2900
|
+
"error",
|
|
2901
|
+
"warning",
|
|
2902
|
+
"information",
|
|
2903
|
+
"hint",
|
|
2904
|
+
"all"
|
|
2905
|
+
],
|
|
2906
|
+
description: "Severity filter. Defaults to all."
|
|
2907
|
+
}
|
|
2908
|
+
}, ["filePath"]),
|
|
2909
|
+
execute: executeLspDiagnostics
|
|
2910
|
+
},
|
|
2911
|
+
{
|
|
2912
|
+
name: "goto_definition",
|
|
2913
|
+
aliases: ["lsp_goto_definition"],
|
|
2914
|
+
title: "LSP Goto Definition",
|
|
2915
|
+
description: "Use to find the exact definition of a symbol before changing or explaining it.",
|
|
2916
|
+
inputSchema: objectSchema({
|
|
2917
|
+
filePath: {
|
|
2918
|
+
type: "string",
|
|
2919
|
+
description: "Source file containing the symbol."
|
|
2920
|
+
},
|
|
2921
|
+
line: {
|
|
2922
|
+
type: "number",
|
|
2923
|
+
description: "1-based line number."
|
|
2924
|
+
},
|
|
2925
|
+
character: {
|
|
2926
|
+
type: "number",
|
|
2927
|
+
description: "0-based column."
|
|
2928
|
+
}
|
|
2929
|
+
}, [
|
|
2930
|
+
"filePath",
|
|
2931
|
+
"line",
|
|
2932
|
+
"character"
|
|
2933
|
+
]),
|
|
2934
|
+
execute: executeLspGotoDefinition
|
|
2935
|
+
},
|
|
2936
|
+
{
|
|
2937
|
+
name: "find_references",
|
|
2938
|
+
aliases: ["lsp_find_references"],
|
|
2939
|
+
title: "LSP Find References",
|
|
2940
|
+
description: "Use to find every workspace reference before refactoring, renaming, or assessing impact.",
|
|
2941
|
+
inputSchema: objectSchema({
|
|
2942
|
+
filePath: {
|
|
2943
|
+
type: "string",
|
|
2944
|
+
description: "Source file containing the symbol."
|
|
2945
|
+
},
|
|
2946
|
+
line: {
|
|
2947
|
+
type: "number",
|
|
2948
|
+
description: "1-based line number."
|
|
2949
|
+
},
|
|
2950
|
+
character: {
|
|
2951
|
+
type: "number",
|
|
2952
|
+
description: "0-based column."
|
|
2953
|
+
},
|
|
2954
|
+
includeDeclaration: {
|
|
2955
|
+
type: "boolean",
|
|
2956
|
+
description: "Include the declaration. Defaults to true."
|
|
2957
|
+
}
|
|
2958
|
+
}, [
|
|
2959
|
+
"filePath",
|
|
2960
|
+
"line",
|
|
2961
|
+
"character"
|
|
2962
|
+
]),
|
|
2963
|
+
execute: executeLspFindReferences
|
|
2964
|
+
},
|
|
2965
|
+
{
|
|
2966
|
+
name: "symbols",
|
|
2967
|
+
aliases: ["lsp_symbols"],
|
|
2968
|
+
title: "LSP Symbols",
|
|
2969
|
+
description: "Use to outline one file or locate named symbols across the workspace.",
|
|
2970
|
+
inputSchema: objectSchema({
|
|
2971
|
+
filePath: {
|
|
2972
|
+
type: "string",
|
|
2973
|
+
description: "File path used as LSP context."
|
|
2974
|
+
},
|
|
2975
|
+
scope: {
|
|
2976
|
+
type: "string",
|
|
2977
|
+
enum: ["document", "workspace"],
|
|
2978
|
+
description: "Use document for file outline or workspace for project-wide search."
|
|
2979
|
+
},
|
|
2980
|
+
query: {
|
|
2981
|
+
type: "string",
|
|
2982
|
+
description: "Workspace symbol query."
|
|
2983
|
+
},
|
|
2984
|
+
limit: {
|
|
2985
|
+
type: "number",
|
|
2986
|
+
description: "Maximum number of symbols to return."
|
|
2987
|
+
}
|
|
2988
|
+
}, ["filePath", "scope"]),
|
|
2989
|
+
execute: executeLspSymbols
|
|
2990
|
+
},
|
|
2991
|
+
{
|
|
2992
|
+
name: "prepare_rename",
|
|
2993
|
+
aliases: ["lsp_prepare_rename"],
|
|
2994
|
+
title: "LSP Prepare Rename",
|
|
2995
|
+
description: "Use before rename to verify the symbol and position support a semantic rename.",
|
|
2996
|
+
inputSchema: objectSchema({
|
|
2997
|
+
filePath: {
|
|
2998
|
+
type: "string",
|
|
2999
|
+
description: "Source file path."
|
|
3000
|
+
},
|
|
3001
|
+
line: {
|
|
3002
|
+
type: "number",
|
|
3003
|
+
description: "1-based line number."
|
|
3004
|
+
},
|
|
3005
|
+
character: {
|
|
3006
|
+
type: "number",
|
|
3007
|
+
description: "0-based column."
|
|
3008
|
+
}
|
|
3009
|
+
}, [
|
|
3010
|
+
"filePath",
|
|
3011
|
+
"line",
|
|
3012
|
+
"character"
|
|
3013
|
+
]),
|
|
3014
|
+
execute: executeLspPrepareRename
|
|
3015
|
+
},
|
|
3016
|
+
{
|
|
3017
|
+
name: "rename",
|
|
3018
|
+
aliases: ["lsp_rename"],
|
|
3019
|
+
title: "LSP Rename",
|
|
3020
|
+
description: "Use for a semantic workspace-wide symbol rename after prepare_rename succeeds.",
|
|
3021
|
+
inputSchema: objectSchema({
|
|
3022
|
+
filePath: {
|
|
3023
|
+
type: "string",
|
|
3024
|
+
description: "Source file path."
|
|
3025
|
+
},
|
|
3026
|
+
line: {
|
|
3027
|
+
type: "number",
|
|
3028
|
+
description: "1-based line number."
|
|
3029
|
+
},
|
|
3030
|
+
character: {
|
|
3031
|
+
type: "number",
|
|
3032
|
+
description: "0-based column."
|
|
3033
|
+
},
|
|
3034
|
+
newName: {
|
|
3035
|
+
type: "string",
|
|
3036
|
+
description: "New symbol name."
|
|
3037
|
+
}
|
|
3038
|
+
}, [
|
|
3039
|
+
"filePath",
|
|
3040
|
+
"line",
|
|
3041
|
+
"character",
|
|
3042
|
+
"newName"
|
|
3043
|
+
]),
|
|
3044
|
+
execute: executeLspRename
|
|
3045
|
+
},
|
|
3046
|
+
{
|
|
3047
|
+
name: "install_decision",
|
|
3048
|
+
aliases: ["lsp_install_decision"],
|
|
3049
|
+
title: "LSP Install Decision",
|
|
3050
|
+
description: "Use after a missing-server prompt to record explicit install permission or a decline; decline when permission was not explicit.",
|
|
3051
|
+
inputSchema: objectSchema({
|
|
3052
|
+
server_id: {
|
|
3053
|
+
type: "string",
|
|
3054
|
+
description: "The LSP server id from the not-installed message (e.g. 'rust')."
|
|
3055
|
+
},
|
|
3056
|
+
decision: {
|
|
3057
|
+
type: "string",
|
|
3058
|
+
enum: ["declined", "allowed"],
|
|
3059
|
+
description: "'declined' silences future prompts; 'allowed' pre-authorizes installation."
|
|
3060
|
+
}
|
|
3061
|
+
}, ["server_id", "decision"]),
|
|
3062
|
+
execute: executeLspInstallDecision
|
|
3063
|
+
}
|
|
3064
|
+
];
|
|
3065
|
+
//#endregion
|
|
3066
|
+
//#region packages/lsp-core/src/tools/runtime.ts
|
|
3067
|
+
async function executeLspTool(name, params, signal) {
|
|
3068
|
+
const tool = LSP_MCP_TOOLS.find((candidate) => matchesToolName(candidate, name));
|
|
3069
|
+
if (!tool) throw new Error(`Unknown LSP tool: ${name}`);
|
|
3070
|
+
return tool.execute(params, signal);
|
|
3071
|
+
}
|
|
3072
|
+
function matchesToolName(tool, name) {
|
|
3073
|
+
return tool.name === name || (tool.aliases?.includes(name) ?? false);
|
|
3074
|
+
}
|
|
3075
|
+
function coerceToolArguments(value) {
|
|
3076
|
+
return isRecord(value) ? value : {};
|
|
3077
|
+
}
|
|
3078
|
+
//#endregion
|
|
3079
|
+
//#region packages/lsp-core/src/mcp.ts
|
|
3080
|
+
var SERVER_NAME = "lsp";
|
|
3081
|
+
var SERVER_VERSION = "0.2.1";
|
|
3082
|
+
async function handleLspMcpRequest(input) {
|
|
3083
|
+
if (!isPlainRecord(input)) return errorResponse(null, -32600, "Invalid Request");
|
|
3084
|
+
const id = jsonRpcId(input["id"]);
|
|
3085
|
+
const method = input["method"];
|
|
3086
|
+
if (method === "notifications/initialized") return void 0;
|
|
3087
|
+
if (method === "ping") return successResponse(id, {});
|
|
3088
|
+
if (method === "initialize") {
|
|
3089
|
+
const protocolVersion = requestedProtocolVersion(input["params"]);
|
|
3090
|
+
return successResponse(id, {
|
|
3091
|
+
capabilities: { tools: { listChanged: false } },
|
|
3092
|
+
serverInfo: {
|
|
3093
|
+
name: SERVER_NAME,
|
|
3094
|
+
version: SERVER_VERSION
|
|
3095
|
+
},
|
|
3096
|
+
protocolVersion
|
|
3097
|
+
});
|
|
3098
|
+
}
|
|
3099
|
+
if (method === "tools/list") return successResponse(id, { tools: LSP_MCP_TOOLS.map(describeTool) });
|
|
3100
|
+
if (method === "tools/call") return handleToolCall(id, input["params"]);
|
|
3101
|
+
return errorResponse(id, -32601, `Method not found: ${String(method)}`);
|
|
3102
|
+
}
|
|
3103
|
+
async function handleToolCall(id, params) {
|
|
3104
|
+
if (!isPlainRecord(params) || typeof params["name"] !== "string") return errorResponse(id, -32602, "tools/call requires params.name");
|
|
3105
|
+
try {
|
|
3106
|
+
const result = await executeLspTool(params["name"], coerceToolArguments(params["arguments"]));
|
|
3107
|
+
return successResponse(id, {
|
|
3108
|
+
content: result.content,
|
|
3109
|
+
isError: result.isError ?? false,
|
|
3110
|
+
details: result.details
|
|
3111
|
+
});
|
|
3112
|
+
} catch (error) {
|
|
3113
|
+
return successResponse(id, {
|
|
3114
|
+
content: [{
|
|
3115
|
+
type: "text",
|
|
3116
|
+
text: messageFromError(error)
|
|
3117
|
+
}],
|
|
3118
|
+
isError: true
|
|
3119
|
+
});
|
|
3120
|
+
}
|
|
3121
|
+
}
|
|
3122
|
+
function describeTool(tool) {
|
|
3123
|
+
return {
|
|
3124
|
+
name: tool.name,
|
|
3125
|
+
title: tool.title,
|
|
3126
|
+
description: tool.description,
|
|
3127
|
+
inputSchema: tool.inputSchema
|
|
3128
|
+
};
|
|
3129
|
+
}
|
|
3130
|
+
function requestedProtocolVersion(params) {
|
|
3131
|
+
if (!isPlainRecord(params) || typeof params["protocolVersion"] !== "string") return "2024-11-05";
|
|
3132
|
+
return params["protocolVersion"];
|
|
3133
|
+
}
|
|
3134
|
+
//#endregion
|
|
3135
|
+
//#region packages/lsp-daemon/src/lock.ts
|
|
3136
|
+
function isProcessAlive(pid) {
|
|
3137
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
3138
|
+
try {
|
|
3139
|
+
process.kill(pid, 0);
|
|
3140
|
+
return true;
|
|
3141
|
+
} catch (error) {
|
|
3142
|
+
return error.code === "EPERM";
|
|
3143
|
+
}
|
|
3144
|
+
}
|
|
3145
|
+
function readLockPid(lockPath) {
|
|
3146
|
+
try {
|
|
3147
|
+
const pid = Number.parseInt(readFileSync(lockPath, "utf8").trim(), 10);
|
|
3148
|
+
return Number.isInteger(pid) ? pid : null;
|
|
3149
|
+
} catch {
|
|
3150
|
+
return null;
|
|
3151
|
+
}
|
|
3152
|
+
}
|
|
3153
|
+
function tryAcquireLock(lockPath, ownerPid = process.pid) {
|
|
3154
|
+
mkdirSync(dirname(lockPath), { recursive: true });
|
|
3155
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
3156
|
+
const handle = writeLockFile(lockPath, ownerPid);
|
|
3157
|
+
if (handle) return handle;
|
|
3158
|
+
if (!reapStaleLock(lockPath)) return null;
|
|
3159
|
+
}
|
|
3160
|
+
return null;
|
|
3161
|
+
}
|
|
3162
|
+
function writeLockFile(lockPath, ownerPid) {
|
|
3163
|
+
try {
|
|
3164
|
+
const fd = openSync(lockPath, "wx");
|
|
3165
|
+
writeSync(fd, `${ownerPid}\n`);
|
|
3166
|
+
closeSync(fd);
|
|
3167
|
+
return { release: () => unlinkQuietly(lockPath) };
|
|
3168
|
+
} catch (error) {
|
|
3169
|
+
if (error.code === "EEXIST") return null;
|
|
3170
|
+
throw error;
|
|
3171
|
+
}
|
|
3172
|
+
}
|
|
3173
|
+
function reapStaleLock(lockPath) {
|
|
3174
|
+
const pid = readLockPid(lockPath);
|
|
3175
|
+
if (pid !== null && isProcessAlive(pid)) return false;
|
|
3176
|
+
unlinkQuietly(lockPath);
|
|
3177
|
+
return true;
|
|
3178
|
+
}
|
|
3179
|
+
function unlinkQuietly(path) {
|
|
3180
|
+
try {
|
|
3181
|
+
unlinkSync(path);
|
|
3182
|
+
} catch {}
|
|
3183
|
+
}
|
|
3184
|
+
//#endregion
|
|
3185
|
+
//#region packages/lsp-daemon/src/ensure-daemon.ts
|
|
3186
|
+
var PROBE_TIMEOUT_MS = 500;
|
|
3187
|
+
var DEFAULT_READY_TIMEOUT_MS = 5e3;
|
|
3188
|
+
var DEFAULT_POLL_INTERVAL_MS = 100;
|
|
3189
|
+
var CODEX_LSP_DAEMON_CLI_ENV = "CODEX_LSP_DAEMON_CLI";
|
|
3190
|
+
var DaemonUnreachableError = class extends Error {
|
|
3191
|
+
constructor(socketPath) {
|
|
3192
|
+
super(`LSP daemon did not become reachable at ${socketPath}`);
|
|
3193
|
+
this.name = "DaemonUnreachableError";
|
|
3194
|
+
}
|
|
3195
|
+
};
|
|
3196
|
+
async function ensureDaemonRunning(paths, deps = defaultEnsureDaemonDeps(), options = {}) {
|
|
3197
|
+
const readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
|
|
3198
|
+
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
3199
|
+
if (await deps.probe(paths.socket)) return;
|
|
3200
|
+
const lock = deps.acquireLock(paths.lock);
|
|
3201
|
+
if (!lock) {
|
|
3202
|
+
await waitUntilReachable(paths.socket, deps, readyTimeoutMs, pollIntervalMs);
|
|
3203
|
+
return;
|
|
3204
|
+
}
|
|
3205
|
+
try {
|
|
3206
|
+
if (await deps.probe(paths.socket)) return;
|
|
3207
|
+
deps.cleanupStaleSocket(paths.socket);
|
|
3208
|
+
deps.spawnDaemon(paths);
|
|
3209
|
+
await waitUntilReachable(paths.socket, deps, readyTimeoutMs, pollIntervalMs);
|
|
3210
|
+
} finally {
|
|
3211
|
+
lock.release();
|
|
3212
|
+
}
|
|
3213
|
+
}
|
|
3214
|
+
async function waitUntilReachable(socketPath, deps, readyTimeoutMs, pollIntervalMs) {
|
|
3215
|
+
const deadline = deps.now() + readyTimeoutMs;
|
|
3216
|
+
for (;;) {
|
|
3217
|
+
if (await deps.probe(socketPath)) return;
|
|
3218
|
+
if (deps.now() >= deadline) throw new DaemonUnreachableError(socketPath);
|
|
3219
|
+
await deps.sleep(pollIntervalMs);
|
|
3220
|
+
}
|
|
3221
|
+
}
|
|
3222
|
+
function probeSocket(socketPath, timeoutMs = PROBE_TIMEOUT_MS) {
|
|
3223
|
+
return new Promise((resolve) => {
|
|
3224
|
+
const socket = connect(socketPath);
|
|
3225
|
+
const finish = (ok) => {
|
|
3226
|
+
socket.destroy();
|
|
3227
|
+
resolve(ok);
|
|
3228
|
+
};
|
|
3229
|
+
const timer = setTimeout(() => finish(false), timeoutMs);
|
|
3230
|
+
timer.unref?.();
|
|
3231
|
+
socket.once("connect", () => {
|
|
3232
|
+
clearTimeout(timer);
|
|
3233
|
+
finish(true);
|
|
3234
|
+
});
|
|
3235
|
+
socket.once("error", () => {
|
|
3236
|
+
clearTimeout(timer);
|
|
3237
|
+
finish(false);
|
|
3238
|
+
});
|
|
3239
|
+
});
|
|
3240
|
+
}
|
|
3241
|
+
function spawnDaemonProcess(paths) {
|
|
3242
|
+
mkdirSync(dirname(paths.log), { recursive: true });
|
|
3243
|
+
const logFd = openSync(paths.log, "a");
|
|
3244
|
+
try {
|
|
3245
|
+
spawn(execPath, [resolveDaemonCliPath(), "daemon"], {
|
|
3246
|
+
detached: true,
|
|
3247
|
+
stdio: [
|
|
3248
|
+
"ignore",
|
|
3249
|
+
logFd,
|
|
3250
|
+
logFd
|
|
3251
|
+
]
|
|
3252
|
+
}).unref();
|
|
3253
|
+
} finally {
|
|
3254
|
+
closeSync(logFd);
|
|
3255
|
+
}
|
|
3256
|
+
}
|
|
3257
|
+
function resolveDaemonCliPath(env = process.env) {
|
|
3258
|
+
const override = env[CODEX_LSP_DAEMON_CLI_ENV]?.trim();
|
|
3259
|
+
if (override) return override;
|
|
3260
|
+
const current = fileURLToPath(import.meta.url);
|
|
3261
|
+
return basename(current) === "ensure-daemon.ts" ? join(dirname(current), "cli.ts") : current;
|
|
3262
|
+
}
|
|
3263
|
+
function defaultEnsureDaemonDeps() {
|
|
3264
|
+
return {
|
|
3265
|
+
probe: (socketPath) => probeSocket(socketPath),
|
|
3266
|
+
acquireLock: (lockPath) => tryAcquireLock(lockPath),
|
|
3267
|
+
cleanupStaleSocket: (socketPath) => {
|
|
3268
|
+
if (existsSync(socketPath)) unlinkQuietly(socketPath);
|
|
3269
|
+
},
|
|
3270
|
+
spawnDaemon: (paths) => spawnDaemonProcess(paths),
|
|
3271
|
+
sleep: (ms) => new Promise((resolve) => {
|
|
3272
|
+
setTimeout(resolve, ms);
|
|
3273
|
+
}),
|
|
3274
|
+
now: () => Date.now()
|
|
3275
|
+
};
|
|
3276
|
+
}
|
|
3277
|
+
//#endregion
|
|
3278
|
+
//#region packages/lsp-daemon/src/paths.ts
|
|
3279
|
+
var requireFromHere = createRequire(import.meta.url);
|
|
3280
|
+
var MAX_SOCKET_PATH_LENGTH = 100;
|
|
3281
|
+
var CODEX_LSP_DAEMON_VERSION_ENV = "CODEX_LSP_DAEMON_VERSION";
|
|
3282
|
+
function resolveDaemonVersion(requireFn = requireFromHere) {
|
|
3283
|
+
for (const candidate of ["./package.json", "../package.json"]) try {
|
|
3284
|
+
const pkg = requireFn(candidate);
|
|
3285
|
+
if (typeof pkg.version === "string" && pkg.version.length > 0) return pkg.version;
|
|
3286
|
+
} catch {}
|
|
3287
|
+
return "0";
|
|
3288
|
+
}
|
|
3289
|
+
function daemonBaseDir(env = process.env) {
|
|
3290
|
+
const explicit = env["CODEX_LSP_DAEMON_DIR"]?.trim();
|
|
3291
|
+
if (explicit) return explicit;
|
|
3292
|
+
const pluginData = env["PLUGIN_DATA"]?.trim();
|
|
3293
|
+
if (pluginData) return join(pluginData, "daemon");
|
|
3294
|
+
const codexHome = env["CODEX_HOME"]?.trim();
|
|
3295
|
+
return join(codexHome && codexHome.length > 0 ? codexHome : join(homedir(), ".codex"), "codex-lsp", "daemon");
|
|
3296
|
+
}
|
|
3297
|
+
function daemonPaths(env = process.env, version = resolveDaemonVersionFromEnv(env) ?? resolveDaemonVersion()) {
|
|
3298
|
+
const dir = join(daemonBaseDir(env), `v${version}`);
|
|
3299
|
+
return {
|
|
3300
|
+
version,
|
|
3301
|
+
dir,
|
|
3302
|
+
socket: resolveSocketPath(dir, version),
|
|
3303
|
+
lock: join(dir, "daemon.lock"),
|
|
3304
|
+
pid: join(dir, "daemon.pid"),
|
|
3305
|
+
log: join(dir, "daemon.log")
|
|
3306
|
+
};
|
|
3307
|
+
}
|
|
3308
|
+
function resolveDaemonVersionFromEnv(env = process.env) {
|
|
3309
|
+
const version = env[CODEX_LSP_DAEMON_VERSION_ENV]?.trim();
|
|
3310
|
+
return version && version.length > 0 ? version : null;
|
|
3311
|
+
}
|
|
3312
|
+
function resolveSocketPath(dir, version) {
|
|
3313
|
+
const digest = createHash("sha256").update(dir).digest("hex").slice(0, 16);
|
|
3314
|
+
if (process.platform === "win32") return `\\\\.\\pipe\\holycodex-lsp-${version}-${digest}`;
|
|
3315
|
+
const natural = join(dir, "daemon.sock");
|
|
3316
|
+
if (natural.length < MAX_SOCKET_PATH_LENGTH) return natural;
|
|
3317
|
+
return join(tmpdir(), `holycodex-lsp-${version}-${digest}.sock`);
|
|
3318
|
+
}
|
|
3319
|
+
//#endregion
|
|
3320
|
+
//#region packages/lsp-daemon/src/request-routing.ts
|
|
3321
|
+
var CONTEXT_KEY = "_context";
|
|
3322
|
+
function extractRequestContext(raw) {
|
|
3323
|
+
if (!isPlainRecord(raw) || raw["method"] !== "tools/call") return {
|
|
3324
|
+
input: raw,
|
|
3325
|
+
context: void 0
|
|
3326
|
+
};
|
|
3327
|
+
const params = raw["params"];
|
|
3328
|
+
if (!isPlainRecord(params)) return {
|
|
3329
|
+
input: raw,
|
|
3330
|
+
context: void 0
|
|
3331
|
+
};
|
|
3332
|
+
const args = params["arguments"];
|
|
3333
|
+
if (!isPlainRecord(args)) return {
|
|
3334
|
+
input: raw,
|
|
3335
|
+
context: void 0
|
|
3336
|
+
};
|
|
3337
|
+
const context = parseContext(args[CONTEXT_KEY]);
|
|
3338
|
+
if (!context) return {
|
|
3339
|
+
input: raw,
|
|
3340
|
+
context: void 0
|
|
3341
|
+
};
|
|
3342
|
+
const cleanedArgs = { ...args };
|
|
3343
|
+
delete cleanedArgs[CONTEXT_KEY];
|
|
3344
|
+
return {
|
|
3345
|
+
input: {
|
|
3346
|
+
...raw,
|
|
3347
|
+
params: {
|
|
3348
|
+
...params,
|
|
3349
|
+
arguments: cleanedArgs
|
|
3350
|
+
}
|
|
3351
|
+
},
|
|
3352
|
+
context
|
|
3353
|
+
};
|
|
3354
|
+
}
|
|
3355
|
+
function handleDaemonMessage(raw) {
|
|
3356
|
+
const { input, context } = extractRequestContext(raw);
|
|
3357
|
+
if (context) return runWithRequestContext(context, () => handleLspMcpRequest(input));
|
|
3358
|
+
return handleLspMcpRequest(input);
|
|
3359
|
+
}
|
|
3360
|
+
function parseContext(value) {
|
|
3361
|
+
if (!isPlainRecord(value)) return void 0;
|
|
3362
|
+
const context = {};
|
|
3363
|
+
const cwd = value["cwd"];
|
|
3364
|
+
if (typeof cwd === "string") context.cwd = cwd;
|
|
3365
|
+
const env = value["env"];
|
|
3366
|
+
if (isStringRecord(env)) context.env = env;
|
|
3367
|
+
return context.cwd === void 0 && context.env === void 0 ? void 0 : context;
|
|
3368
|
+
}
|
|
3369
|
+
function isStringRecord(value) {
|
|
3370
|
+
return isPlainRecord(value) && Object.values(value).every((item) => typeof item === "string");
|
|
3371
|
+
}
|
|
3372
|
+
//#endregion
|
|
3373
|
+
//#region packages/lsp-daemon/src/socket-jsonrpc.ts
|
|
3374
|
+
function encodeJsonLine(message) {
|
|
3375
|
+
return `${JSON.stringify(message)}\n`;
|
|
3376
|
+
}
|
|
3377
|
+
function createLineDecoder(onMessage, onParseError) {
|
|
3378
|
+
let buffer = "";
|
|
3379
|
+
return { push(chunk) {
|
|
3380
|
+
buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
3381
|
+
let index = buffer.indexOf("\n");
|
|
3382
|
+
while (index !== -1) {
|
|
3383
|
+
const raw = buffer.slice(0, index).trim();
|
|
3384
|
+
buffer = buffer.slice(index + 1);
|
|
3385
|
+
if (raw.length > 0) try {
|
|
3386
|
+
onMessage(JSON.parse(raw));
|
|
3387
|
+
} catch (error) {
|
|
3388
|
+
onParseError?.(raw, error);
|
|
3389
|
+
}
|
|
3390
|
+
index = buffer.indexOf("\n");
|
|
3391
|
+
}
|
|
3392
|
+
} };
|
|
3393
|
+
}
|
|
3394
|
+
//#endregion
|
|
3395
|
+
//#region packages/lsp-daemon/src/daemon-client.ts
|
|
3396
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
|
|
3397
|
+
var REQUEST_ID = 1;
|
|
3398
|
+
var DaemonRequestError = class extends Error {
|
|
3399
|
+
constructor(message, requestWritten) {
|
|
3400
|
+
super(message);
|
|
3401
|
+
this.name = "DaemonRequestError";
|
|
3402
|
+
this.requestWritten = requestWritten;
|
|
3403
|
+
}
|
|
3404
|
+
};
|
|
3405
|
+
async function callToolViaDaemon(name, args, options = {}) {
|
|
3406
|
+
const paths = options.paths ?? daemonPaths();
|
|
3407
|
+
const ensure = options.ensure ?? ensureDaemonRunning;
|
|
3408
|
+
const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
3409
|
+
const requestArgs = withContext(args, options.context);
|
|
3410
|
+
let lastError;
|
|
3411
|
+
for (let attempt = 0; attempt < 2; attempt += 1) try {
|
|
3412
|
+
await ensure(paths);
|
|
3413
|
+
return await sendToolCall(paths.socket, name, requestArgs, timeoutMs);
|
|
3414
|
+
} catch (error) {
|
|
3415
|
+
lastError = error;
|
|
3416
|
+
if (error instanceof DaemonRequestError && error.requestWritten) break;
|
|
3417
|
+
}
|
|
3418
|
+
return daemonUnreachableResult(paths, lastError);
|
|
3419
|
+
}
|
|
3420
|
+
var FORWARDED_ENV_KEYS = [
|
|
3421
|
+
"LSP_TOOLS_MCP_PROJECT_CONFIG",
|
|
3422
|
+
"LSP_TOOLS_MCP_USER_CONFIG",
|
|
3423
|
+
"LSP_TOOLS_MCP_INSTALL_DECISIONS"
|
|
3424
|
+
];
|
|
3425
|
+
function currentRequestContext(env = process.env) {
|
|
3426
|
+
const forwarded = {};
|
|
3427
|
+
for (const key of FORWARDED_ENV_KEYS) {
|
|
3428
|
+
const value = env[key];
|
|
3429
|
+
if (value !== void 0) forwarded[key] = value;
|
|
3430
|
+
}
|
|
3431
|
+
return {
|
|
3432
|
+
cwd: process.cwd(),
|
|
3433
|
+
env: forwarded
|
|
3434
|
+
};
|
|
3435
|
+
}
|
|
3436
|
+
function withContext(args, context) {
|
|
3437
|
+
if (!context || context.cwd === void 0 && context.env === void 0) return args;
|
|
3438
|
+
return {
|
|
3439
|
+
...args,
|
|
3440
|
+
[CONTEXT_KEY]: context
|
|
3441
|
+
};
|
|
3442
|
+
}
|
|
3443
|
+
function daemonUnreachableResult(paths, error) {
|
|
3444
|
+
return {
|
|
3445
|
+
content: [{
|
|
3446
|
+
type: "text",
|
|
3447
|
+
text: [
|
|
3448
|
+
`LSP daemon unreachable: ${errorText(error)}.`,
|
|
3449
|
+
"The MCP server is a thin proxy and never runs language servers in-process.",
|
|
3450
|
+
`Socket: ${paths.socket}`,
|
|
3451
|
+
`Logs: ${paths.log}`,
|
|
3452
|
+
"The daemon is auto-started on demand and will be retried on the next request."
|
|
3453
|
+
].join("\n")
|
|
3454
|
+
}],
|
|
3455
|
+
isError: true
|
|
3456
|
+
};
|
|
3457
|
+
}
|
|
3458
|
+
function sendToolCall(socketPath, name, args, timeoutMs) {
|
|
3459
|
+
return new Promise((resolve, reject) => {
|
|
3460
|
+
const socket = connect(socketPath);
|
|
3461
|
+
let settled = false;
|
|
3462
|
+
let requestWritten = false;
|
|
3463
|
+
const finish = (run) => {
|
|
3464
|
+
if (settled) return;
|
|
3465
|
+
settled = true;
|
|
3466
|
+
clearTimeout(timer);
|
|
3467
|
+
socket.destroy();
|
|
3468
|
+
run();
|
|
3469
|
+
};
|
|
3470
|
+
const timer = setTimeout(() => finish(() => reject(new DaemonRequestError("daemon request timed out", requestWritten))), timeoutMs);
|
|
3471
|
+
timer.unref();
|
|
3472
|
+
const decoder = createLineDecoder((message) => {
|
|
3473
|
+
const result = toToolResult(message);
|
|
3474
|
+
if (result) finish(() => resolve(result));
|
|
3475
|
+
else finish(() => reject(new DaemonRequestError("invalid daemon response", requestWritten)));
|
|
3476
|
+
});
|
|
3477
|
+
socket.once("connect", () => {
|
|
3478
|
+
requestWritten = true;
|
|
3479
|
+
socket.write(encodeJsonLine({
|
|
3480
|
+
jsonrpc: "2.0",
|
|
3481
|
+
id: REQUEST_ID,
|
|
3482
|
+
method: "tools/call",
|
|
3483
|
+
params: {
|
|
3484
|
+
name,
|
|
3485
|
+
arguments: args
|
|
3486
|
+
}
|
|
3487
|
+
}));
|
|
3488
|
+
});
|
|
3489
|
+
socket.on("data", (chunk) => decoder.push(chunk));
|
|
3490
|
+
socket.once("error", (error) => finish(() => reject(new DaemonRequestError(error.message, requestWritten))));
|
|
3491
|
+
socket.once("close", () => finish(() => reject(new DaemonRequestError("daemon connection closed", requestWritten))));
|
|
3492
|
+
});
|
|
3493
|
+
}
|
|
3494
|
+
function toToolResult(message) {
|
|
3495
|
+
if (!isPlainRecord(message) || message["id"] !== REQUEST_ID) return null;
|
|
3496
|
+
const result = message["result"];
|
|
3497
|
+
if (!isPlainRecord(result) || !Array.isArray(result["content"])) return null;
|
|
3498
|
+
return {
|
|
3499
|
+
content: result["content"],
|
|
3500
|
+
isError: result["isError"] === true,
|
|
3501
|
+
details: result["details"]
|
|
3502
|
+
};
|
|
3503
|
+
}
|
|
3504
|
+
function errorText(error) {
|
|
3505
|
+
return error instanceof Error ? error.message : String(error);
|
|
3506
|
+
}
|
|
3507
|
+
//#endregion
|
|
3508
|
+
//#region packages/lsp-daemon/src/proxy.ts
|
|
3509
|
+
async function runMcpStdioProxy(options = {}) {
|
|
3510
|
+
await runJsonRpcStdioServer({
|
|
3511
|
+
input: options.input ?? process.stdin,
|
|
3512
|
+
output: options.output ?? process.stdout,
|
|
3513
|
+
idleTimeoutMs: 0,
|
|
3514
|
+
handler: handleProxyRequest,
|
|
3515
|
+
handlerOptions: {
|
|
3516
|
+
paths: options.paths ?? daemonPaths(),
|
|
3517
|
+
context: options.context ?? currentRequestContext(),
|
|
3518
|
+
...options.ensure ? { ensure: options.ensure } : {}
|
|
3519
|
+
},
|
|
3520
|
+
onHandlerError: (error) => {
|
|
3521
|
+
process.stderr.write(`[lsp-daemon] proxy error: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
3522
|
+
}
|
|
3523
|
+
});
|
|
3524
|
+
}
|
|
3525
|
+
async function handleProxyRequest(parsed, callOptions) {
|
|
3526
|
+
const toolCall = asToolCall(parsed);
|
|
3527
|
+
if (!toolCall) return handleLspMcpRequest(parsed);
|
|
3528
|
+
const result = await callToolViaDaemon(toolCall.name, toolCall.args, callOptions);
|
|
3529
|
+
return successResponse(toolCall.id, {
|
|
3530
|
+
content: result.content,
|
|
3531
|
+
isError: result.isError ?? false,
|
|
3532
|
+
details: result.details
|
|
3533
|
+
});
|
|
3534
|
+
}
|
|
3535
|
+
function asToolCall(parsed) {
|
|
3536
|
+
if (!isPlainRecord(parsed) || parsed["method"] !== "tools/call") return null;
|
|
3537
|
+
const params = parsed["params"];
|
|
3538
|
+
if (!isPlainRecord(params) || typeof params["name"] !== "string") return null;
|
|
3539
|
+
const args = params["arguments"];
|
|
3540
|
+
return {
|
|
3541
|
+
id: jsonRpcId(parsed["id"]),
|
|
3542
|
+
name: params["name"],
|
|
3543
|
+
args: isPlainRecord(args) ? args : {}
|
|
3544
|
+
};
|
|
3545
|
+
}
|
|
3546
|
+
//#endregion
|
|
3547
|
+
//#region packages/lsp-daemon/src/daemon-server.ts
|
|
3548
|
+
var DEFAULT_IDLE_SHUTDOWN_MS = 30 * 6e4;
|
|
3549
|
+
var DEFAULT_IDLE_CHECK_INTERVAL_MS = 6e4;
|
|
3550
|
+
async function startDaemonServer(paths, options = {}) {
|
|
3551
|
+
const idleShutdownMs = options.idleShutdownMs ?? DEFAULT_IDLE_SHUTDOWN_MS;
|
|
3552
|
+
const idleCheckIntervalMs = options.idleCheckIntervalMs ?? DEFAULT_IDLE_CHECK_INTERVAL_MS;
|
|
3553
|
+
mkdirSync(paths.dir, { recursive: true });
|
|
3554
|
+
unlinkQuietly(paths.socket);
|
|
3555
|
+
const connections = /* @__PURE__ */ new Set();
|
|
3556
|
+
let lastActiveAt = Date.now();
|
|
3557
|
+
const touch = () => {
|
|
3558
|
+
lastActiveAt = Date.now();
|
|
3559
|
+
};
|
|
3560
|
+
const server = createServer((socket) => {
|
|
3561
|
+
connections.add(socket);
|
|
3562
|
+
touch();
|
|
3563
|
+
const decoder = createLineDecoder((message) => {
|
|
3564
|
+
touch();
|
|
3565
|
+
respond(socket, message);
|
|
3566
|
+
});
|
|
3567
|
+
socket.on("data", (chunk) => decoder.push(chunk));
|
|
3568
|
+
socket.on("error", () => socket.destroy());
|
|
3569
|
+
socket.on("close", () => {
|
|
3570
|
+
connections.delete(socket);
|
|
3571
|
+
touch();
|
|
3572
|
+
});
|
|
3573
|
+
});
|
|
3574
|
+
server.on("error", (error) => logServerError(error));
|
|
3575
|
+
const endpointPath = join(paths.dir, "daemon.endpoint");
|
|
3576
|
+
await listen(server, paths.socket);
|
|
3577
|
+
writeFileSync(paths.pid, `${process.pid}\n`);
|
|
3578
|
+
writeFileSync(endpointPath, paths.socket);
|
|
3579
|
+
let closed = false;
|
|
3580
|
+
const close = async () => {
|
|
3581
|
+
if (closed) return;
|
|
3582
|
+
closed = true;
|
|
3583
|
+
clearInterval(idleTimer);
|
|
3584
|
+
for (const socket of connections) socket.destroy();
|
|
3585
|
+
connections.clear();
|
|
3586
|
+
await closeServer(server);
|
|
3587
|
+
unlinkQuietly(paths.socket);
|
|
3588
|
+
unlinkQuietly(paths.pid);
|
|
3589
|
+
unlinkQuietly(endpointPath);
|
|
3590
|
+
await disposeDefaultLspManager();
|
|
3591
|
+
};
|
|
3592
|
+
const idleTimer = setInterval(() => {
|
|
3593
|
+
if (connections.size > 0) return;
|
|
3594
|
+
if (getLspManager().clientCount() > 0) {
|
|
3595
|
+
touch();
|
|
3596
|
+
return;
|
|
3597
|
+
}
|
|
3598
|
+
if (Date.now() - lastActiveAt < idleShutdownMs) return;
|
|
3599
|
+
if (options.onIdleShutdown) {
|
|
3600
|
+
options.onIdleShutdown();
|
|
3601
|
+
return;
|
|
3602
|
+
}
|
|
3603
|
+
close().then(() => process.exit(0));
|
|
3604
|
+
}, idleCheckIntervalMs);
|
|
3605
|
+
idleTimer.unref();
|
|
3606
|
+
installSignalHandlers(close);
|
|
3607
|
+
return {
|
|
3608
|
+
server,
|
|
3609
|
+
close
|
|
3610
|
+
};
|
|
3611
|
+
}
|
|
3612
|
+
async function respond(socket, message) {
|
|
3613
|
+
try {
|
|
3614
|
+
const response = await handleDaemonMessage(message);
|
|
3615
|
+
if (response && socket.writable) socket.write(encodeJsonLine(response));
|
|
3616
|
+
} catch (error) {
|
|
3617
|
+
logServerError(error);
|
|
3618
|
+
}
|
|
3619
|
+
}
|
|
3620
|
+
function listen(server, socketPath) {
|
|
3621
|
+
return new Promise((resolve, reject) => {
|
|
3622
|
+
const onError = (error) => reject(error);
|
|
3623
|
+
server.once("error", onError);
|
|
3624
|
+
server.listen(socketPath, () => {
|
|
3625
|
+
server.removeListener("error", onError);
|
|
3626
|
+
resolve();
|
|
3627
|
+
});
|
|
3628
|
+
});
|
|
3629
|
+
}
|
|
3630
|
+
function closeServer(server) {
|
|
3631
|
+
return new Promise((resolve) => server.close(() => resolve()));
|
|
3632
|
+
}
|
|
3633
|
+
function installSignalHandlers(close) {
|
|
3634
|
+
const handler = () => {
|
|
3635
|
+
close().then(() => process.exit(0));
|
|
3636
|
+
};
|
|
3637
|
+
process.once("SIGTERM", handler);
|
|
3638
|
+
process.once("SIGINT", handler);
|
|
3639
|
+
}
|
|
3640
|
+
function logServerError(error) {
|
|
3641
|
+
const message = error instanceof Error ? error.stack ?? error.message : String(error);
|
|
3642
|
+
process.stderr.write(`[lsp-daemon] ${message}\n`);
|
|
3643
|
+
}
|
|
3644
|
+
//#endregion
|
|
3645
|
+
//#region packages/lsp-daemon/src/run-daemon.ts
|
|
3646
|
+
async function runDaemon() {
|
|
3647
|
+
process.on("uncaughtException", (error) => logNonFatal("uncaughtException", error));
|
|
3648
|
+
process.on("unhandledRejection", (reason) => logNonFatal("unhandledRejection", reason));
|
|
3649
|
+
await startDaemonServer(daemonPaths());
|
|
3650
|
+
}
|
|
3651
|
+
function logNonFatal(kind, error) {
|
|
3652
|
+
const message = error instanceof Error ? error.stack ?? error.message : String(error);
|
|
3653
|
+
process.stderr.write(`[lsp-daemon] ${kind}: ${message}\n`);
|
|
3654
|
+
}
|
|
3655
|
+
//#endregion
|
|
3656
|
+
//#region packages/lsp-daemon/src/cli.ts
|
|
3657
|
+
async function main() {
|
|
3658
|
+
const [command = "mcp"] = argv.slice(2);
|
|
3659
|
+
if (command === "daemon") {
|
|
3660
|
+
await runDaemon();
|
|
3661
|
+
return;
|
|
3662
|
+
}
|
|
3663
|
+
if (command === "mcp") {
|
|
3664
|
+
await runMcpStdioProxy();
|
|
3665
|
+
return;
|
|
3666
|
+
}
|
|
3667
|
+
stderr.write("Usage: holycodex-lsp-daemon [mcp | daemon]\n");
|
|
3668
|
+
process.exitCode = 2;
|
|
3669
|
+
}
|
|
3670
|
+
main().catch((error) => {
|
|
3671
|
+
stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
|
|
3672
|
+
process.exitCode = 1;
|
|
3673
|
+
});
|
|
3674
|
+
//#endregion
|