@tiens.nguyen/gu-cli 1.0.931 → 1.0.932
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/autocompact.mjs +136 -0
- package/browser-bridge.mjs +8 -0
- package/browser-extension/README.md +4 -0
- package/browser-extension/actions.js +366 -5
- package/browser-extension/background.js +104 -14
- package/browser-extension/manifest.json +1 -1
- package/browser-extension/popup.html +83 -15
- package/browser-extension/popup.js +145 -35
- package/clear-state.mjs +12 -1
- package/client-expert-api.mjs +105 -20
- package/client-expert-run.mjs +179 -120
- package/client-expert-setup.mjs +3 -2
- package/gonext_agent_chat.py +450 -14
- package/gu-cli.mjs +44 -6
- package/gu-repl.mjs +408 -24
- package/gu_browser.py +83 -9
- package/gu_gif.py +101 -0
- package/install-path.mjs +52 -20
- package/lsp-client.mjs +267 -0
- package/lsp-host.mjs +391 -0
- package/lsp-registry.mjs +568 -0
- package/model-doctor.mjs +5 -2
- package/next-suggestion.mjs +137 -0
- package/package.json +9 -1
- package/powershell-alias.mjs +12 -1
- package/setup-fixes.mjs +240 -0
- package/step-group.mjs +59 -18
- package/terminal-layout.mjs +82 -3
- package/win-shell.mjs +26 -0
package/lsp-host.mjs
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE LANGUAGE-SERVER HOST (GH #540) — lives in gu's worker daemon, which outlives every turn.
|
|
3
|
+
*
|
|
4
|
+
* WHY HERE AND NOT IN THE AGENT: the agent (gonext_agent_chat.py) is a new process for every turn,
|
|
5
|
+
* and a server that reads a big project takes seconds to minutes to get going. Held here, it starts
|
|
6
|
+
* once — the first time the agent edits a file of its language in that project — and stays warm
|
|
7
|
+
* for the next edits and the next turns, until it has been idle for IDLE_MS.
|
|
8
|
+
*
|
|
9
|
+
* The agent asks over 127.0.0.1 with a per-run token (lsp-host.json, never a fixed port):
|
|
10
|
+
* POST /check { file, text, changed:[from,to]|null, workspace, budgetMs }
|
|
11
|
+
* → { status: "ok", server, errors, warnings, rows } the file's problems now
|
|
12
|
+
* → { status: "offer", lang, name, server, needsInstall } ask the user (once per worker run)
|
|
13
|
+
* → { status: "installing" | "starting" | "off" | "missing" | "unsupported" | "timeout" | "error", … }
|
|
14
|
+
* GET /status → every language: its choice, whether its server is found, what is running.
|
|
15
|
+
*
|
|
16
|
+
* Nothing here ever blocks a turn for long: a server that is not ready within the budget gives
|
|
17
|
+
* "timeout", and the agent carries on as it did before language servers existed.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { createServer } from "node:http";
|
|
21
|
+
import { randomBytes } from "node:crypto";
|
|
22
|
+
import { spawn as nodeSpawn } from "node:child_process";
|
|
23
|
+
import { mkdirSync, readFileSync, writeFileSync, unlinkSync } from "node:fs";
|
|
24
|
+
import { dirname } from "node:path";
|
|
25
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
26
|
+
import { LspClient } from "./lsp-client.mjs";
|
|
27
|
+
import { shellCommand } from "./win-shell.mjs";
|
|
28
|
+
import {
|
|
29
|
+
allLanguages, canInstall, findProjectRoot, installCommand, languageFor, lspHostPath, lspInstallDir,
|
|
30
|
+
lspStatePath, mayOffer, pickDiagnostics, readLspState, resolveServer,
|
|
31
|
+
} from "./lsp-registry.mjs";
|
|
32
|
+
|
|
33
|
+
export const IDLE_MS = 10 * 60_000;
|
|
34
|
+
|
|
35
|
+
/** What an install is keyed by: HTML and CSS come from ONE npm package, installed once (GH #543). */
|
|
36
|
+
const installKey = (lang) => (lang.npm ? `npm:${lang.npm.join(" ")}` : lang.tool ? `tool:${lang.tool.what}` : lang.id);
|
|
37
|
+
|
|
38
|
+
const fileUriOf = (p) => pathToFileURL(p).href;
|
|
39
|
+
|
|
40
|
+
/** LSP SymbolKind numbers → words. */
|
|
41
|
+
const SYMBOL_KINDS = { 2: "module", 5: "class", 6: "method", 7: "property", 8: "field", 9: "constructor", 10: "enum",
|
|
42
|
+
11: "interface", 12: "function", 13: "variable", 14: "constant", 22: "enum member", 23: "struct", 26: "type parameter" };
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Where `symbol` sits on 1-based `line` → an LSP position (0-based). The first WHOLE-WORD match;
|
|
46
|
+
* no symbol (or not on that line) → the first non-blank character. null when the line does not exist.
|
|
47
|
+
*/
|
|
48
|
+
export function positionOf(text, line, symbol = "") {
|
|
49
|
+
const rows = String(text ?? "").split(/\r?\n/);
|
|
50
|
+
const i = Number(line) - 1;
|
|
51
|
+
if (!(i >= 0 && i < rows.length)) return null;
|
|
52
|
+
const row = rows[i];
|
|
53
|
+
const name = String(symbol ?? "").trim();
|
|
54
|
+
if (name) {
|
|
55
|
+
const esc = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
56
|
+
const m = new RegExp(`(^|[^\\w$])(${esc})(?![\\w$])`).exec(row);
|
|
57
|
+
if (m) return { line: i, character: m.index + m[1].length };
|
|
58
|
+
}
|
|
59
|
+
return { line: i, character: Math.max(0, row.search(/\S/)) };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Hover contents (string | MarkupContent | MarkedString[]) → plain text, code fences dropped. */
|
|
63
|
+
export function hoverText(contents) {
|
|
64
|
+
const one = (c) => (typeof c === "string" ? c : c?.value ?? "");
|
|
65
|
+
const raw = Array.isArray(contents) ? contents.map(one).join("\n") : one(contents);
|
|
66
|
+
return raw.replace(/```[\w-]*\n?/g, "").replace(/\n{3,}/g, "\n\n").trim().slice(0, 1500);
|
|
67
|
+
}
|
|
68
|
+
export const MAX_RESTARTS = 3;
|
|
69
|
+
export const START_TIMEOUT_MS = 60_000;
|
|
70
|
+
|
|
71
|
+
export class LspHost {
|
|
72
|
+
constructor({ home, log = () => {}, resolve = resolveServer, Client = LspClient, spawnImpl = nodeSpawn, idleMs = IDLE_MS, now = Date.now } = {}) {
|
|
73
|
+
Object.assign(this, { home, log, resolve, Client, spawnImpl, idleMs, now });
|
|
74
|
+
this.clients = new Map(); // `${lang}|${root}` → { client, starting, restarts, lang, root }
|
|
75
|
+
this.offered = new Set(); // languages offered during this worker run
|
|
76
|
+
this.installing = new Map(); // installKey → Promise
|
|
77
|
+
this.installErrors = new Map();
|
|
78
|
+
this.langCache = new Map(); // workspace → { at, langs } — lsp.json files re-read every few seconds
|
|
79
|
+
this.workspaces = new Set();
|
|
80
|
+
this.timer = setInterval(() => this.sweep(), 30_000);
|
|
81
|
+
this.timer.unref?.();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Built-ins plus the user's lsp.json servers for this workspace (GH #542). */
|
|
85
|
+
languages(workspace = "") {
|
|
86
|
+
const hit = this.langCache.get(workspace);
|
|
87
|
+
if (hit && this.now() - hit.at < 5000) return hit.langs;
|
|
88
|
+
const langs = allLanguages({ home: this.home, workspace });
|
|
89
|
+
this.langCache.set(workspace, { at: this.now(), langs });
|
|
90
|
+
if (workspace) this.workspaces.add(workspace);
|
|
91
|
+
return langs;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
state() {
|
|
95
|
+
try {
|
|
96
|
+
return readLspState(readFileSync(lspStatePath(this.home), "utf8"));
|
|
97
|
+
} catch {
|
|
98
|
+
return readLspState("");
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The server for a language in a project root — started (or restarted) as needed. */
|
|
103
|
+
async clientFor(lang, root, server) {
|
|
104
|
+
const key = `${lang.id}|${root}`;
|
|
105
|
+
let entry = this.clients.get(key);
|
|
106
|
+
if (entry?.client?.alive) return entry;
|
|
107
|
+
if (entry?.starting) return entry;
|
|
108
|
+
if (entry && entry.restarts >= MAX_RESTARTS) throw new Error(`${lang.server} stopped ${entry.restarts} times — not restarted again (/lsp restart)`);
|
|
109
|
+
const restarts = entry ? entry.restarts + 1 : 0;
|
|
110
|
+
// Some servers want per-project arguments (jdtls: its index folder) — GH #543.
|
|
111
|
+
const args = lang.argsFor ? [...(server.args ?? []), ...lang.argsFor(root, this.home)] : server.args;
|
|
112
|
+
const client = new this.Client({ ...server, args, root, log: this.log, spawnImpl: this.spawnImpl,
|
|
113
|
+
initializationOptions: lang.initializationOptionsFor?.(root, this.home) ?? lang.initializationOptions, settings: lang.settings });
|
|
114
|
+
entry = { client, lang, root, restarts, starting: null };
|
|
115
|
+
entry.starting = client
|
|
116
|
+
.start({ timeoutMs: lang.startupTimeout ?? START_TIMEOUT_MS })
|
|
117
|
+
.then(() => {
|
|
118
|
+
entry.starting = null;
|
|
119
|
+
this.log(`[lsp] ${lang.server} started for ${root}`);
|
|
120
|
+
})
|
|
121
|
+
.catch((e) => {
|
|
122
|
+
entry.starting = null;
|
|
123
|
+
entry.failed = String(e?.message || e);
|
|
124
|
+
this.log(`[lsp] ${lang.server} failed to start in ${root}: ${entry.failed}`);
|
|
125
|
+
try {
|
|
126
|
+
client.proc?.kill();
|
|
127
|
+
} catch {}
|
|
128
|
+
});
|
|
129
|
+
this.clients.set(key, entry);
|
|
130
|
+
return entry;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Install a server into ~/.gonext/lsp (npm), once at a time per language. */
|
|
134
|
+
install(lang) {
|
|
135
|
+
if (this.installing.has(installKey(lang))) return this.installing.get(installKey(lang));
|
|
136
|
+
const { cmd, args } = installCommand(lang, this.home);
|
|
137
|
+
if (!lang.tool) mkdirSync(lspInstallDir(this.home), { recursive: true });
|
|
138
|
+
this.log(`[lsp] installing ${lang.server}: ${[cmd, ...args].join(" ")}`);
|
|
139
|
+
const p = new Promise((resolve) => {
|
|
140
|
+
const sc = shellCommand(cmd, args); // one string on Windows: no DEP0190 (GH #557)
|
|
141
|
+
const child = this.spawnImpl(sc.cmd, sc.args, { stdio: ["ignore", "ignore", "pipe"], shell: sc.shell, windowsHide: true });
|
|
142
|
+
let err = "";
|
|
143
|
+
child.stderr?.on("data", (b) => (err = (err + b).slice(-800)));
|
|
144
|
+
child.on("error", (e) => resolve({ ok: false, why: String(e?.message || e) }));
|
|
145
|
+
child.on("exit", (code) => resolve(code === 0 ? { ok: true } : { ok: false, why: err.trim() || `npm exited ${code}` }));
|
|
146
|
+
}).then((r) => {
|
|
147
|
+
this.installing.delete(installKey(lang));
|
|
148
|
+
if (!r.ok) {
|
|
149
|
+
this.installErrors.set(installKey(lang), r.why);
|
|
150
|
+
this.log(`[lsp] install of ${lang.server} failed: ${r.why}`);
|
|
151
|
+
} else {
|
|
152
|
+
this.installErrors.delete(installKey(lang));
|
|
153
|
+
this.log(`[lsp] ${lang.server} installed`);
|
|
154
|
+
}
|
|
155
|
+
return r;
|
|
156
|
+
});
|
|
157
|
+
this.installing.set(installKey(lang), p);
|
|
158
|
+
return p;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The agent's question after an edit. Never throws. */
|
|
162
|
+
async check({ file, text, changed = null, workspace = "", budgetMs = 3000 } = {}) {
|
|
163
|
+
try {
|
|
164
|
+
const hit = languageFor(file, this.languages(workspace));
|
|
165
|
+
if (!hit) return { status: "unsupported" };
|
|
166
|
+
const { lang, languageId } = hit;
|
|
167
|
+
if (lang.diagnostics === false) return { status: "off", lang: lang.id };
|
|
168
|
+
const st = this.state();
|
|
169
|
+
const choice = st.languages[lang.id];
|
|
170
|
+
const server = this.resolve(lang, { home: this.home });
|
|
171
|
+
if (choice !== "on") {
|
|
172
|
+
if (choice === undefined && mayOffer(st, lang.id) && !this.offered.has(lang.id) && (server || canInstall(lang))) {
|
|
173
|
+
this.offered.add(lang.id);
|
|
174
|
+
return { status: "offer", lang: lang.id, name: lang.name, server: lang.server, needsInstall: !server, size: lang.size ?? "",
|
|
175
|
+
...(lang.custom ? { command: [lang.command, ...lang.args].join(" "), source: lang.source } : {}) };
|
|
176
|
+
}
|
|
177
|
+
return { status: "off", lang: lang.id };
|
|
178
|
+
}
|
|
179
|
+
if (!server) {
|
|
180
|
+
if (!canInstall(lang)) return { status: "missing", lang: lang.id, server: lang.server, hint: lang.hint ?? "" };
|
|
181
|
+
if (this.installErrors.has(installKey(lang)) && !this.installing.has(installKey(lang))) {
|
|
182
|
+
return { status: "error", lang: lang.id, server: lang.server, why: `install failed: ${this.installErrors.get(installKey(lang))}` };
|
|
183
|
+
}
|
|
184
|
+
void this.install(lang);
|
|
185
|
+
return { status: "installing", lang: lang.id, server: lang.server };
|
|
186
|
+
}
|
|
187
|
+
const root = findProjectRoot(file, lang, workspace);
|
|
188
|
+
const entry = await this.clientFor(lang, root, server);
|
|
189
|
+
const deadline = this.now() + budgetMs;
|
|
190
|
+
if (entry.starting) {
|
|
191
|
+
await Promise.race([entry.starting, new Promise((r) => setTimeout(r, Math.max(0, budgetMs)))]);
|
|
192
|
+
if (entry.starting) return { status: "starting", lang: lang.id, server: lang.server };
|
|
193
|
+
}
|
|
194
|
+
if (!entry.client.alive) return { status: "error", lang: lang.id, server: lang.server, why: entry.failed || entry.client.diedBecause || "not running" };
|
|
195
|
+
const synced = entry.client.sync(file, languageId, String(text ?? ""));
|
|
196
|
+
const left = Math.max(200, deadline - this.now());
|
|
197
|
+
const d = await entry.client.diagnostics(file, { timeoutMs: left, since: synced.at, version: synced.version });
|
|
198
|
+
if (!d.ok) return { status: "timeout", lang: lang.id, server: lang.server };
|
|
199
|
+
return { status: "ok", lang: lang.id, server: lang.server, root, ...pickDiagnostics(d.diagnostics, changed) };
|
|
200
|
+
} catch (e) {
|
|
201
|
+
return { status: "error", why: String(e?.message || e) };
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* The agent's `lsp` tool (GH #541): ask the server about a symbol. Read-only.
|
|
207
|
+
* op "definition" | "references" | "type": `file` + `line` (1-based) + `symbol` (a name on that
|
|
208
|
+
* line — models give names, not columns; the column is found here).
|
|
209
|
+
* op "symbol": `query`, searched in the project of `file` (any file of that language).
|
|
210
|
+
* → { status: "ok", op, server, results: [{ file, line, col, text }] } or { status: "ok", type }
|
|
211
|
+
* or { status: "off" | "missing" | "starting" | "timeout" | "error" | "unsupported", why? }.
|
|
212
|
+
*/
|
|
213
|
+
async query({ op, file, line = 0, symbol = "", query = "", workspace = "", budgetMs = 8000 } = {}) {
|
|
214
|
+
try {
|
|
215
|
+
const hit = languageFor(file, this.languages(workspace));
|
|
216
|
+
if (!hit) return { status: "unsupported" };
|
|
217
|
+
const { lang, languageId } = hit;
|
|
218
|
+
if (this.state().languages[lang.id] !== "on") return { status: "off", lang: lang.id, name: lang.name };
|
|
219
|
+
const server = this.resolve(lang, { home: this.home });
|
|
220
|
+
if (!server) return { status: "missing", lang: lang.id, server: lang.server };
|
|
221
|
+
let text;
|
|
222
|
+
try {
|
|
223
|
+
text = readFileSync(file, "utf8");
|
|
224
|
+
} catch {
|
|
225
|
+
return { status: "error", why: `cannot read ${file}` };
|
|
226
|
+
}
|
|
227
|
+
const root = findProjectRoot(file, lang, workspace);
|
|
228
|
+
const entry = await this.clientFor(lang, root, server);
|
|
229
|
+
if (entry.starting) {
|
|
230
|
+
await Promise.race([entry.starting, new Promise((r) => setTimeout(r, budgetMs))]);
|
|
231
|
+
if (entry.starting) return { status: "starting", lang: lang.id, server: lang.server };
|
|
232
|
+
}
|
|
233
|
+
if (!entry.client.alive) return { status: "error", why: entry.failed || entry.client.diedBecause || "not running" };
|
|
234
|
+
const c = entry.client;
|
|
235
|
+
c.sync(file, languageId, text);
|
|
236
|
+
const uri = fileUriOf(file);
|
|
237
|
+
if (op === "symbol") {
|
|
238
|
+
const r = await c.request("workspace/symbol", { query: String(query || symbol) }, budgetMs);
|
|
239
|
+
const results = (Array.isArray(r) ? r : []).slice(0, 30).map((s) => ({
|
|
240
|
+
name: s.name, kind: SYMBOL_KINDS[s.kind] ?? "", ...this.place(s.location ?? { uri: s.uri }),
|
|
241
|
+
}));
|
|
242
|
+
return { status: "ok", op, server: lang.server, results };
|
|
243
|
+
}
|
|
244
|
+
const pos = positionOf(text, line, symbol);
|
|
245
|
+
if (!pos) return { status: "error", why: `line ${line} of ${file} does not exist` };
|
|
246
|
+
const params = { textDocument: { uri }, position: pos };
|
|
247
|
+
if (op === "type") {
|
|
248
|
+
const r = await c.request("textDocument/hover", params, budgetMs);
|
|
249
|
+
return { status: "ok", op, server: lang.server, type: hoverText(r?.contents) };
|
|
250
|
+
}
|
|
251
|
+
const method = op === "references" ? "textDocument/references" : "textDocument/definition";
|
|
252
|
+
const r = await c.request(method, op === "references" ? { ...params, context: { includeDeclaration: true } } : params, budgetMs);
|
|
253
|
+
const locs = (Array.isArray(r) ? r : r ? [r] : []).slice(0, 50);
|
|
254
|
+
return { status: "ok", op, server: lang.server, results: locs.map((l) => this.place(l)).filter((x) => x.file) };
|
|
255
|
+
} catch (e) {
|
|
256
|
+
return { status: /timed out/.test(String(e?.message)) ? "timeout" : "error", why: String(e?.message || e) };
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** A Location or LocationLink → { file, line, col, text } with the line's own text. */
|
|
261
|
+
place(loc) {
|
|
262
|
+
const uri = loc?.targetUri ?? loc?.uri ?? "";
|
|
263
|
+
const range = loc?.targetSelectionRange ?? loc?.range ?? loc?.targetRange;
|
|
264
|
+
let file = "";
|
|
265
|
+
try {
|
|
266
|
+
file = uri.startsWith("file:") ? fileURLToPath(uri) : "";
|
|
267
|
+
} catch {}
|
|
268
|
+
const line = (range?.start?.line ?? 0) + 1;
|
|
269
|
+
let text = "";
|
|
270
|
+
if (file) {
|
|
271
|
+
try {
|
|
272
|
+
text = (readFileSync(file, "utf8").split(/\r?\n/)[line - 1] ?? "").trim().slice(0, 200);
|
|
273
|
+
} catch {}
|
|
274
|
+
}
|
|
275
|
+
return { file, line, col: (range?.start?.character ?? 0) + 1, text };
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** What /lsp shows. */
|
|
279
|
+
status(workspace = "") {
|
|
280
|
+
const st = this.state();
|
|
281
|
+
const langs = new Map();
|
|
282
|
+
for (const ws of [workspace, ...this.workspaces]) for (const l of this.languages(ws)) if (!langs.has(l.id)) langs.set(l.id, l);
|
|
283
|
+
return [...langs.values()].map((lang) => {
|
|
284
|
+
const running = [...this.clients.values()].filter((e) => e.lang.id === lang.id && e.client.alive && !e.starting).map((e) => e.root);
|
|
285
|
+
const starting = [...this.clients.values()].filter((e) => e.lang.id === lang.id && e.starting).map((e) => e.root);
|
|
286
|
+
return {
|
|
287
|
+
id: lang.id,
|
|
288
|
+
name: lang.name,
|
|
289
|
+
server: lang.server,
|
|
290
|
+
choice: st.languages[lang.id] ?? "",
|
|
291
|
+
found: Boolean(this.resolve(lang, { home: this.home })),
|
|
292
|
+
canInstall: canInstall(lang),
|
|
293
|
+
hint: lang.hint ?? "",
|
|
294
|
+
custom: Boolean(lang.custom),
|
|
295
|
+
...(lang.custom ? { command: [lang.command, ...lang.args].join(" "), source: lang.source } : {}),
|
|
296
|
+
installing: this.installing.has(installKey(lang)),
|
|
297
|
+
installError: this.installErrors.get(installKey(lang)) ?? "",
|
|
298
|
+
running,
|
|
299
|
+
starting,
|
|
300
|
+
};
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Stop every server of a language (or all) — /lsp off, /lsp restart, idle. */
|
|
305
|
+
async stop(id = "") {
|
|
306
|
+
for (const [key, e] of this.clients) {
|
|
307
|
+
if (id && e.lang.id !== id) continue;
|
|
308
|
+
this.clients.delete(key);
|
|
309
|
+
await e.client.shutdown().catch(() => {});
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Servers idle for IDLE_MS are stopped: their memory is the real cost of this feature. */
|
|
314
|
+
sweep() {
|
|
315
|
+
const t = this.now();
|
|
316
|
+
for (const [key, e] of this.clients) {
|
|
317
|
+
if (e.client.alive && !e.starting && t - e.client.lastUsed >= this.idleMs) {
|
|
318
|
+
this.log(`[lsp] ${e.lang.server} idle for ${Math.round(this.idleMs / 60000)} min in ${e.root} — stopped`);
|
|
319
|
+
this.clients.delete(key);
|
|
320
|
+
void e.client.shutdown();
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
async close() {
|
|
326
|
+
clearInterval(this.timer);
|
|
327
|
+
await this.stop();
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Serve a host on 127.0.0.1 (a free port) and write where to reach it to ~/.gonext/lsp-host.json.
|
|
333
|
+
* → { url, token, host, close }.
|
|
334
|
+
*/
|
|
335
|
+
export async function serveLspHost({ home, log = () => {}, host = new LspHost({ home, log }) } = {}) {
|
|
336
|
+
const token = randomBytes(18).toString("hex");
|
|
337
|
+
const server = createServer((req, res) => {
|
|
338
|
+
const reply = (code, body) => {
|
|
339
|
+
res.writeHead(code, { "Content-Type": "application/json" });
|
|
340
|
+
res.end(JSON.stringify(body));
|
|
341
|
+
};
|
|
342
|
+
if (req.headers["x-gu-lsp-token"] !== token) return reply(403, { error: "forbidden" });
|
|
343
|
+
let body = "";
|
|
344
|
+
req.on("data", (c) => {
|
|
345
|
+
body += c;
|
|
346
|
+
if (body.length > 8_000_000) req.destroy();
|
|
347
|
+
});
|
|
348
|
+
req.on("end", async () => {
|
|
349
|
+
try {
|
|
350
|
+
if (req.method === "GET" && req.url.startsWith("/status")) {
|
|
351
|
+
const ws = new URL(req.url, "http://x").searchParams.get("workspace") ?? "";
|
|
352
|
+
return reply(200, { languages: host.status(ws) });
|
|
353
|
+
}
|
|
354
|
+
const input = body ? JSON.parse(body) : {};
|
|
355
|
+
if (req.method === "POST" && req.url === "/check") return reply(200, await host.check(input));
|
|
356
|
+
if (req.method === "POST" && req.url === "/query") return reply(200, await host.query(input));
|
|
357
|
+
if (req.method === "POST" && req.url === "/stop") {
|
|
358
|
+
await host.stop(String(input.lang ?? ""));
|
|
359
|
+
return reply(200, { ok: true });
|
|
360
|
+
}
|
|
361
|
+
return reply(404, { error: "not found" });
|
|
362
|
+
} catch (e) {
|
|
363
|
+
return reply(500, { error: String(e?.message || e) });
|
|
364
|
+
}
|
|
365
|
+
});
|
|
366
|
+
});
|
|
367
|
+
await new Promise((resolve, reject) => {
|
|
368
|
+
server.once("error", reject);
|
|
369
|
+
server.listen(0, "127.0.0.1", resolve);
|
|
370
|
+
});
|
|
371
|
+
server.unref?.();
|
|
372
|
+
const url = `http://127.0.0.1:${server.address().port}`;
|
|
373
|
+
const file = lspHostPath(home);
|
|
374
|
+
try {
|
|
375
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
376
|
+
writeFileSync(file, JSON.stringify({ url, token, pid: process.pid }) + "\n", { mode: 0o600 });
|
|
377
|
+
} catch {}
|
|
378
|
+
return {
|
|
379
|
+
url,
|
|
380
|
+
token,
|
|
381
|
+
host,
|
|
382
|
+
async close() {
|
|
383
|
+
server.close();
|
|
384
|
+
await host.close();
|
|
385
|
+
try {
|
|
386
|
+
const cur = JSON.parse(readFileSync(file, "utf8"));
|
|
387
|
+
if (cur.pid === process.pid) unlinkSync(file);
|
|
388
|
+
} catch {}
|
|
389
|
+
},
|
|
390
|
+
};
|
|
391
|
+
}
|