@tiens.nguyen/gu-cli 1.0.930 → 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.
@@ -0,0 +1,568 @@
1
+ /**
2
+ * LANGUAGE SERVERS gu KNOWS (GH #539, phase 1 #540) — which server speaks which language, how to
3
+ * find it on this computer, how to install it, and what the user chose. Pure apart from the small
4
+ * `find*` helpers that look at the filesystem.
5
+ *
6
+ * LSP = Language Server Protocol: the standard way a code tool asks a LANGUAGE SERVER (a program
7
+ * that understands one language) "any errors in this file?" or "where is Greeter defined?". gu
8
+ * builds only the client side; each server comes from its language's own project (all open source,
9
+ * see the table's `licence`). Claude Code's plugins are the same idea — a few lines saying which
10
+ * program serves which file types — without the install: gu offers to install it, with consent.
11
+ *
12
+ * The user's choices are ~/.gonext/lsp-state.json, written by the terminal (the offer, /lsp) and
13
+ * read by the worker's host (lsp-host.mjs):
14
+ * { "languages": { "<id>": "on" | "off" | "never" }, "neverAsk": false, "ignored": 0 }
15
+ */
16
+
17
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
18
+ import { delimiter, dirname, extname, isAbsolute, join, parse as parsePath, resolve } from "node:path";
19
+ import { execFileSync } from "node:child_process";
20
+ import { createHash } from "node:crypto";
21
+
22
+ /** Every "<base>/<something>/bin" — gem and similar tools put one folder per version. */
23
+ function binsUnder(base) {
24
+ if (!base) return [];
25
+ try {
26
+ return readdirSync(base).map((v) => join(base, v, "bin"));
27
+ } catch {
28
+ return [];
29
+ }
30
+ }
31
+
32
+ const CORE_LANGUAGES = [
33
+ {
34
+ id: "typescript",
35
+ name: "TypeScript/JavaScript",
36
+ server: "typescript-language-server",
37
+ licence: "Apache-2.0",
38
+ exts: { ".ts": "typescript", ".tsx": "typescriptreact", ".mts": "typescript", ".cts": "typescript",
39
+ ".js": "javascript", ".jsx": "javascriptreact", ".mjs": "javascript", ".cjs": "javascript" },
40
+ bin: "typescript-language-server",
41
+ args: ["--stdio"],
42
+ // Below 7: TypeScript 7 is the native (Go) compiler and ships no tsserver.js, which
43
+ // typescript-language-server 6 runs — npm's "latest" became 7, and every new install failed
44
+ // with "Could not find a valid TypeScript installation" (GH #552, seen live).
45
+ // Written "@6", not "@<7" (GH #557, seen live on Windows 11): there npm runs through cmd.exe,
46
+ // which read "<7" as "input from a file named 7" — "The system cannot find the file specified".
47
+ // npm's "6" is the range >=6.0.0 <7.0.0, with no character any shell treats specially.
48
+ npm: ["typescript-language-server", "typescript@6"],
49
+ // An install is usable only with this file; an older install that got TypeScript 7 counts as
50
+ // missing, so gu offers the install again and npm puts the right version in.
51
+ needs: [join("node_modules", "typescript", "lib", "tsserver.js")],
52
+ size: "~5 MB",
53
+ roots: ["tsconfig.json", "jsconfig.json", "package.json"],
54
+ // GH #552: the server looks for TypeScript in the PROJECT's node_modules and gives up without
55
+ // it ("Could not find a valid TypeScript installation") — a fresh clone, or a project that
56
+ // never ran npm install, got no checks at all. gu installs typescript next to the server, so
57
+ // that copy is the fallback; a project's own TypeScript still wins.
58
+ initializationOptionsFor: (root, home) => {
59
+ const lib = join(lspInstallDir(home), "node_modules", "typescript", "lib");
60
+ return existsSync(join(lib, "tsserver.js")) ? { tsserver: { fallbackPath: lib } } : undefined;
61
+ },
62
+ },
63
+ {
64
+ id: "python",
65
+ name: "Python",
66
+ server: "pyright",
67
+ licence: "MIT",
68
+ exts: { ".py": "python", ".pyi": "python" },
69
+ bin: "pyright-langserver",
70
+ args: ["--stdio"],
71
+ npm: ["pyright"],
72
+ size: "~19 MB",
73
+ roots: ["pyproject.toml", "pyrightconfig.json", "setup.py", "setup.cfg", "requirements.txt"],
74
+ },
75
+ {
76
+ id: "swift",
77
+ name: "Swift",
78
+ server: "sourcekit-lsp",
79
+ licence: "Apache-2.0",
80
+ exts: { ".swift": "swift" },
81
+ bin: "sourcekit-lsp",
82
+ args: [],
83
+ xcrun: true, // comes with Xcode (macOS) or the Swift toolchain (Linux): nothing to download
84
+ hint: "comes with Xcode on macOS, and with the Swift toolchain on Linux (swift.org/install)",
85
+ roots: ["Package.swift", "*.xcodeproj", "*.xcworkspace"],
86
+ },
87
+ // GH #542 (phase 3). Go and Rust are installed with the language's OWN tool — `go install`,
88
+ // `rustup` — so gu offers them only where that tool is already here.
89
+ {
90
+ id: "go",
91
+ name: "Go",
92
+ server: "gopls",
93
+ licence: "BSD-3-Clause",
94
+ exts: { ".go": "go" },
95
+ bin: "gopls",
96
+ args: [],
97
+ tool: { cmd: "go", args: ["install", "golang.org/x/tools/gopls@latest"], what: "go install golang.org/x/tools/gopls@latest" },
98
+ extraDirs: (home, env) => [env.GOBIN, env.GOPATH && join(env.GOPATH, "bin"), home && join(home, "go", "bin")],
99
+ size: "~30 MB",
100
+ hint: "install Go (go.dev/dl), then: go install golang.org/x/tools/gopls@latest",
101
+ roots: ["go.work", "go.mod"],
102
+ },
103
+ {
104
+ id: "rust",
105
+ name: "Rust",
106
+ server: "rust-analyzer",
107
+ licence: "MIT OR Apache-2.0",
108
+ exts: { ".rs": "rust" },
109
+ bin: "rust-analyzer",
110
+ args: [],
111
+ tool: { cmd: "rustup", args: ["component", "add", "rust-analyzer"], what: "rustup component add rust-analyzer" },
112
+ extraDirs: (home, env) => [env.CARGO_HOME && join(env.CARGO_HOME, "bin"), home && join(home, ".cargo", "bin")],
113
+ size: "~40 MB",
114
+ hint: "install Rust with rustup (rustup.rs), then: rustup component add rust-analyzer",
115
+ roots: ["Cargo.toml", "rust-project.json"],
116
+ },
117
+ {
118
+ id: "cpp",
119
+ name: "C/C++",
120
+ server: "clangd",
121
+ licence: "Apache-2.0 WITH LLVM-exception",
122
+ exts: { ".c": "c", ".h": "c", ".cc": "cpp", ".cpp": "cpp", ".cxx": "cpp", ".hpp": "cpp", ".hh": "cpp", ".hxx": "cpp", ".m": "objective-c", ".mm": "objective-cpp" },
123
+ bin: "clangd",
124
+ args: ["--background-index=false"],
125
+ xcrun: true, // part of Xcode on macOS; elsewhere it needs the system's package manager (admin rights)
126
+ hint: "comes with Xcode on macOS; on Linux: sudo apt install clangd (or your distribution's package); on Windows: the LLVM installer (github.com/llvm/llvm-project/releases)",
127
+ roots: ["compile_commands.json", "compile_flags.txt", ".clangd", "CMakeLists.txt", "Makefile"],
128
+ },
129
+ ];
130
+
131
+ // GH #543 (phase 4). Heavier servers, most of them installed with the language's own tool or with
132
+ // Homebrew; each is offered for install only where that tool is already here, else /lsp says how.
133
+ const BREW = (formula) => ({ cmd: "brew", args: ["install", formula], what: `brew install ${formula}` });
134
+ export const PHASE4_LANGUAGES = Object.freeze([
135
+ {
136
+ id: "java",
137
+ name: "Java",
138
+ server: "jdtls",
139
+ licence: "EPL-2.0",
140
+ exts: { ".java": "java" },
141
+ bin: "jdtls",
142
+ args: [],
143
+ // jdtls keeps an index per project in a -data folder; one per root, under gu's own folder.
144
+ argsFor: (root, home) => ["-data", join(lspInstallDir(home), "jdtls-data", createHash("sha256").update(root).digest("hex").slice(0, 16))],
145
+ tool: BREW("jdtls"),
146
+ size: "~50 MB, needs Java 21+",
147
+ startupTimeout: 180_000, // a Gradle/Maven import can take minutes the first time
148
+ hint: "needs Java 21+; macOS: brew install jdtls; elsewhere: download from download.eclipse.org/jdtls/milestones",
149
+ roots: ["pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts", ".project"],
150
+ },
151
+ {
152
+ id: "kotlin",
153
+ name: "Kotlin",
154
+ server: "kotlin-lsp",
155
+ licence: "Apache-2.0",
156
+ exts: { ".kt": "kotlin", ".kts": "kotlin" },
157
+ bin: "kotlin-lsp",
158
+ args: ["--stdio"],
159
+ tool: BREW("JetBrains/utils/kotlin-lsp"),
160
+ size: "~200 MB",
161
+ startupTimeout: 180_000,
162
+ hint: "macOS: brew install JetBrains/utils/kotlin-lsp; elsewhere: github.com/Kotlin/kotlin-lsp/releases",
163
+ roots: ["settings.gradle.kts", "settings.gradle", "build.gradle.kts", "build.gradle", "pom.xml"],
164
+ },
165
+ {
166
+ id: "csharp",
167
+ name: "C#",
168
+ server: "csharp-ls",
169
+ licence: "MIT",
170
+ exts: { ".cs": "csharp" },
171
+ bin: "csharp-ls",
172
+ args: [],
173
+ tool: { cmd: "dotnet", args: ["tool", "install", "--global", "csharp-ls"], what: "dotnet tool install --global csharp-ls" },
174
+ extraDirs: (home) => [home && join(home, ".dotnet", "tools")],
175
+ size: "~30 MB",
176
+ startupTimeout: 120_000,
177
+ hint: "install the .NET SDK (dot.net), then: dotnet tool install --global csharp-ls",
178
+ roots: ["*.sln", "*.csproj"],
179
+ },
180
+ {
181
+ // NOT intelephense, the one Claude Code lists: its licence is a personal one for an individual's
182
+ // own editor and forbids copying or distributing it beyond that, so gu does not install it.
183
+ // phpactor is MIT. Someone who has intelephense can add it in lsp.json.
184
+ id: "php",
185
+ name: "PHP",
186
+ server: "phpactor",
187
+ licence: "MIT",
188
+ exts: { ".php": "php" },
189
+ bin: "phpactor",
190
+ args: ["language-server"],
191
+ tool: { cmd: "composer", args: ["global", "require", "phpactor/phpactor"], what: "composer global require phpactor/phpactor" },
192
+ extraDirs: (home, env) => [env.COMPOSER_HOME && join(env.COMPOSER_HOME, "vendor", "bin"), home && join(home, ".composer", "vendor", "bin"), home && join(home, ".config", "composer", "vendor", "bin")],
193
+ size: "~20 MB, needs PHP 8.1+",
194
+ hint: "needs PHP 8.1+ and Composer (getcomposer.org), then: composer global require phpactor/phpactor",
195
+ roots: ["composer.json"],
196
+ },
197
+ {
198
+ id: "ruby",
199
+ name: "Ruby",
200
+ server: "ruby-lsp",
201
+ licence: "MIT",
202
+ exts: { ".rb": "ruby", ".rake": "ruby", ".gemspec": "ruby", ".ru": "ruby" },
203
+ bin: "ruby-lsp",
204
+ args: [],
205
+ tool: { cmd: "gem", args: ["install", "--user-install", "ruby-lsp"], what: "gem install --user-install ruby-lsp" },
206
+ extraDirs: (home) => [...binsUnder(home && join(home, ".gem", "ruby")), ...binsUnder(home && join(home, ".local", "share", "gem", "ruby"))],
207
+ size: "~5 MB, needs Ruby 3.0+",
208
+ hint: "needs Ruby 3.0+, then: gem install --user-install ruby-lsp",
209
+ roots: ["Gemfile", ".ruby-version"],
210
+ },
211
+ {
212
+ id: "lua",
213
+ name: "Lua",
214
+ server: "lua-language-server",
215
+ licence: "MIT",
216
+ exts: { ".lua": "lua" },
217
+ bin: "lua-language-server",
218
+ args: [],
219
+ tool: BREW("lua-language-server"),
220
+ size: "~15 MB",
221
+ hint: "macOS: brew install lua-language-server; elsewhere: github.com/LuaLS/lua-language-server/releases",
222
+ roots: [".luarc.json", ".luarc.jsonc", ".stylua.toml"],
223
+ },
224
+ {
225
+ id: "html",
226
+ name: "HTML",
227
+ server: "vscode-html-language-server",
228
+ licence: "MIT",
229
+ exts: { ".html": "html", ".htm": "html" },
230
+ bin: "vscode-html-language-server",
231
+ args: ["--stdio"],
232
+ npm: ["vscode-langservers-extracted"],
233
+ size: "~10 MB",
234
+ roots: ["package.json"],
235
+ },
236
+ {
237
+ id: "css",
238
+ name: "CSS",
239
+ server: "vscode-css-language-server",
240
+ licence: "MIT",
241
+ exts: { ".css": "css", ".scss": "scss", ".less": "less" },
242
+ bin: "vscode-css-language-server",
243
+ args: ["--stdio"],
244
+ npm: ["vscode-langservers-extracted"],
245
+ size: "~10 MB",
246
+ roots: ["package.json"],
247
+ },
248
+ ]);
249
+
250
+ export const BUILTIN_LANGUAGES = Object.freeze([...CORE_LANGUAGES, ...PHASE4_LANGUAGES]);
251
+ /** Kept for callers that only need the built-in table. */
252
+ export const LSP_LANGUAGES = BUILTIN_LANGUAGES;
253
+
254
+ // ---------------------------------------------------------------------------------------------
255
+ // the user's own servers (GH #542): lsp.json files, gu's or Claude Code's format
256
+ // ---------------------------------------------------------------------------------------------
257
+
258
+ /**
259
+ * Where custom servers are read from, the first that defines an id winning:
260
+ * <workspace>/.gu/lsp.json this project, gu's file
261
+ * <workspace>/.lsp.json this project, Claude Code's plugin file (a team that set it up for
262
+ * Claude Code gets the same servers in gu)
263
+ * ~/.gonext/lsp.json every project on this computer
264
+ * Each holds either Claude Code's shape — { "<id>": { command, args, extensionToLanguage, env,
265
+ * initializationOptions, settings, startupTimeout, … } } — or the same map under "lspServers".
266
+ */
267
+ export const customLspFiles = (home, workspace) =>
268
+ [workspace && join(workspace, ".gu", "lsp.json"), workspace && join(workspace, ".lsp.json"), home && join(home, ".gonext", "lsp.json")].filter(Boolean);
269
+
270
+ const ID_RE = /^[A-Za-z0-9][\w.-]{0,40}$/;
271
+
272
+ /** One lsp.json's text → custom language entries (bad entries are skipped, never fatal). */
273
+ export function parseLspJson(text, { source = "", workspace = "" } = {}) {
274
+ let raw;
275
+ try {
276
+ raw = JSON.parse(String(text ?? ""));
277
+ } catch {
278
+ return [];
279
+ }
280
+ const map = raw && typeof raw === "object" && raw.lspServers && typeof raw.lspServers === "object" ? raw.lspServers : raw;
281
+ if (!map || typeof map !== "object" || Array.isArray(map)) return [];
282
+ const out = [];
283
+ for (const [id, c] of Object.entries(map)) {
284
+ if (!ID_RE.test(id) || !c || typeof c !== "object") continue;
285
+ const command = typeof c.command === "string" ? c.command.trim() : "";
286
+ const e2l = c.extensionToLanguage && typeof c.extensionToLanguage === "object" ? c.extensionToLanguage : null;
287
+ if (!command || !e2l) continue;
288
+ const exts = {};
289
+ for (const [ext, languageId] of Object.entries(e2l)) {
290
+ const e = String(ext).trim().toLowerCase();
291
+ if (/^\.[\w.+-]+$/.test(e) && typeof languageId === "string" && languageId) exts[e] = languageId;
292
+ }
293
+ if (!Object.keys(exts).length) continue;
294
+ // Claude Code's ${CLAUDE_PROJECT_DIR} means the project; its plugin-root variables have no
295
+ // meaning outside a plugin, so an entry that needs them is skipped rather than run wrong.
296
+ const sub = (v) => String(v).replaceAll("${CLAUDE_PROJECT_DIR}", workspace || "");
297
+ if (/\$\{CLAUDE_PLUGIN_(ROOT|DATA)\}/.test(JSON.stringify(c))) continue;
298
+ out.push({
299
+ id,
300
+ name: typeof c.name === "string" && c.name ? c.name : id,
301
+ server: command.split(/[\\/]/).pop(),
302
+ custom: true,
303
+ source,
304
+ command: sub(command),
305
+ args: Array.isArray(c.args) ? c.args.map((a) => sub(a)) : [],
306
+ env: c.env && typeof c.env === "object" ? Object.fromEntries(Object.entries(c.env).map(([k, v]) => [k, sub(v)])) : {},
307
+ initializationOptions: c.initializationOptions ?? undefined,
308
+ settings: c.settings ?? undefined,
309
+ startupTimeout: Number.isInteger(c.startupTimeout) && c.startupTimeout > 0 ? c.startupTimeout : undefined,
310
+ diagnostics: c.diagnostics !== false,
311
+ exts,
312
+ bin: command,
313
+ roots: [],
314
+ });
315
+ }
316
+ return out;
317
+ }
318
+
319
+ /** The user's servers for a workspace (project files first, then the computer's). */
320
+ export function customLanguages({ home = "", workspace = "", read = (f) => readFileSync(f, "utf8") } = {}) {
321
+ const seen = new Set();
322
+ const out = [];
323
+ for (const f of customLspFiles(home, workspace)) {
324
+ let text;
325
+ try {
326
+ text = read(f);
327
+ } catch {
328
+ continue;
329
+ }
330
+ for (const l of parseLspJson(text, { source: f, workspace })) {
331
+ if (seen.has(l.id)) continue;
332
+ seen.add(l.id);
333
+ out.push(l);
334
+ }
335
+ }
336
+ return out;
337
+ }
338
+
339
+ /** Everything gu knows for a workspace: the user's servers first (they win an extension), then the built-ins. */
340
+ export function allLanguages(opts = {}) {
341
+ const mine = customLanguages(opts);
342
+ return [...mine, ...BUILTIN_LANGUAGES.filter((b) => !mine.some((c) => c.id === b.id))];
343
+ }
344
+
345
+ export const lspById = (id, langs = BUILTIN_LANGUAGES) => langs.find((l) => l.id === id) ?? null;
346
+
347
+ /** The language of a file → { lang, languageId } or null. */
348
+ export function languageFor(file, langs = BUILTIN_LANGUAGES) {
349
+ const ext = extname(String(file ?? "")).toLowerCase();
350
+ for (const lang of langs) if (ext in lang.exts) return { lang, languageId: lang.exts[ext] };
351
+ return null;
352
+ }
353
+
354
+ /** Every extension a server is known for — the agent skips the call for any other file. */
355
+ export const lspExtensions = (langs = BUILTIN_LANGUAGES) => [...new Set(langs.flatMap((l) => Object.keys(l.exts)))];
356
+
357
+ /** Where gu installs npm servers: its own folder, no admin rights, nothing global. */
358
+ export const lspInstallDir = (home) => join(home, ".gonext", "lsp");
359
+ export const lspStatePath = (home) => join(home, ".gonext", "lsp-state.json");
360
+ export const lspHostPath = (home) => join(home, ".gonext", "lsp-host.json");
361
+
362
+ // ---------------------------------------------------------------------------------------------
363
+ // the user's choices
364
+ // ---------------------------------------------------------------------------------------------
365
+
366
+ const CHOICES = new Set(["on", "off", "never"]);
367
+ /** After this many unanswered offers gu stops offering (Claude Code's rule). */
368
+ export const LSP_MAX_IGNORED = 5;
369
+ /** How long the offer waits; no answer = ignored. */
370
+ export const LSP_OFFER_MS = 30_000;
371
+
372
+ export function readLspState(text) {
373
+ let raw;
374
+ try {
375
+ raw = JSON.parse(String(text ?? ""));
376
+ } catch {
377
+ raw = null;
378
+ }
379
+ const languages = {};
380
+ if (raw && typeof raw === "object" && raw.languages && typeof raw.languages === "object") {
381
+ for (const [k, v] of Object.entries(raw.languages)) if (ID_RE.test(k) && CHOICES.has(v)) languages[k] = v;
382
+ }
383
+ return {
384
+ languages,
385
+ neverAsk: raw?.neverAsk === true,
386
+ ignored: Number.isInteger(raw?.ignored) && raw.ignored > 0 ? raw.ignored : 0,
387
+ };
388
+ }
389
+
390
+ export const writeLspState = (state) =>
391
+ JSON.stringify({ languages: state.languages ?? {}, neverAsk: state.neverAsk === true, ignored: state.ignored | 0 }, null, 2) + "\n";
392
+
393
+ /** May gu offer this language now? (It is offered at most once per worker run — the host tracks that.) */
394
+ export function mayOffer(state, id) {
395
+ if (!ID_RE.test(String(id ?? "")) || state.neverAsk || state.ignored >= LSP_MAX_IGNORED) return false;
396
+ return !(id in state.languages);
397
+ }
398
+
399
+ /** The offer's answer → the new state. `choice`: "yes" | "not-now" | "never" | "never-ask" | "ignored". */
400
+ export function applyOfferAnswer(state, id, choice) {
401
+ const next = { languages: { ...state.languages }, neverAsk: state.neverAsk, ignored: state.ignored };
402
+ if (choice === "yes") next.languages[id] = "on";
403
+ else if (choice === "never") next.languages[id] = "never";
404
+ else if (choice === "never-ask") next.neverAsk = true;
405
+ else if (choice === "ignored") next.ignored += 1;
406
+ return next;
407
+ }
408
+
409
+ /** The offer's rows, the first highlighted. Swift needs no download, so it is "turn on". */
410
+ export function offerRows(lang, { needsInstall }) {
411
+ const install = lang.tool ? `Yes, install ${lang.server} (${lang.tool.what})` : `Yes, install ${lang.server} (${lang.size}, into ~/.gonext/lsp)`;
412
+ return [
413
+ needsInstall ? install : "Yes, turn it on",
414
+ "Not now",
415
+ `Never for ${lang.name}`,
416
+ "Never ask about language servers",
417
+ ];
418
+ }
419
+ export const OFFER_CHOICES = ["yes", "not-now", "never", "never-ask"];
420
+
421
+ // ---------------------------------------------------------------------------------------------
422
+ // finding the server
423
+ // ---------------------------------------------------------------------------------------------
424
+
425
+ /** An executable on PATH (Windows: with its .cmd/.exe), or "". */
426
+ export function whichOnPath(name, { env = process.env, platform = process.platform } = {}) {
427
+ const exts = platform === "win32" ? (env.PATHEXT || ".EXE;.CMD;.BAT").split(";").map((e) => e.toLowerCase()) : [""];
428
+ for (const dir of String(env.PATH ?? env.Path ?? "").split(delimiter)) {
429
+ if (!dir) continue;
430
+ for (const e of exts) {
431
+ const p = join(dir, name + e);
432
+ try {
433
+ if (statSync(p).isFile()) return p;
434
+ } catch {}
435
+ }
436
+ }
437
+ return "";
438
+ }
439
+
440
+ /**
441
+ * The Xcode to use on macOS. A broken Command Line Tools install is common (seen on our own Mac:
442
+ * `swift package` crashes with a dyld symbol error) while Xcode itself works — so when
443
+ * xcode-select points at the Command Line Tools and Xcode.app exists, Xcode wins.
444
+ */
445
+ export function xcodeDeveloperDir({ exists = existsSync, selected = "" } = {}) {
446
+ const xcode = "/Applications/Xcode.app/Contents/Developer";
447
+ if (selected && !/CommandLineTools/.test(selected)) return selected;
448
+ return exists(xcode) ? xcode : selected;
449
+ }
450
+
451
+ /**
452
+ * How to start a language's server here → { cmd, args, env } or null (not installed).
453
+ * Order: gu's own install (~/.gonext/lsp), then PATH; Swift on macOS through xcrun with the Xcode
454
+ * picked above.
455
+ */
456
+ export function resolveServer(lang, { home, platform = process.platform, env = process.env, run = execFileSync, exists = existsSync } = {}) {
457
+ if (lang.custom) {
458
+ // A path ("./tools/my-ls", "/opt/x/bin/ls") is used as written; a bare name is looked up on PATH.
459
+ const childEnv = { ...env, ...lang.env };
460
+ const cmd = /[\\/]/.test(lang.command) ? (isAbsolute(lang.command) ? lang.command : "") : whichOnPath(lang.command, { env, platform });
461
+ return cmd && exists(cmd) ? { cmd, args: lang.args, env: childEnv } : null;
462
+ }
463
+ if (lang.extraDirs) {
464
+ const onPath = whichOnPath(lang.bin, { env, platform });
465
+ if (onPath) return { cmd: onPath, args: lang.args, env: { ...env } };
466
+ const exe = platform === "win32" ? ".exe" : "";
467
+ for (const d of lang.extraDirs(home, env).filter(Boolean)) {
468
+ const p = join(d, lang.bin + exe);
469
+ if (exists(p)) return { cmd: p, args: lang.args, env: { ...env } };
470
+ }
471
+ return null;
472
+ }
473
+ if (lang.xcrun && platform === "darwin") {
474
+ let selected = "";
475
+ try {
476
+ selected = String(run("xcode-select", ["-p"], { encoding: "utf8", timeout: 5000 })).trim();
477
+ } catch {}
478
+ const dev = xcodeDeveloperDir({ exists, selected });
479
+ const childEnv = dev ? { ...env, DEVELOPER_DIR: dev } : { ...env };
480
+ try {
481
+ const cmd = String(run("xcrun", ["-f", lang.bin], { encoding: "utf8", timeout: 10_000, env: childEnv })).trim();
482
+ if (cmd && exists(cmd)) return { cmd, args: lang.args, env: childEnv };
483
+ } catch {}
484
+ const onPath = whichOnPath(lang.bin, { env, platform });
485
+ return onPath ? { cmd: onPath, args: lang.args, env: childEnv } : null;
486
+ }
487
+ if (lang.npm && home) {
488
+ const local = join(lspInstallDir(home), "node_modules", ".bin", lang.bin + (platform === "win32" ? ".cmd" : ""));
489
+ const complete = (lang.needs ?? []).every((rel) => exists(join(lspInstallDir(home), rel)));
490
+ if (exists(local) && complete) return { cmd: local, args: lang.args, env: { ...env } };
491
+ }
492
+ const onPath = whichOnPath(lang.bin, { env, platform });
493
+ return onPath ? { cmd: onPath, args: lang.args, env: { ...env } } : null;
494
+ }
495
+
496
+ /**
497
+ * Can gu install this language's server itself? npm ones always (into ~/.gonext/lsp); Go and Rust
498
+ * when their own tool (`go`, `rustup`) is on this computer. Swift and C/C++ come with their toolchain.
499
+ */
500
+ export function canInstall(lang, { env = process.env, platform = process.platform } = {}) {
501
+ if (Array.isArray(lang.npm) && lang.npm.length > 0) return true;
502
+ return Boolean(lang.tool && whichOnPath(lang.tool.cmd, { env, platform }));
503
+ }
504
+
505
+ /** The command that installs a server: npm into gu's own folder, or the language's own tool. */
506
+ export const installCommand = (lang, home) =>
507
+ lang.tool
508
+ ? { cmd: lang.tool.cmd, args: [...lang.tool.args] }
509
+ : { cmd: "npm", args: ["install", "--prefix", lspInstallDir(home), "--no-audit", "--no-fund", "--loglevel=error", ...lang.npm] };
510
+
511
+ // ---------------------------------------------------------------------------------------------
512
+ // the project a file belongs to
513
+ // ---------------------------------------------------------------------------------------------
514
+
515
+ function hasMarker(dir, marker) {
516
+ if (marker.startsWith("*")) {
517
+ const suffix = marker.slice(1);
518
+ try {
519
+ return readdirSync(dir).some((n) => n.endsWith(suffix));
520
+ } catch {
521
+ return false;
522
+ }
523
+ }
524
+ return existsSync(join(dir, marker));
525
+ }
526
+
527
+ /**
528
+ * The project root a server should be started in: the nearest folder above the file holding one
529
+ * of the language's markers (tsconfig.json, Package.swift…), never above the workspace. None found
530
+ * → the workspace itself. One server per root, so a monorepo's packages each get the right one.
531
+ */
532
+ export function findProjectRoot(file, lang, workspace) {
533
+ const ws = workspace ? resolve(workspace) : "";
534
+ let dir = dirname(resolve(file));
535
+ const top = parsePath(dir).root;
536
+ for (;;) {
537
+ for (const m of lang.roots) if (hasMarker(dir, m)) return dir;
538
+ if ((ws && dir === ws) || dir === top) break;
539
+ if (ws && !dir.startsWith(ws)) break;
540
+ dir = dirname(dir);
541
+ }
542
+ return ws || dirname(resolve(file));
543
+ }
544
+
545
+ // ---------------------------------------------------------------------------------------------
546
+ // what the agent is told
547
+ // ---------------------------------------------------------------------------------------------
548
+
549
+ export const LSP_MAX_REPORTED = 10;
550
+
551
+ /**
552
+ * Diagnostics → what the agent reads after an edit. Errors always; warnings only on the lines the
553
+ * edit changed (the rest were there before and are not this edit's business). At most 10.
554
+ * `changed`: [from, to] 1-based, or null for a whole-file write (then no warnings at all).
555
+ */
556
+ export function pickDiagnostics(diags, changed) {
557
+ const sev = (d) => (d?.severity ?? 1);
558
+ const line = (d) => (d?.range?.start?.line ?? 0) + 1;
559
+ const inChange = (d) => Array.isArray(changed) && line(d) >= changed[0] && line(d) <= changed[1];
560
+ const errors = (diags ?? []).filter((d) => sev(d) === 1);
561
+ const warnings = (diags ?? []).filter((d) => sev(d) === 2 && inChange(d));
562
+ const clean = (s) => String(s ?? "").replace(/\s+/g, " ").trim().slice(0, 240);
563
+ const rows = [...errors.map((d) => ({ kind: "error", d })), ...warnings.map((d) => ({ kind: "warning", d }))]
564
+ .sort((a, b) => line(a.d) - line(b.d))
565
+ .slice(0, LSP_MAX_REPORTED)
566
+ .map(({ kind, d }) => ({ kind, line: line(d), col: (d?.range?.start?.character ?? 0) + 1, message: clean(d?.message) }));
567
+ return { errors: errors.length, warnings: warnings.length, rows };
568
+ }
package/model-doctor.mjs CHANGED
@@ -14,6 +14,7 @@ import { arch, homedir, platform, totalmem } from "node:os";
14
14
  import { join } from "node:path";
15
15
  import { fileURLToPath } from "node:url";
16
16
  import { ensureSupportedPython, isBuildToolsMissing, buildFailureMessage, ownVenvPython } from "./platform-tools.mjs";
17
+ import { shellCommand } from "./win-shell.mjs";
17
18
 
18
19
  // Minimum RAM to run the default 14B-4bit chat model comfortably on Apple Silicon.
19
20
  const MIN_CHAT_RAM_GB = 16;
@@ -1407,8 +1408,10 @@ export function skillsNodeDir() {
1407
1408
  function npmInstallInto(dir, pkgs) {
1408
1409
  const win = platform() === "win32";
1409
1410
  return new Promise((resolve, reject) => {
1410
- execFile(win ? "npm.cmd" : "npm", ["install", "--prefix", dir, "--no-audit", "--no-fund", "--loglevel=error", ...pkgs],
1411
- { shell: win, timeout: 600000, windowsHide: true }, (err, _out, errOut) => {
1411
+ // One string on Windows (shellCommand): an args array with shell:true prints DEP0190 (GH #557).
1412
+ const sc = shellCommand(win ? "npm.cmd" : "npm", ["install", "--prefix", dir, "--no-audit", "--no-fund", "--loglevel=error", ...pkgs]);
1413
+ execFile(sc.cmd, sc.args,
1414
+ { shell: sc.shell, timeout: 600000, windowsHide: true }, (err, _out, errOut) => {
1412
1415
  if (err) reject(new Error(String(errOut || err.message).trim().split("\n").slice(-3).join(" ")));
1413
1416
  else resolve();
1414
1417
  });