zidane-gui 8.1.0 → 8.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.
@@ -1,10 +1,21 @@
1
1
  import { spawn } from "node:child_process";
2
- import { join, dirname } from "node:path";
2
+ import { posix, join, dirname, relative } from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
4
  import { m as makeToolContext } from "./chunks/context-77_UZfgL.js";
5
5
  import { realpathSync, existsSync } from "node:fs";
6
+ import { access } from "node:fs/promises";
6
7
  import { createRequire } from "node:module";
7
- import "node:fs/promises";
8
+ const RPC_METHOD_NOT_FOUND = -32601;
9
+ const RPC_INTERNAL_ERROR = -32603;
10
+ const LSP_CONTENT_MODIFIED = -32801;
11
+ const LSP_SERVER_CANCELLED = -32802;
12
+ class RpcError extends Error {
13
+ code;
14
+ constructor(message, code) {
15
+ super(message);
16
+ this.code = code;
17
+ }
18
+ }
8
19
  class JsonRpcConnection {
9
20
  #child;
10
21
  /** Unparsed chunks; concatenated only when a frame boundary needs it (no O(n²) concat per chunk). */
@@ -19,18 +30,20 @@ class JsonRpcConnection {
19
30
  constructor(child) {
20
31
  this.#child = child;
21
32
  child.stdout?.on("data", (chunk) => this.#onData(chunk));
22
- const close = () => {
33
+ const close = (info) => {
23
34
  if (this.#closed) return;
24
35
  this.#closed = true;
36
+ const reason = info.error ? info.error.message : "connection closed";
25
37
  for (const p of this.#pending.values()) {
26
38
  clearTimeout(p.timer);
27
- p.reject(new Error("connection closed"));
39
+ p.reject(new Error(reason));
28
40
  }
29
41
  this.#pending.clear();
30
- this.onClose?.();
42
+ this.onClose?.(info);
31
43
  };
32
- child.on("exit", close);
33
- child.on("error", close);
44
+ child.on("exit", (code, signal) => close({ code, signal }));
45
+ child.on("error", (error) => close({ code: null, signal: null, error }));
46
+ child.stdin?.on("error", () => void 0);
34
47
  }
35
48
  get closed() {
36
49
  return this.#closed;
@@ -38,7 +51,7 @@ class JsonRpcConnection {
38
51
  onNotification(method, handler) {
39
52
  this.#notifications.set(method, handler);
40
53
  }
41
- /** Server → client requests (e.g. `client/registerCapability`); default replies null. */
54
+ /** Server → client requests (e.g. `client/registerCapability`); unregistered ones get MethodNotFound. */
42
55
  onRequest(method, handler) {
43
56
  this.#requests.set(method, handler);
44
57
  }
@@ -132,13 +145,20 @@ class JsonRpcConnection {
132
145
  if (msg.method !== void 0) {
133
146
  if (msg.id !== void 0) {
134
147
  const handler = this.#requests.get(msg.method);
135
- let result = null;
148
+ if (!handler) {
149
+ this.#send({
150
+ jsonrpc: "2.0",
151
+ id: msg.id,
152
+ error: { code: RPC_METHOD_NOT_FOUND, message: `Unhandled method ${msg.method}` }
153
+ });
154
+ return;
155
+ }
136
156
  try {
137
- result = handler ? handler(msg.params) : null;
138
- } catch {
139
- result = null;
157
+ this.#send({ jsonrpc: "2.0", id: msg.id, result: handler(msg.params) ?? null });
158
+ } catch (err) {
159
+ const message = err instanceof Error ? err.message : String(err);
160
+ this.#send({ jsonrpc: "2.0", id: msg.id, error: { code: RPC_INTERNAL_ERROR, message } });
140
161
  }
141
- this.#send({ jsonrpc: "2.0", id: msg.id, result });
142
162
  } else {
143
163
  this.#notifications.get(msg.method)?.(msg.params);
144
164
  }
@@ -149,7 +169,7 @@ class JsonRpcConnection {
149
169
  if (!p) return;
150
170
  this.#pending.delete(msg.id);
151
171
  clearTimeout(p.timer);
152
- if (msg.error) p.reject(new Error(msg.error.message ?? "request failed"));
172
+ if (msg.error) p.reject(new RpcError(msg.error.message ?? "request failed", msg.error.code));
153
173
  else p.resolve(msg.result);
154
174
  }
155
175
  }
@@ -272,10 +292,57 @@ function languageIdFor(server, path) {
272
292
  const ext = path.split(".").pop()?.toLowerCase() ?? "";
273
293
  return server.languageIds?.[ext] ?? ext;
274
294
  }
295
+ function splitCommand(line) {
296
+ const words = [];
297
+ let word = "";
298
+ let inWord = false;
299
+ let quote = null;
300
+ for (let i = 0; i < line.length; i++) {
301
+ const c = line[i];
302
+ if (quote) {
303
+ if (c === quote) quote = null;
304
+ else if (c === "\\" && quote === '"' && i + 1 < line.length) word += line[++i];
305
+ else word += c;
306
+ } else if (c === '"' || c === "'") {
307
+ quote = c;
308
+ inWord = true;
309
+ } else if (c === "\\" && i + 1 < line.length) {
310
+ word += line[++i];
311
+ inWord = true;
312
+ } else if (/\s/.test(c)) {
313
+ if (inWord) words.push(word);
314
+ word = "";
315
+ inWord = false;
316
+ } else {
317
+ word += c;
318
+ inWord = true;
319
+ }
320
+ }
321
+ if (inWord) words.push(word);
322
+ return words;
323
+ }
324
+ async function projectRootFor(cwd, path, signals) {
325
+ const has = async (dir) => {
326
+ for (const s of signals) {
327
+ try {
328
+ await access(join(cwd, dir, s));
329
+ return true;
330
+ } catch {
331
+ }
332
+ }
333
+ return false;
334
+ };
335
+ if (await has("")) return "";
336
+ for (let dir = posix.dirname(path); dir !== "." && dir !== "/" && dir !== ""; dir = posix.dirname(dir)) {
337
+ if (await has(dir)) return dir;
338
+ }
339
+ return null;
340
+ }
275
341
  async function detectServer(ctx, server, override) {
276
342
  if (!await ctx.hasFile(...server.signals)) return null;
277
- if (override?.trim()) {
278
- const [bin2, ...args] = override.trim().split(/\s+/);
343
+ const words = override ? splitCommand(override.trim()) : [];
344
+ if (words.length > 0) {
345
+ const [bin2, ...args] = words;
279
346
  return { bin: bin2, args };
280
347
  }
281
348
  const project = await server.project?.(ctx).catch(() => null);
@@ -287,17 +354,59 @@ async function detectServer(ctx, server, override) {
287
354
  }
288
355
  const SEVERITY = { 1: "error", 2: "warning", 3: "info", 4: "hint" };
289
356
  const MAX_RESTARTS = 3;
357
+ const STABLE_RUN_MS = 5 * 6e4;
358
+ const RESTART_BACKOFF_MS = [1e3, 4e3, 16e3];
290
359
  const START_COOLDOWN_MS = 6e4;
360
+ const EXIT_GRACE_MS = 2e3;
291
361
  const MAX_INCREMENTAL_CHANGES = 64;
362
+ const POSITIONAL_TIMEOUT_MS = 1e4;
363
+ const MAX_COMPLETION_ITEMS = 500;
364
+ const NEGATIVE_CACHE_MS = 3e4;
365
+ const COMPLETION_KINDS = [
366
+ "",
367
+ "text",
368
+ "method",
369
+ "function",
370
+ "constructor",
371
+ "field",
372
+ "variable",
373
+ "class",
374
+ "interface",
375
+ "module",
376
+ "property",
377
+ "unit",
378
+ "value",
379
+ "enum",
380
+ "keyword",
381
+ "snippet",
382
+ "color",
383
+ "file",
384
+ "reference",
385
+ "folder",
386
+ "enum-member",
387
+ "constant",
388
+ "struct",
389
+ "event",
390
+ "operator",
391
+ "type-parameter"
392
+ ];
292
393
  class ServerClient {
394
+ /** The session folder: document paths are relative to it. */
293
395
  cwd;
396
+ /** Where the server runs (its `rootUri`): `cwd`, or a project folder inside it. */
397
+ root;
294
398
  server;
295
399
  #conn = null;
400
+ #child = null;
296
401
  #ready = null;
402
+ /** `initialize` answered for the current connection. */
403
+ #initialized = false;
404
+ /** Documents the server has (kept across a crash, sent again on restart). */
297
405
  #docs = /* @__PURE__ */ new Map();
298
406
  #diagnostics = /* @__PURE__ */ new Map();
299
407
  #idleTimer = null;
300
- /** One in-flight hover / definition at a time: a newer one cancels the older on the server. */
408
+ #restartTimer = null;
409
+ /** One in-flight request per kind: a newer one cancels the older on the server. */
301
410
  #inflight = /* @__PURE__ */ new Map();
302
411
  /** Server accepts incremental `didChange` (textDocumentSync 2). */
303
412
  #incremental = false;
@@ -309,21 +418,34 @@ class ServerClient {
309
418
  #pull = false;
310
419
  /** In-flight pull per document; a newer one cancels the older on the server. */
311
420
  #pulls = /* @__PURE__ */ new Map();
421
+ #completionProvider = false;
422
+ #completionResolve = false;
423
+ #triggerCharacters = /* @__PURE__ */ new Set();
424
+ /** The last completion answer, kept raw for `completionItem/resolve`. */
425
+ #completion = null;
426
+ #completionSeq = 0;
427
+ /** Work-done progress by token (`$/progress`). */
428
+ #progress = /* @__PURE__ */ new Map();
429
+ /** The first loading round finished: later progress (a `cargo check`) no longer means \"not ready\". */
430
+ #warm = false;
431
+ /** rust-analyzer's `experimental/serverStatus`: authoritative when sent. */
432
+ #quiescent = null;
312
433
  #restarts = 0;
313
- /** After a failed spawn/initialize, do not retry before this time. */
434
+ #startedAt = 0;
435
+ /** After a failed start (or too many crashes), do not retry before this time. */
314
436
  #retryAfter = 0;
437
+ #stderr = "";
315
438
  #command;
316
- #onDown;
317
439
  #idleMs;
318
440
  #emit;
319
441
  lastError = null;
320
- constructor(cwd, server, command, idleMs, onDown, emit) {
321
- this.#emit = emit;
442
+ constructor(cwd, root, server, command, idleMs, emit) {
322
443
  this.cwd = cwd;
444
+ this.root = root;
323
445
  this.server = server;
324
446
  this.#command = command;
325
447
  this.#idleMs = idleMs;
326
- this.#onDown = onDown;
448
+ this.#emit = emit;
327
449
  }
328
450
  get running() {
329
451
  return this.#conn !== null && !this.#conn.closed;
@@ -331,8 +453,25 @@ class ServerClient {
331
453
  get openCount() {
332
454
  return this.#docs.size;
333
455
  }
456
+ get commandLine() {
457
+ return [this.#command.bin, ...this.#command.args].join(" ");
458
+ }
459
+ get log() {
460
+ return this.#stderr;
461
+ }
462
+ /** What the server is still doing before its answers are complete, or undefined when it is ready. */
463
+ get busy() {
464
+ if (!this.running) return this.#restartTimer ? `${this.server.binary}: restarting` : void 0;
465
+ if (!this.#initialized) return `${this.server.binary}: starting`;
466
+ if (this.#quiescent === true) return void 0;
467
+ if (this.#quiescent === null && this.#warm) return void 0;
468
+ const latest = [...this.#progress.values()].pop();
469
+ if (!latest) return this.#quiescent === false ? `${this.server.binary}: loading the project` : void 0;
470
+ const pct = latest.percentage !== void 0 ? ` ${Math.round(latest.percentage)}%` : "";
471
+ return `${this.server.binary}: ${latest.title}${latest.message ? ` ${latest.message}` : ""}${pct}`;
472
+ }
334
473
  isOpen(path) {
335
- return this.#docs.has(path);
474
+ return this.running && this.#docs.has(path);
336
475
  }
337
476
  diagnosticsFor(path) {
338
477
  return this.#diagnostics.get(path) ?? [];
@@ -347,69 +486,190 @@ class ServerClient {
347
486
  }
348
487
  #start() {
349
488
  if (this.#ready) return this.#ready;
350
- this.#ready = (async () => {
489
+ if (this.#restartTimer) clearTimeout(this.#restartTimer);
490
+ this.#restartTimer = null;
491
+ const ready = (async () => {
351
492
  const child = spawn(this.#command.bin, [...this.#command.args], {
352
- cwd: this.cwd,
493
+ cwd: this.root,
353
494
  stdio: ["pipe", "pipe", "pipe"],
354
495
  env: { ...process.env, ...this.#command.env }
355
496
  });
356
497
  const conn = new JsonRpcConnection(child);
498
+ this.#child = child;
357
499
  this.#conn = conn;
500
+ this.#initialized = false;
501
+ this.#warm = false;
502
+ this.#quiescent = null;
503
+ this.#progress.clear();
358
504
  child.stderr?.on("data", (d) => {
359
- this.lastError = d.toString("utf8").trim().slice(-500) || this.lastError;
505
+ this.#stderr = (this.#stderr + d.toString("utf8")).slice(-4e3);
360
506
  });
361
- conn.onNotification("textDocument/publishDiagnostics", (params) => this.#onPublish(params));
362
- conn.onRequest("window/workDoneProgress/create", () => null);
363
- conn.onRequest("client/registerCapability", () => null);
364
- conn.onRequest("workspace/configuration", (params) => {
365
- const items = params?.items ?? [];
366
- return items.map(() => null);
367
- });
368
- conn.onClose = () => {
369
- this.#conn = null;
370
- this.#ready = null;
371
- this.#diagnostics.clear();
372
- const hadDocs = this.#docs.size > 0;
373
- this.#docs.clear();
374
- if (hadDocs && this.#restarts < MAX_RESTARTS) {
375
- this.#restarts++;
376
- } else if (hadDocs) {
377
- this.lastError = `stopped after ${MAX_RESTARTS} crashes${this.lastError ? `: ${this.lastError}` : ""}`;
378
- }
379
- this.#onDown();
380
- };
381
- const rootUri = pathToFileURL(this.cwd).href;
507
+ conn.onClose = (info) => this.#onClose(conn, info);
508
+ this.#wire(conn);
509
+ const rootUri = pathToFileURL(this.root).href;
382
510
  const init = await conn.request(
383
511
  "initialize",
384
512
  {
385
513
  processId: process.pid,
514
+ clientInfo: { name: "zidane" },
386
515
  rootUri,
387
- workspaceFolders: [{ uri: rootUri, name: this.cwd.split("/").pop() ?? "workspace" }],
516
+ workspaceFolders: [{ uri: rootUri, name: this.root.split("/").pop() ?? "workspace" }],
388
517
  capabilities: {
518
+ general: { positionEncodings: ["utf-16"] },
519
+ window: { workDoneProgress: true },
389
520
  textDocument: {
390
521
  publishDiagnostics: { relatedInformation: false },
391
522
  diagnostic: { dynamicRegistration: false, relatedDocumentSupport: false },
392
523
  hover: { contentFormat: ["markdown", "plaintext"] },
393
524
  definition: { linkSupport: true },
394
- synchronization: { didSave: false, willSave: false }
525
+ synchronization: { didSave: false, willSave: false },
526
+ completion: {
527
+ contextSupport: true,
528
+ completionItem: {
529
+ snippetSupport: true,
530
+ insertReplaceSupport: true,
531
+ labelDetailsSupport: true,
532
+ preselectSupport: true,
533
+ documentationFormat: ["markdown", "plaintext"],
534
+ resolveSupport: { properties: ["documentation", "detail", "additionalTextEdits"] }
535
+ },
536
+ completionList: { itemDefaults: ["editRange", "insertTextFormat", "data"] }
537
+ }
395
538
  },
396
- workspace: { configuration: true, workspaceFolders: true }
539
+ workspace: { configuration: true, workspaceFolders: true, diagnostics: { refreshSupport: true } },
540
+ experimental: { serverStatusNotification: true }
397
541
  },
398
542
  initializationOptions: mergeInit(this.server.initializationOptions, this.#command.initializationOptions)
399
543
  },
400
544
  3e4
401
545
  );
402
- const sync = init?.capabilities?.textDocumentSync;
546
+ if (this.#conn !== conn) throw new Error("stopped while starting");
547
+ const caps = init?.capabilities;
548
+ const sync = caps?.textDocumentSync;
403
549
  this.#incremental = sync === 2 || typeof sync === "object" && sync?.change === 2;
404
- this.#pull = Boolean(init?.capabilities?.diagnosticProvider);
550
+ this.#pull = Boolean(caps?.diagnosticProvider);
551
+ this.#completionProvider = Boolean(caps?.completionProvider);
552
+ this.#completionResolve = Boolean(caps?.completionProvider?.resolveProvider);
553
+ this.#triggerCharacters = new Set(caps?.completionProvider?.triggerCharacters ?? []);
405
554
  conn.notify("initialized", {});
555
+ this.#initialized = true;
556
+ this.#startedAt = Date.now();
557
+ this.lastError = null;
558
+ for (const [path, doc] of this.#docs) {
559
+ doc.version = 1;
560
+ conn.notify("textDocument/didOpen", {
561
+ textDocument: {
562
+ uri: this.#uri(path),
563
+ languageId: languageIdFor(this.server, path),
564
+ version: 1,
565
+ text: doc.text
566
+ }
567
+ });
568
+ }
569
+ const first = this.#docs.keys().next();
570
+ if (!first.done) this.#pullDiagnostics(first.value);
406
571
  })();
407
- this.#ready.catch((err) => {
408
- this.#ready = null;
572
+ this.#ready = ready;
573
+ ready.catch((err) => {
574
+ if (this.#ready === ready) this.#ready = null;
409
575
  this.#retryAfter = Date.now() + START_COOLDOWN_MS;
410
- this.lastError = err instanceof Error ? err.message : String(err);
576
+ const message = err instanceof Error ? err.message : String(err);
577
+ if (message !== "stopped while starting") this.lastError = this.#withLog(`failed to start: ${message}`);
578
+ const child = this.#child;
579
+ this.#conn = null;
580
+ this.#child = null;
581
+ if (child && child.exitCode === null && child.signalCode === null) child.kill();
582
+ });
583
+ return ready;
584
+ }
585
+ #wire(conn) {
586
+ conn.onNotification("textDocument/publishDiagnostics", (params) => this.#onPublish(params));
587
+ conn.onNotification("$/progress", (params) => this.#onProgress(params));
588
+ conn.onNotification("experimental/serverStatus", (params) => {
589
+ const quiescent = params?.quiescent;
590
+ if (typeof quiescent === "boolean") this.#quiescent = quiescent;
591
+ });
592
+ conn.onRequest("window/workDoneProgress/create", () => null);
593
+ conn.onRequest("client/registerCapability", () => null);
594
+ conn.onRequest("client/unregisterCapability", () => null);
595
+ conn.onRequest("window/showMessageRequest", () => null);
596
+ conn.onRequest("window/showDocument", () => ({ success: false }));
597
+ conn.onRequest("workspace/applyEdit", () => ({ applied: false, failureReason: "not supported by this client" }));
598
+ conn.onRequest("workspace/workspaceFolders", () => {
599
+ const uri = pathToFileURL(this.root).href;
600
+ return [{ uri, name: this.root.split("/").pop() ?? "workspace" }];
601
+ });
602
+ conn.onRequest("workspace/configuration", (params) => {
603
+ const items = params?.items ?? [];
604
+ return items.map(() => null);
411
605
  });
412
- return this.#ready;
606
+ conn.onRequest("workspace/diagnostic/refresh", () => {
607
+ const first = this.#docs.keys().next();
608
+ if (!first.done) queueMicrotask(() => this.#pullDiagnostics(first.value));
609
+ return null;
610
+ });
611
+ }
612
+ #withLog(message) {
613
+ const tail = this.#stderr.trim().split("\n").filter((l) => l.trim()).slice(-3).join("\n");
614
+ return tail ? `${message}
615
+ ${tail}` : message;
616
+ }
617
+ #onClose(conn, info) {
618
+ if (this.#conn !== conn) return;
619
+ const initialized = this.#initialized;
620
+ this.#conn = null;
621
+ this.#child = null;
622
+ this.#ready = null;
623
+ this.#initialized = false;
624
+ this.#progress.clear();
625
+ this.#pulls.clear();
626
+ this.#inflight.clear();
627
+ this.#completion = null;
628
+ for (const path of this.#diagnostics.keys())
629
+ this.#emit({ kind: "diagnostics", cwd: this.cwd, path, diagnostics: [] });
630
+ this.#diagnostics.clear();
631
+ if (!initialized) return;
632
+ const how = info.error ? info.error.message : info.signal ? `killed by ${info.signal}` : `exited with code ${info.code ?? "?"}`;
633
+ this.lastError = this.#withLog(`crashed (${how})`);
634
+ if (this.#docs.size === 0) return;
635
+ if (Date.now() - this.#startedAt > STABLE_RUN_MS) this.#restarts = 0;
636
+ if (this.#restarts >= MAX_RESTARTS) {
637
+ this.lastError = this.#withLog(`stopped after ${MAX_RESTARTS} crashes (${how})`);
638
+ this.#docs.clear();
639
+ this.#restarts = 0;
640
+ this.#retryAfter = Date.now() + START_COOLDOWN_MS;
641
+ return;
642
+ }
643
+ const delay = RESTART_BACKOFF_MS[Math.min(this.#restarts, RESTART_BACKOFF_MS.length - 1)];
644
+ this.#restarts++;
645
+ this.#restartTimer = setTimeout(() => {
646
+ this.#restartTimer = null;
647
+ if (this.#docs.size > 0) void this.#start().catch(() => void 0);
648
+ }, delay);
649
+ }
650
+ #onProgress(params) {
651
+ const p = params;
652
+ const value = p?.value;
653
+ if (p?.token === void 0 || !value || typeof value !== "object") return;
654
+ if (value.kind === "begin") {
655
+ this.#progress.set(p.token, {
656
+ title: value.title ?? "working",
657
+ message: value.message,
658
+ percentage: value.percentage
659
+ });
660
+ } else if (value.kind === "report") {
661
+ const cur = this.#progress.get(p.token);
662
+ if (!cur) return;
663
+ this.#progress.delete(p.token);
664
+ this.#progress.set(p.token, {
665
+ title: cur.title,
666
+ message: value.message ?? cur.message,
667
+ percentage: value.percentage ?? cur.percentage
668
+ });
669
+ } else if (value.kind === "end") {
670
+ this.#progress.delete(p.token);
671
+ if (this.#progress.size === 0) this.#warm = true;
672
+ }
413
673
  }
414
674
  #onPublish(params) {
415
675
  const p = params;
@@ -458,15 +718,15 @@ class ServerClient {
458
718
  }
459
719
  #touch() {
460
720
  if (this.#idleTimer) clearTimeout(this.#idleTimer);
721
+ this.#idleTimer = null;
461
722
  if (this.#docs.size > 0) return;
462
723
  this.#idleTimer = setTimeout(() => void this.stop(), this.#idleMs);
463
724
  }
464
725
  async open(path, text, changes) {
465
- if (this.#restarts >= MAX_RESTARTS && !this.running) return;
466
726
  if (!this.running && Date.now() < this.#retryAfter) return;
467
727
  await this.#start().catch(() => void 0);
468
728
  const conn = this.#conn;
469
- if (!conn) return;
729
+ if (!conn || !this.#initialized) return;
470
730
  const existing = this.#docs.get(path);
471
731
  if (existing) {
472
732
  if (existing.text === text) return;
@@ -489,41 +749,229 @@ class ServerClient {
489
749
  close(path) {
490
750
  if (!this.#docs.delete(path)) return;
491
751
  this.#pulls.get(path)?.();
752
+ if (this.#completion?.path === path) this.#completion = null;
492
753
  this.#conn?.notify("textDocument/didClose", { textDocument: { uri: this.#uri(path) } });
493
754
  this.#diagnostics.delete(path);
755
+ if (this.#docs.size === 0 && this.#restartTimer) {
756
+ clearTimeout(this.#restartTimer);
757
+ this.#restartTimer = null;
758
+ }
494
759
  this.#touch();
495
760
  }
496
- #positional(kind, path, line, character) {
497
- if (!this.#conn || !this.#docs.has(path)) return Promise.resolve(null);
498
- this.#inflight.get(kind)?.();
499
- const { promise, cancel } = this.#conn.requestCancellable(
500
- `textDocument/${kind}`,
501
- { textDocument: { uri: this.#uri(path) }, position: { line: line - 1, character: character - 1 } },
502
- 5e3
503
- );
504
- this.#inflight.set(kind, cancel);
505
- return promise.catch(() => null).finally(() => {
506
- if (this.#inflight.get(kind) === cancel) this.#inflight.delete(kind);
507
- });
761
+ /** A request at a 1-based position; asked once more when the document moved under the server (`ContentModified`). */
762
+ async #positional(kind, path, line, character, extra) {
763
+ for (let attempt = 0; ; attempt++) {
764
+ const conn = this.#conn;
765
+ if (!conn || !this.#initialized || !this.#docs.has(path)) return null;
766
+ this.#inflight.get(kind)?.();
767
+ const { promise, cancel } = conn.requestCancellable(
768
+ `textDocument/${kind}`,
769
+ {
770
+ textDocument: { uri: this.#uri(path) },
771
+ position: { line: line - 1, character: character - 1 },
772
+ ...extra
773
+ },
774
+ POSITIONAL_TIMEOUT_MS
775
+ );
776
+ this.#inflight.set(kind, cancel);
777
+ try {
778
+ return await promise;
779
+ } catch (err) {
780
+ const code = err instanceof RpcError ? err.code : void 0;
781
+ if (attempt === 0 && (code === LSP_CONTENT_MODIFIED || code === LSP_SERVER_CANCELLED)) continue;
782
+ return null;
783
+ } finally {
784
+ if (this.#inflight.get(kind) === cancel) this.#inflight.delete(kind);
785
+ }
786
+ }
508
787
  }
509
788
  async definition(path, line, character) {
510
789
  return locationsIn(this.cwd, await this.#positional("definition", path, line, character));
511
790
  }
512
791
  async hover(path, line, character) {
513
792
  const res = await this.#positional("hover", path, line, character);
514
- return res ? hoverText(res.contents) : null;
793
+ const text = res ? hoverText(res.contents) : null;
794
+ const busy = text ? void 0 : this.busy;
795
+ return busy ? { text, busy } : { text };
796
+ }
797
+ async completion(path, line, character, trigger) {
798
+ const id = ++this.#completionSeq;
799
+ const empty = () => {
800
+ const busy = this.busy;
801
+ return busy ? { id, items: [], incomplete: true, busy } : { id, items: [], incomplete: false };
802
+ };
803
+ if (!this.#completionProvider) return empty();
804
+ if (trigger && !this.#triggerCharacters.has(trigger)) return { id, items: [], incomplete: false };
805
+ const context = trigger ? { triggerKind: 2, triggerCharacter: trigger } : { triggerKind: 1 };
806
+ const res = await this.#positional("completion", path, line, character, { context });
807
+ if (id !== this.#completionSeq) return { id, items: [], incomplete: true };
808
+ const list = Array.isArray(res) ? { items: res, isIncomplete: false } : res;
809
+ const all = Array.isArray(list?.items) ? list.items : [];
810
+ if (all.length === 0) return empty();
811
+ const defaults = Array.isArray(res) ? void 0 : res?.itemDefaults;
812
+ const sorted = all.length > MAX_COMPLETION_ITEMS ? sortCompletions(all).slice(0, MAX_COMPLETION_ITEMS) : all;
813
+ this.#completion = { id, path, items: sorted, defaults };
814
+ return {
815
+ id,
816
+ items: sorted.map((item) => completionItem(item, defaults)),
817
+ incomplete: Boolean(list?.isIncomplete) || sorted.length < all.length
818
+ };
819
+ }
820
+ async resolveCompletion(id, index) {
821
+ const last = this.#completion;
822
+ const raw = last?.id === id ? last.items[index] : void 0;
823
+ if (!last || !raw) return null;
824
+ let item = raw;
825
+ const conn = this.#conn;
826
+ if (this.#completionResolve && conn) {
827
+ const data = raw.data ?? last.defaults?.data;
828
+ item = await conn.request(
829
+ "completionItem/resolve",
830
+ data !== void 0 ? { ...raw, data } : raw,
831
+ 5e3
832
+ ).catch(() => null) ?? raw;
833
+ }
834
+ const documentation = documentationText(item.documentation);
835
+ const detail = item.detail ?? raw.detail;
836
+ return {
837
+ ...detail ? { detail } : {},
838
+ ...documentation ? { documentation } : {},
839
+ ...item.additionalTextEdits?.length ? { additionalEdits: item.additionalTextEdits } : {}
840
+ };
515
841
  }
516
842
  async stop() {
517
843
  if (this.#idleTimer) clearTimeout(this.#idleTimer);
844
+ if (this.#restartTimer) clearTimeout(this.#restartTimer);
845
+ this.#idleTimer = null;
846
+ this.#restartTimer = null;
518
847
  const conn = this.#conn;
519
- if (!conn) return;
848
+ const child = this.#child;
520
849
  this.#docs.clear();
521
850
  this.#diagnostics.clear();
851
+ this.#progress.clear();
852
+ this.#completion = null;
522
853
  this.#conn = null;
854
+ this.#child = null;
523
855
  this.#ready = null;
856
+ this.#initialized = false;
857
+ if (!conn) return;
524
858
  await conn.request("shutdown", null, 3e3).catch(() => void 0);
525
859
  conn.notify("exit");
860
+ if (child) {
861
+ setTimeout(() => {
862
+ if (child.exitCode === null && child.signalCode === null) child.kill();
863
+ }, EXIT_GRACE_MS).unref?.();
864
+ }
865
+ }
866
+ }
867
+ function sortCompletions(items) {
868
+ return [...items].sort((a, b) => {
869
+ if (a.preselect !== b.preselect) return a.preselect ? -1 : 1;
870
+ const sa = a.sortText ?? a.label;
871
+ const sb = b.sortText ?? b.label;
872
+ return sa < sb ? -1 : sa > sb ? 1 : 0;
873
+ });
874
+ }
875
+ function completionItem(item, defaults) {
876
+ const format = item.insertTextFormat ?? defaults?.insertTextFormat ?? 1;
877
+ let text;
878
+ let range;
879
+ if (item.textEdit) {
880
+ text = item.textEdit.newText;
881
+ range = item.textEdit.range ?? item.textEdit.insert;
882
+ } else {
883
+ text = item.textEditText ?? item.insertText ?? item.label;
884
+ const editRange = defaults?.editRange;
885
+ range = editRange ? "insert" in editRange ? editRange.insert : editRange : void 0;
886
+ }
887
+ const snippet = format === 2 ? flattenSnippet(text) : null;
888
+ const detail = item.labelDetails?.description ?? item.detail ?? item.labelDetails?.detail;
889
+ return {
890
+ label: item.label,
891
+ insertText: snippet ? snippet.text : text,
892
+ ...item.kind && COMPLETION_KINDS[item.kind] ? { kind: COMPLETION_KINDS[item.kind] } : {},
893
+ ...detail ? { detail } : {},
894
+ ...range ? { range } : {},
895
+ ...item.filterText ? { filterText: item.filterText } : {},
896
+ ...item.sortText ? { sortText: item.sortText } : {},
897
+ ...item.preselect ? { preselect: true } : {},
898
+ ...snippet?.cursor ? { cursor: snippet.cursor } : {}
899
+ };
900
+ }
901
+ function flattenSnippet(snippet) {
902
+ let out = "";
903
+ const stops = /* @__PURE__ */ new Map();
904
+ const parse = (s) => {
905
+ let text = "";
906
+ for (let i = 0; i < s.length; i++) {
907
+ const c = s[i];
908
+ if (c === "\\" && i + 1 < s.length && "$}\\,|".includes(s[i + 1])) {
909
+ text += s[++i];
910
+ continue;
911
+ }
912
+ if (c !== "$") {
913
+ text += c;
914
+ continue;
915
+ }
916
+ const bare = /^\$(\d+)/.exec(s.slice(i));
917
+ if (bare) {
918
+ const n = Number(bare[1]);
919
+ const at = out.length + text.length;
920
+ if (!stops.has(n)) stops.set(n, { start: at, end: at });
921
+ i += bare[0].length - 1;
922
+ continue;
923
+ }
924
+ if (s[i + 1] !== "{") {
925
+ const v2 = /^\$[A-Za-z_]\w*/.exec(s.slice(i));
926
+ if (v2) i += v2[0].length - 1;
927
+ else text += c;
928
+ continue;
929
+ }
930
+ let level = 0;
931
+ let j = i + 1;
932
+ for (; j < s.length; j++) {
933
+ if (s[j] === "\\") {
934
+ j++;
935
+ continue;
936
+ }
937
+ if (s[j] === "{") level++;
938
+ else if (s[j] === "}" && --level === 0) break;
939
+ }
940
+ const body = s.slice(i + 2, j);
941
+ i = j;
942
+ const m = /^(\d+)(?::([\s\S]*)|\|([\s\S]*)\|)?$/.exec(body);
943
+ if (m) {
944
+ const n = Number(m[1]);
945
+ const start = out.length + text.length;
946
+ let inner = "";
947
+ if (m[2] !== void 0) {
948
+ const saved = out;
949
+ out = out + text;
950
+ inner = parse(m[2]);
951
+ out = saved;
952
+ } else if (m[3] !== void 0) {
953
+ inner = m[3].split(/(?<!\\),/)[0]?.replace(/\\(.)/g, "$1") ?? "";
954
+ }
955
+ text += inner;
956
+ if (!stops.has(n)) stops.set(n, { start, end: start + inner.length });
957
+ continue;
958
+ }
959
+ const v = /^[A-Za-z_]\w*(?::([\s\S]*))?$/.exec(body);
960
+ if (v?.[1] !== void 0) text += parse(v[1]);
961
+ }
962
+ return text;
963
+ };
964
+ out = parse(snippet);
965
+ const first = [...stops.keys()].filter((n) => n > 0).sort((a, b) => a - b)[0];
966
+ const cursor = first !== void 0 ? stops.get(first) : stops.get(0);
967
+ return cursor && cursor.end <= out.length && !(cursor.start === out.length && cursor.end === out.length) ? { text: out, cursor } : { text: out };
968
+ }
969
+ function documentationText(doc) {
970
+ if (typeof doc === "string") return doc.trim() || void 0;
971
+ if (doc && typeof doc === "object" && typeof doc.value === "string") {
972
+ return doc.value.trim() || void 0;
526
973
  }
974
+ return void 0;
527
975
  }
528
976
  function mergeInit(base, extra) {
529
977
  const out = { ...base ?? {} };
@@ -615,9 +1063,16 @@ class DocOwners {
615
1063
  }
616
1064
  const DEFAULT_OWNER = "main";
617
1065
  class LspManager {
1066
+ /** By `${root}\0${server id}`. */
618
1067
  #clients = /* @__PURE__ */ new Map();
619
1068
  /** Detections in flight, so concurrent opens share one server. */
620
1069
  #starting = /* @__PURE__ */ new Map();
1070
+ /** Which client has each open document (`${cwd}\0${path}`). */
1071
+ #docClients = /* @__PURE__ */ new Map();
1072
+ /** Project root per (cwd, server, folder); misses expire (a manifest can appear). */
1073
+ #roots = /* @__PURE__ */ new Map();
1074
+ /** Clients that could not be made (no binary), by key, with when. */
1075
+ #missing = /* @__PURE__ */ new Map();
621
1076
  #owners = new DocOwners();
622
1077
  #options = { idleMs: 5 * 6e4, overrides: {} };
623
1078
  #emit;
@@ -625,34 +1080,46 @@ class LspManager {
625
1080
  this.#emit = emit;
626
1081
  }
627
1082
  configure(options) {
1083
+ const overridesChanged = options.overrides && options.overrides !== this.#options.overrides;
628
1084
  this.#options = { ...this.#options, ...options };
1085
+ if (overridesChanged) this.#missing.clear();
1086
+ }
1087
+ async #rootFor(cwd, path, server) {
1088
+ const folder = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
1089
+ const key = `${cwd}\0${server.id}\0${folder}`;
1090
+ const hit = this.#roots.get(key);
1091
+ if (hit && (hit.root !== null || Date.now() - hit.at < NEGATIVE_CACHE_MS)) return hit.root;
1092
+ const rel = await projectRootFor(cwd, path, server.signals);
1093
+ const root = rel === null ? null : rel ? join(cwd, rel) : cwd;
1094
+ this.#roots.set(key, { root, at: Date.now() });
1095
+ return root;
629
1096
  }
630
1097
  async #clientFor(cwd, path) {
631
1098
  const server = serverFor(path);
632
1099
  if (!server) return null;
633
- const key = `${cwd}\0${server.id}`;
1100
+ const root = await this.#rootFor(cwd, path, server);
1101
+ if (root === null) return null;
1102
+ const key = `${root}\0${server.id}`;
634
1103
  const existing = this.#clients.get(key);
635
1104
  if (existing) return existing;
1105
+ const missedAt = this.#missing.get(key);
1106
+ if (missedAt !== void 0 && Date.now() - missedAt < NEGATIVE_CACHE_MS) return null;
636
1107
  let starting = this.#starting.get(key);
637
1108
  if (!starting) {
638
- starting = this.#startClient(cwd, server, key).finally(() => this.#starting.delete(key));
1109
+ starting = this.#startClient(cwd, root, server, key).finally(() => this.#starting.delete(key));
639
1110
  this.#starting.set(key, starting);
640
1111
  }
641
1112
  return starting;
642
1113
  }
643
- async #startClient(cwd, server, key) {
644
- const ctx = makeToolContext(cwd, 1e4);
1114
+ async #startClient(cwd, root, server, key) {
1115
+ const ctx = makeToolContext(root, 1e4);
645
1116
  const detected = await detectServer(ctx, server, this.#options.overrides[server.id]);
646
- if (!detected || "missing" in detected) return null;
647
- const client = new ServerClient(
648
- cwd,
649
- server,
650
- detected,
651
- this.#options.idleMs,
652
- () => {
653
- },
654
- this.#emit
655
- );
1117
+ if (!detected || "missing" in detected) {
1118
+ this.#missing.set(key, Date.now());
1119
+ return null;
1120
+ }
1121
+ this.#missing.delete(key);
1122
+ const client = new ServerClient(cwd, root, server, detected, this.#options.idleMs, this.#emit);
656
1123
  this.#clients.set(key, client);
657
1124
  return client;
658
1125
  }
@@ -668,6 +1135,7 @@ class LspManager {
668
1135
  const client = await this.#clientFor(cwd, path);
669
1136
  if (!client) return [];
670
1137
  if (!this.#owners.owns(docKey, owner)) return [];
1138
+ this.#docClients.set(docKey, client);
671
1139
  if (step.kind === "attach" && client.isOpen(path)) return client.diagnosticsFor(path);
672
1140
  const incremental = step.kind === "change" && !step.full ? changes : void 0;
673
1141
  await client.open(path, text, incremental).catch(() => void 0);
@@ -676,47 +1144,60 @@ class LspManager {
676
1144
  /** `owner` closed `path`; the server hears `didClose` when it was the last one. */
677
1145
  close(cwd, path, owner = DEFAULT_OWNER) {
678
1146
  if (!this.#owners.close(`${cwd}\0${path}`, owner)) return;
679
- this.#closeDoc(cwd, path);
1147
+ this.#closeDoc(`${cwd}\0${path}`, path);
680
1148
  }
681
1149
  /** `owner` went away: close what only it had open. */
682
1150
  release(owner) {
683
- for (const key of this.#owners.release(owner)) {
684
- const at = key.indexOf("\0");
685
- this.#closeDoc(key.slice(0, at), key.slice(at + 1));
686
- }
1151
+ for (const key of this.#owners.release(owner)) this.#closeDoc(key, key.slice(key.indexOf("\0") + 1));
687
1152
  }
688
- #closeDoc(cwd, path) {
689
- const server = serverFor(path);
690
- if (!server) return;
691
- this.#clients.get(`${cwd}\0${server.id}`)?.close(path);
1153
+ #closeDoc(docKey, path) {
1154
+ const client = this.#docClients.get(docKey);
1155
+ this.#docClients.delete(docKey);
1156
+ client?.close(path);
692
1157
  }
693
1158
  async definition(cwd, path, line, character) {
694
- const server = serverFor(path);
695
- if (!server) return [];
696
- const client = this.#clients.get(`${cwd}\0${server.id}`);
1159
+ const client = this.#docClients.get(`${cwd}\0${path}`);
697
1160
  return client ? client.definition(path, line, character) : [];
698
1161
  }
699
1162
  async hover(cwd, path, line, character) {
700
- const server = serverFor(path);
701
- if (!server) return null;
702
- const client = this.#clients.get(`${cwd}\0${server.id}`);
703
- return client ? client.hover(path, line, character) : null;
1163
+ const client = this.#docClients.get(`${cwd}\0${path}`);
1164
+ return client ? client.hover(path, line, character) : { text: null };
1165
+ }
1166
+ /** Bring `path` up to `text` (as `open` does), then ask for completions at the 1-based position. */
1167
+ async completion(cwd, path, text, changes, line, character, trigger, owner = DEFAULT_OWNER) {
1168
+ await this.open(cwd, path, text, changes, owner);
1169
+ const client = this.#docClients.get(`${cwd}\0${path}`);
1170
+ return client ? client.completion(path, line, character, trigger) : { id: 0, items: [], incomplete: false };
1171
+ }
1172
+ async resolveCompletion(cwd, path, id, index) {
1173
+ const client = this.#docClients.get(`${cwd}\0${path}`);
1174
+ return client ? client.resolveCompletion(id, index) : null;
704
1175
  }
705
1176
  async list(cwd) {
706
1177
  const ctx = makeToolContext(cwd, 1e4);
707
1178
  return Promise.all(
708
1179
  LANGUAGE_SERVERS.map(async (server) => {
709
1180
  const d = await detectServer(ctx, server, this.#options.overrides[server.id]);
710
- const client = this.#clients.get(`${cwd}\0${server.id}`);
711
1181
  const base = { id: server.id, label: server.label, install: server.install };
712
- if (!d) return { ...base, status: "absent" };
713
- if ("missing" in d) return { ...base, status: "missing", detail: d.missing };
1182
+ const clients = [...this.#clients.values()].filter((c2) => c2.cwd === cwd && c2.server.id === server.id);
1183
+ if (clients.length === 0) {
1184
+ if (!d) return { ...base, status: "absent" };
1185
+ if ("missing" in d) return { ...base, status: "missing", detail: d.missing };
1186
+ return { ...base, status: "ready", detail: [d.bin, ...d.args].join(" ") };
1187
+ }
1188
+ const c = clients.find((x) => x.running) ?? clients.find((x) => x.lastError) ?? clients[0];
1189
+ const where = c.root !== cwd ? ` (in ${relative(cwd, c.root)})` : "";
1190
+ const open = clients.reduce((n, x) => n + x.openCount, 0);
1191
+ const busy = c.busy;
1192
+ const log = c.log.trim();
714
1193
  return {
715
1194
  ...base,
716
- status: client?.running ? "running" : client?.lastError ? "failed" : "ready",
717
- detail: [d.bin, ...d.args].join(" "),
718
- ...client?.openCount ? { openDocuments: client.openCount } : {},
719
- ...client?.lastError ? { lastError: client.lastError } : {}
1195
+ status: c.running ? "running" : c.lastError ? "failed" : "ready",
1196
+ detail: c.commandLine + where,
1197
+ ...open ? { openDocuments: open } : {},
1198
+ ...c.lastError ? { lastError: c.lastError } : {},
1199
+ ...busy ? { busy } : {},
1200
+ ...log ? { log } : {}
720
1201
  };
721
1202
  })
722
1203
  );
@@ -724,6 +1205,7 @@ class LspManager {
724
1205
  async stopAll() {
725
1206
  await Promise.all([...this.#clients.values()].map((c) => c.stop()));
726
1207
  this.#clients.clear();
1208
+ this.#docClients.clear();
727
1209
  }
728
1210
  }
729
1211
  const port = process.parentPort;