@weave-os/router 0.2.14

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.
Files changed (69) hide show
  1. package/LICENSE +90 -0
  2. package/README.md +172 -0
  3. package/bin.js +68 -0
  4. package/cc-statusline.sh +951 -0
  5. package/codex-skills/disable-routing/SKILL.md +22 -0
  6. package/codex-skills/fm/SKILL.md +15 -0
  7. package/codex-skills/fm/scripts/emit.sh +8 -0
  8. package/codex-skills/force-model/SKILL.md +15 -0
  9. package/codex-skills/force-model/scripts/emit.sh +9 -0
  10. package/codex-skills/rf/SKILL.md +15 -0
  11. package/codex-skills/rf/scripts/emit.sh +7 -0
  12. package/codex-skills/router-feedback/SKILL.md +15 -0
  13. package/codex-skills/router-feedback/scripts/emit.sh +9 -0
  14. package/codex-skills/router-models/SKILL.md +51 -0
  15. package/codex-skills/router-off/SKILL.md +22 -0
  16. package/codex-skills/router-on/SKILL.md +22 -0
  17. package/codex-skills/router-status/SKILL.md +19 -0
  18. package/codex-skills/ufm/SKILL.md +14 -0
  19. package/codex-skills/ufm/scripts/emit.sh +3 -0
  20. package/codex-skills/unforce-model/SKILL.md +14 -0
  21. package/codex-skills/unforce-model/scripts/emit.sh +4 -0
  22. package/codex-status.sh +378 -0
  23. package/commands/beta.md +5 -0
  24. package/commands/fm.md +6 -0
  25. package/commands/force-model.md +6 -0
  26. package/commands/models.md +46 -0
  27. package/commands/rf.md +6 -0
  28. package/commands/router-feedback.md +6 -0
  29. package/commands/router-models.md +46 -0
  30. package/commands/router-off.md +10 -0
  31. package/commands/router-on.md +10 -0
  32. package/commands/router-session.md +15 -0
  33. package/commands/router-status.md +10 -0
  34. package/commands/ufm.md +5 -0
  35. package/commands/unforce-model.md +5 -0
  36. package/directives.tsv +13 -0
  37. package/install.sh +5092 -0
  38. package/opencode-weave/README.md +78 -0
  39. package/opencode-weave/package.json +18 -0
  40. package/opencode-weave/src/index.ts +655 -0
  41. package/package.json +79 -0
  42. package/pi-router/README.md +123 -0
  43. package/pi-router/package.json +25 -0
  44. package/pi-router/skills/install-lsps/SKILL.md +75 -0
  45. package/pi-router/skills/lsp-guide/SKILL.md +63 -0
  46. package/pi-router/src/beta.ts +21 -0
  47. package/pi-router/src/compaction.ts +188 -0
  48. package/pi-router/src/config.ts +293 -0
  49. package/pi-router/src/context-window.ts +12 -0
  50. package/pi-router/src/dispatch.ts +377 -0
  51. package/pi-router/src/force-model.ts +126 -0
  52. package/pi-router/src/index.ts +62 -0
  53. package/pi-router/src/lsp-broker.ts +255 -0
  54. package/pi-router/src/lsp-client.ts +435 -0
  55. package/pi-router/src/lsp-format.ts +230 -0
  56. package/pi-router/src/lsp-install.ts +215 -0
  57. package/pi-router/src/lsp-protocol.ts +128 -0
  58. package/pi-router/src/lsp-servers.ts +361 -0
  59. package/pi-router/src/lsp.ts +529 -0
  60. package/pi-router/src/metadata.ts +32 -0
  61. package/pi-router/src/pricing.generated.ts +91 -0
  62. package/pi-router/src/provider.ts +64 -0
  63. package/pi-router/src/routed-model.ts +182 -0
  64. package/pi-router/src/safety.ts +66 -0
  65. package/pi-router/src/savings.ts +191 -0
  66. package/pi-router/src/ui.ts +91 -0
  67. package/pi-router/src/wooly.ts +408 -0
  68. package/registry.sh +102 -0
  69. package/uninstall.sh +788 -0
@@ -0,0 +1,435 @@
1
+ /**
2
+ * One language-server connection.
3
+ *
4
+ * The server is reached through an `LspTransport` rather than a ChildProcess so
5
+ * the protocol logic — handshake, document versioning, request correlation,
6
+ * diagnostics bookkeeping — is exercised in tests without spawning anything.
7
+ */
8
+
9
+ import { spawn as nodeSpawn, type ChildProcess, type SpawnOptions } from "node:child_process";
10
+ import * as path from "node:path";
11
+ import { createFrameParser, encodeFrame, pathToUri, type JsonRpcMessage } from "./lsp-protocol.js";
12
+ import type { LspDiagnostic } from "./lsp-format.js";
13
+
14
+ const STDERR_RING_BYTES = 4096;
15
+ const SHUTDOWN_BUDGET_MS = 1000;
16
+ const SIGKILL_GRACE_MS = 5000;
17
+ const METHOD_NOT_FOUND = -32601;
18
+
19
+ export interface TransportClose {
20
+ code: number | null;
21
+ stderr: string;
22
+ }
23
+
24
+ export interface LspTransport {
25
+ send(data: Buffer): void;
26
+ onMessage(handler: (message: JsonRpcMessage) => void): void;
27
+ onClose(handler: (info: TransportClose) => void): void;
28
+ /** Graceful stop: SIGTERM, then SIGKILL if the peer has not exited. */
29
+ kill(): void;
30
+ /** Synchronous SIGKILL for process-exit paths that cannot await anything. */
31
+ killNow(): void;
32
+ }
33
+
34
+ export type SpawnFn = (command: string, args: string[], options: SpawnOptions) => ChildProcess;
35
+
36
+ export function spawnTransport(command: string, args: string[], cwd: string, spawnFn: SpawnFn = nodeSpawn): LspTransport {
37
+ const child = spawnFn(command, args, { cwd, shell: false, detached: false, stdio: ["pipe", "pipe", "pipe"] });
38
+ const messageHandlers: Array<(message: JsonRpcMessage) => void> = [];
39
+ const closeHandlers: Array<(info: TransportClose) => void> = [];
40
+ let stderrTail = "";
41
+ let settled = false;
42
+
43
+ const appendStderr = (text: string): void => {
44
+ stderrTail = (stderrTail + text).slice(-STDERR_RING_BYTES);
45
+ };
46
+ const emitClose = (code: number | null): void => {
47
+ if (settled) return;
48
+ settled = true;
49
+ for (const handler of closeHandlers) handler({ code, stderr: stderrTail });
50
+ };
51
+
52
+ const parser = createFrameParser(
53
+ (message) => {
54
+ for (const handler of messageHandlers) handler(message);
55
+ },
56
+ (error) => {
57
+ appendStderr(`\n${error.message}`);
58
+ child.kill("SIGKILL");
59
+ },
60
+ );
61
+
62
+ child.stdout?.on("data", (chunk: Buffer) => parser.push(chunk));
63
+ // Server stderr is diagnostic noise (gopls indexing chatter); it feeds error
64
+ // messages only and is never streamed to the model.
65
+ child.stderr?.on("data", (chunk: Buffer) => appendStderr(chunk.toString("utf8")));
66
+ child.on("close", (code) => emitClose(code));
67
+ child.on("error", (error: Error) => {
68
+ appendStderr(error.message);
69
+ emitClose(null);
70
+ });
71
+
72
+ return {
73
+ send(data) {
74
+ try {
75
+ child.stdin?.write(data);
76
+ } catch {
77
+ /* peer gone — the close handler rejects everything pending */
78
+ }
79
+ },
80
+ onMessage(handler) {
81
+ messageHandlers.push(handler);
82
+ },
83
+ onClose(handler) {
84
+ closeHandlers.push(handler);
85
+ },
86
+ kill() {
87
+ child.kill("SIGTERM");
88
+ // `child.killed` flips the instant SIGTERM is *sent*, so escalate on
89
+ // whether the process actually exited.
90
+ const timer = setTimeout(() => {
91
+ if (!settled) child.kill("SIGKILL");
92
+ }, SIGKILL_GRACE_MS);
93
+ timer.unref?.();
94
+ },
95
+ killNow() {
96
+ try {
97
+ child.kill("SIGKILL");
98
+ } catch {
99
+ /* already gone */
100
+ }
101
+ },
102
+ };
103
+ }
104
+
105
+ export interface DocumentState {
106
+ version: number;
107
+ text: string;
108
+ }
109
+
110
+ export type DocumentSyncPlan = { action: "none" } | { action: "open" | "change"; version: number };
111
+
112
+ /** didOpen at v1, didChange at v+1, nothing when the buffer is unchanged. */
113
+ export function planDocumentSync(state: DocumentState | undefined, text: string): DocumentSyncPlan {
114
+ if (!state) return { action: "open", version: 1 };
115
+ if (state.text === text) return { action: "none" };
116
+ return { action: "change", version: state.version + 1 };
117
+ }
118
+
119
+ /** Reject when `signal` aborts, leaving `promise` running (a shared warmup must survive one caller leaving). */
120
+ export function abortable<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
121
+ if (!signal) return promise;
122
+ if (signal.aborted) return Promise.reject(new Error("aborted"));
123
+ return new Promise<T>((resolve, reject) => {
124
+ const onAbort = (): void => reject(new Error("aborted"));
125
+ signal.addEventListener("abort", onAbort, { once: true });
126
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
127
+ });
128
+ }
129
+
130
+ function lastLine(text: string): string {
131
+ const lines = text
132
+ .split("\n")
133
+ .map((line) => line.trim())
134
+ .filter(Boolean);
135
+ return lines.length > 0 ? lines[lines.length - 1] : "";
136
+ }
137
+
138
+ interface Pending {
139
+ resolve(value: unknown): void;
140
+ reject(error: Error): void;
141
+ settle(): void;
142
+ }
143
+
144
+ interface DiagnosticsEntry {
145
+ generation: number;
146
+ items: LspDiagnostic[];
147
+ }
148
+
149
+ interface DiagnosticsWaiter {
150
+ uri: string;
151
+ minGeneration: number;
152
+ deliver(items: LspDiagnostic[] | undefined): void;
153
+ }
154
+
155
+ export interface LspClientOptions {
156
+ requestTimeoutMs: number;
157
+ warmupTimeoutMs: number;
158
+ }
159
+
160
+ export class LspClient {
161
+ private nextId = 1;
162
+ private readonly pending = new Map<number, Pending>();
163
+ private readonly documents = new Map<string, DocumentState>();
164
+ private readonly diagnostics = new Map<string, DiagnosticsEntry>();
165
+ private diagnosticsWaiters: DiagnosticsWaiter[] = [];
166
+ private syncChain: Promise<void> = Promise.resolve();
167
+ private initializePromise?: Promise<void>;
168
+ private generation = 0;
169
+ private warmedUp = false;
170
+ private disposed = false;
171
+ private closeInfo?: TransportClose;
172
+
173
+ constructor(
174
+ readonly root: string,
175
+ private readonly transport: LspTransport,
176
+ private readonly options: LspClientOptions,
177
+ ) {
178
+ transport.onMessage((message) => this.handleMessage(message));
179
+ transport.onClose((info) => this.handleClose(info));
180
+ }
181
+
182
+ get dead(): boolean {
183
+ return this.closeInfo !== undefined || this.disposed;
184
+ }
185
+
186
+ /** True while any request or diagnostics wait is in flight — the pool must not idle-dispose a busy client. */
187
+ get busy(): boolean {
188
+ return this.pending.size > 0 || this.diagnosticsWaiters.length > 0;
189
+ }
190
+
191
+ /** Shared across callers and never cancelled by one of them leaving: a rejected handshake poisons the pool entry. */
192
+ initialize(): Promise<void> {
193
+ if (!this.initializePromise) this.initializePromise = this.performInitialize();
194
+ return this.initializePromise;
195
+ }
196
+
197
+ private async performInitialize(): Promise<void> {
198
+ await this.request(
199
+ "initialize",
200
+ {
201
+ processId: process.pid,
202
+ rootUri: pathToUri(this.root),
203
+ rootPath: this.root,
204
+ workspaceFolders: [{ uri: pathToUri(this.root), name: path.basename(this.root) }],
205
+ capabilities: {
206
+ textDocument: {
207
+ synchronization: { didSave: false, dynamicRegistration: false },
208
+ definition: { linkSupport: true },
209
+ references: {},
210
+ hover: { contentFormat: ["markdown", "plaintext"] },
211
+ documentSymbol: { hierarchicalDocumentSymbolSupport: true },
212
+ publishDiagnostics: { relatedInformation: false },
213
+ },
214
+ workspace: { workspaceFolders: true },
215
+ // Declaring workDoneProgress routes indexing chatter into $/progress
216
+ // notifications we drop, instead of showMessage traffic. We
217
+ // deliberately do NOT declare workspace.configuration — but we still
218
+ // answer it if the server asks anyway (see handleServerRequest).
219
+ window: { workDoneProgress: true },
220
+ },
221
+ },
222
+ { timeoutMs: this.options.warmupTimeoutMs },
223
+ );
224
+ this.notify("initialized", {});
225
+ }
226
+
227
+ /** Returns the sync action taken, so callers can tell a real didOpen/didChange from a no-op. */
228
+ async ensureDocument(uri: string, text: string, languageId: string): Promise<DocumentSyncPlan["action"]> {
229
+ // Tool executionMode is parallel and broker requests interleave with the
230
+ // main loop's, so version numbering is serialized on one chain.
231
+ const run = this.syncChain.then(() => {
232
+ const plan = planDocumentSync(this.documents.get(uri), text);
233
+ if (plan.action === "none") return plan.action;
234
+ if (plan.action === "open") {
235
+ this.notify("textDocument/didOpen", { textDocument: { uri, languageId, version: plan.version, text } });
236
+ } else {
237
+ this.notify("textDocument/didChange", {
238
+ textDocument: { uri, version: plan.version },
239
+ contentChanges: [{ text }],
240
+ });
241
+ }
242
+ this.documents.set(uri, { version: plan.version, text });
243
+ return plan.action;
244
+ });
245
+ this.syncChain = run.then(
246
+ () => undefined,
247
+ () => undefined,
248
+ );
249
+ return run;
250
+ }
251
+
252
+ diagnosticsGeneration(): number {
253
+ return this.generation;
254
+ }
255
+
256
+ async waitForDiagnostics(
257
+ uri: string,
258
+ sinceGeneration: number,
259
+ timeoutMs: number,
260
+ signal?: AbortSignal,
261
+ ): Promise<{ items: LspDiagnostic[]; fresh: boolean }> {
262
+ const current = this.diagnostics.get(uri);
263
+ if (current && current.generation > sinceGeneration) return { items: current.items, fresh: true };
264
+
265
+ const published = await new Promise<LspDiagnostic[] | undefined>((resolve) => {
266
+ let settled = false;
267
+ const waiter: DiagnosticsWaiter = {
268
+ uri,
269
+ minGeneration: sinceGeneration,
270
+ deliver: (items) => {
271
+ if (settled) return;
272
+ settled = true;
273
+ clearTimeout(timer);
274
+ signal?.removeEventListener("abort", onAbort);
275
+ this.diagnosticsWaiters = this.diagnosticsWaiters.filter((entry) => entry !== waiter);
276
+ resolve(items);
277
+ },
278
+ };
279
+ const onAbort = (): void => waiter.deliver(undefined);
280
+ const timer = setTimeout(() => waiter.deliver(undefined), timeoutMs);
281
+ signal?.addEventListener("abort", onAbort, { once: true });
282
+ this.diagnosticsWaiters.push(waiter);
283
+ });
284
+
285
+ if (published) return { items: published, fresh: true };
286
+ return { items: this.diagnostics.get(uri)?.items ?? [], fresh: false };
287
+ }
288
+
289
+ request(method: string, params: unknown, options: { signal?: AbortSignal; timeoutMs?: number } = {}): Promise<unknown> {
290
+ if (this.closeInfo) return Promise.reject(new Error(this.closeMessage()));
291
+ const id = this.nextId++;
292
+ // The first real request lands while the server is still indexing, so it
293
+ // inherits the warmup budget rather than the steady-state one.
294
+ const timeoutMs = options.timeoutMs ?? (this.warmedUp ? this.options.requestTimeoutMs : this.options.warmupTimeoutMs);
295
+
296
+ return new Promise<unknown>((resolve, reject) => {
297
+ let settled = false;
298
+ const cleanup = (): void => {
299
+ settled = true;
300
+ clearTimeout(timer);
301
+ options.signal?.removeEventListener("abort", onAbort);
302
+ this.pending.delete(id);
303
+ };
304
+ const entry: Pending = {
305
+ resolve: (value) => {
306
+ if (settled) return;
307
+ cleanup();
308
+ this.warmedUp = true;
309
+ resolve(value);
310
+ },
311
+ reject: (error) => {
312
+ if (settled) return;
313
+ cleanup();
314
+ reject(error);
315
+ },
316
+ settle: cleanup,
317
+ };
318
+ const onAbort = (): void => {
319
+ if (settled) return;
320
+ cleanup();
321
+ this.notify("$/cancelRequest", { id });
322
+ reject(new Error("aborted"));
323
+ };
324
+ const timer = setTimeout(() => {
325
+ if (settled) return;
326
+ cleanup();
327
+ // Keep the server alive: it is probably still indexing, and the next
328
+ // request against a warm index usually succeeds.
329
+ this.notify("$/cancelRequest", { id });
330
+ reject(new Error(`${method} timed out after ${Math.round(timeoutMs / 1000)}s (the language server may still be indexing — retry shortly)`));
331
+ }, timeoutMs);
332
+
333
+ options.signal?.addEventListener("abort", onAbort, { once: true });
334
+ this.pending.set(id, entry);
335
+ this.transport.send(encodeFrame({ jsonrpc: "2.0", id, method, params }));
336
+ });
337
+ }
338
+
339
+ notify(method: string, params: unknown): void {
340
+ if (this.closeInfo) return;
341
+ this.transport.send(encodeFrame({ jsonrpc: "2.0", method, params }));
342
+ }
343
+
344
+ async dispose(): Promise<void> {
345
+ if (this.disposed) return;
346
+ this.disposed = true;
347
+ try {
348
+ await this.request("shutdown", null, { timeoutMs: SHUTDOWN_BUDGET_MS });
349
+ this.notify("exit", undefined);
350
+ } catch {
351
+ /* an unresponsive server just gets killed */
352
+ }
353
+ this.transport.kill();
354
+ }
355
+
356
+ killNow(): void {
357
+ this.disposed = true;
358
+ this.transport.killNow();
359
+ }
360
+
361
+ private closeMessage(): string {
362
+ const detail = lastLine(this.closeInfo?.stderr ?? "");
363
+ const code = this.closeInfo?.code;
364
+ return `language server exited${code === null || code === undefined ? "" : ` (code ${code})`}${detail ? `: ${detail}` : ""}`;
365
+ }
366
+
367
+ private handleClose(info: TransportClose): void {
368
+ this.closeInfo = info;
369
+ const error = new Error(this.closeMessage());
370
+ for (const entry of [...this.pending.values()]) entry.reject(error);
371
+ this.pending.clear();
372
+ for (const waiter of [...this.diagnosticsWaiters]) waiter.deliver(undefined);
373
+ }
374
+
375
+ private handleMessage(message: JsonRpcMessage): void {
376
+ if (message.method !== undefined) {
377
+ if (message.id === undefined || message.id === null) this.handleNotification(message);
378
+ else this.handleServerRequest(message);
379
+ return;
380
+ }
381
+ if (typeof message.id !== "number") return;
382
+ const entry = this.pending.get(message.id);
383
+ if (!entry) return;
384
+ if (message.error) entry.reject(new Error(message.error.message || "language server error"));
385
+ else entry.resolve(message.result);
386
+ }
387
+
388
+ private handleNotification(message: JsonRpcMessage): void {
389
+ if (message.method !== "textDocument/publishDiagnostics") return;
390
+ const params = message.params as { uri?: string; diagnostics?: LspDiagnostic[] } | undefined;
391
+ if (!params?.uri) return;
392
+ this.generation += 1;
393
+ const entry: DiagnosticsEntry = { generation: this.generation, items: params.diagnostics ?? [] };
394
+ this.diagnostics.set(params.uri, entry);
395
+ for (const waiter of [...this.diagnosticsWaiters]) {
396
+ if (waiter.uri === params.uri && entry.generation > waiter.minGeneration) waiter.deliver(entry.items);
397
+ }
398
+ }
399
+
400
+ /**
401
+ * Every server request gets an answer. A server left waiting on a reply it
402
+ * asked for will stall the whole session, so unknown methods are refused
403
+ * explicitly rather than ignored.
404
+ */
405
+ private handleServerRequest(message: JsonRpcMessage): void {
406
+ const reply = (result: unknown): void =>
407
+ this.transport.send(encodeFrame({ jsonrpc: "2.0", id: message.id, result }));
408
+
409
+ switch (message.method) {
410
+ case "workspace/configuration": {
411
+ const items = (message.params as { items?: unknown[] } | undefined)?.items ?? [];
412
+ reply(items.map(() => null));
413
+ return;
414
+ }
415
+ case "client/registerCapability":
416
+ case "client/unregisterCapability":
417
+ case "window/workDoneProgress/create":
418
+ case "window/showMessageRequest":
419
+ reply(null);
420
+ return;
421
+ case "workspace/applyEdit":
422
+ // This subsystem is read-only; refusing is the honest answer.
423
+ reply({ applied: false });
424
+ return;
425
+ default:
426
+ this.transport.send(
427
+ encodeFrame({
428
+ jsonrpc: "2.0",
429
+ id: message.id,
430
+ error: { code: METHOD_NOT_FOUND, message: `unsupported request: ${message.method}` },
431
+ }),
432
+ );
433
+ }
434
+ }
435
+ }
@@ -0,0 +1,230 @@
1
+ /**
2
+ * LSP result shapes to the text the model reads.
3
+ *
4
+ * Pure: the only filesystem touch (a source line for grep-style context) is an
5
+ * injected reader. Empty results are friendly text rather than errors, matching
6
+ * pi's own grep tool ("No matches found") — a model that reads "not found"
7
+ * moves on, a model that reads an error retries.
8
+ */
9
+
10
+ import * as fs from "node:fs";
11
+ import * as path from "node:path";
12
+ import { fromLspPosition, uriToPath, type LspPosition } from "./lsp-protocol.js";
13
+
14
+ const MAX_LINE_CHARS = 500;
15
+ const MAX_HOVER_CHARS = 8000;
16
+ const MAX_SYMBOLS = 200;
17
+ const MAX_DIAGNOSTICS = 50;
18
+
19
+ export interface LspRange {
20
+ start: LspPosition;
21
+ end: LspPosition;
22
+ }
23
+
24
+ export interface LspLocation {
25
+ uri: string;
26
+ range: LspRange;
27
+ }
28
+
29
+ export interface LspLocationLink {
30
+ targetUri: string;
31
+ targetRange: LspRange;
32
+ targetSelectionRange?: LspRange;
33
+ }
34
+
35
+ export interface NormalizedLocation {
36
+ path: string;
37
+ line: number;
38
+ column: number;
39
+ }
40
+
41
+ export interface LspDiagnostic {
42
+ range: LspRange;
43
+ severity?: number;
44
+ code?: string | number;
45
+ source?: string;
46
+ message: string;
47
+ }
48
+
49
+ interface LspDocumentSymbol {
50
+ name: string;
51
+ kind: number;
52
+ detail?: string;
53
+ range?: LspRange;
54
+ selectionRange?: LspRange;
55
+ children?: LspDocumentSymbol[];
56
+ }
57
+
58
+ interface LspSymbolInformation {
59
+ name: string;
60
+ kind: number;
61
+ containerName?: string;
62
+ location: LspLocation;
63
+ }
64
+
65
+ /** LSP 3.17 SymbolKind, 1-based. */
66
+ const SYMBOL_KINDS = [
67
+ "File", "Module", "Namespace", "Package", "Class", "Method", "Property", "Field", "Constructor",
68
+ "Enum", "Interface", "Function", "Variable", "Constant", "String", "Number", "Boolean", "Array",
69
+ "Object", "Key", "Null", "EnumMember", "Struct", "Event", "Operator", "TypeParameter",
70
+ ];
71
+
72
+ const SEVERITY_NAMES = ["error", "warning", "info", "hint"];
73
+
74
+ export type LineReader = (filePath: string, line: number) => string | undefined;
75
+
76
+ /** Memoized per call: a references result routinely hits the same file dozens of times. */
77
+ export function createLineReader(readFile: (p: string) => string = (p) => fs.readFileSync(p, "utf8")): LineReader {
78
+ const cache = new Map<string, string[] | undefined>();
79
+ return (filePath, line) => {
80
+ if (!cache.has(filePath)) {
81
+ try {
82
+ cache.set(filePath, readFile(filePath).split(/\r?\n/));
83
+ } catch {
84
+ cache.set(filePath, undefined);
85
+ }
86
+ }
87
+ return cache.get(filePath)?.[line - 1];
88
+ };
89
+ }
90
+
91
+ export function displayPath(target: string, cwd: string): string {
92
+ const relative = path.relative(cwd, target);
93
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) return target;
94
+ return relative;
95
+ }
96
+
97
+ function truncateLine(text: string): string {
98
+ const trimmed = text.trim();
99
+ return trimmed.length > MAX_LINE_CHARS ? `${trimmed.slice(0, MAX_LINE_CHARS)}... [truncated]` : trimmed;
100
+ }
101
+
102
+ function isRecord(value: unknown): value is Record<string, unknown> {
103
+ return typeof value === "object" && value !== null;
104
+ }
105
+
106
+ /** `Location | Location[] | LocationLink[] | null` collapsed to one 1-based shape. */
107
+ export function normalizeLocations(result: unknown): NormalizedLocation[] {
108
+ if (result === null || result === undefined) return [];
109
+ const items = Array.isArray(result) ? result : [result];
110
+ const out: NormalizedLocation[] = [];
111
+ for (const item of items) {
112
+ if (!isRecord(item)) continue;
113
+ // LocationLink points at targetSelectionRange (the name) rather than
114
+ // targetRange (the whole declaration body), which is what a reader wants.
115
+ const uri = typeof item.uri === "string" ? item.uri : typeof item.targetUri === "string" ? item.targetUri : undefined;
116
+ if (!uri) continue;
117
+ const range = (item.range ?? item.targetSelectionRange ?? item.targetRange) as LspRange | undefined;
118
+ const { line, column } = fromLspPosition(range?.start);
119
+ out.push({ path: uriToPath(uri), line, column });
120
+ }
121
+ return out;
122
+ }
123
+
124
+ export interface LocationListOptions {
125
+ cwd: string;
126
+ readLine: LineReader;
127
+ limit: number;
128
+ /** Plural noun for the header, e.g. "references". Omit for a bare list. */
129
+ label?: string;
130
+ }
131
+
132
+ export function formatLocations(locations: NormalizedLocation[], options: LocationListOptions): string {
133
+ const shown = locations.slice(0, Math.max(1, options.limit));
134
+ const lines = shown.map((location) => {
135
+ const source = options.readLine(location.path, location.line);
136
+ const suffix = source === undefined ? "" : ` ${truncateLine(source)}`;
137
+ return `${displayPath(location.path, options.cwd)}:${location.line}:${location.column}:${suffix}`;
138
+ });
139
+ if (!options.label) return lines.join("\n");
140
+ const header =
141
+ locations.length > shown.length
142
+ ? `${locations.length} ${options.label} (showing first ${shown.length})`
143
+ : `${locations.length} ${options.label}`;
144
+ return [header, ...lines].join("\n");
145
+ }
146
+
147
+ export function formatHover(result: unknown): string {
148
+ if (!isRecord(result)) return "";
149
+ const rendered = renderHoverContents(result.contents).trim();
150
+ return rendered.length > MAX_HOVER_CHARS ? `${rendered.slice(0, MAX_HOVER_CHARS)}\n... [truncated]` : rendered;
151
+ }
152
+
153
+ function renderHoverContents(contents: unknown): string {
154
+ if (typeof contents === "string") return contents;
155
+ if (Array.isArray(contents)) return contents.map(renderHoverContents).filter(Boolean).join("\n\n");
156
+ if (!isRecord(contents)) return "";
157
+ // MarkupContent
158
+ if (typeof contents.value === "string" && typeof contents.kind === "string") return contents.value;
159
+ // MarkedString: {language, value}
160
+ if (typeof contents.value === "string") {
161
+ const language = typeof contents.language === "string" ? contents.language : "";
162
+ return `\`\`\`${language}\n${contents.value}\n\`\`\``;
163
+ }
164
+ return "";
165
+ }
166
+
167
+ function symbolKindName(kind: number): string {
168
+ return SYMBOL_KINDS[kind - 1] ?? "Symbol";
169
+ }
170
+
171
+ export function formatSymbols(result: unknown, cwd: string): string {
172
+ if (!Array.isArray(result) || result.length === 0) return "";
173
+ const lines: string[] = [];
174
+ let remaining = MAX_SYMBOLS;
175
+
176
+ const walk = (symbols: LspDocumentSymbol[], depth: number): void => {
177
+ for (const symbol of symbols) {
178
+ if (remaining <= 0) return;
179
+ remaining -= 1;
180
+ const { line } = fromLspPosition((symbol.selectionRange ?? symbol.range)?.start);
181
+ const detail = symbol.detail ? ` ${symbol.detail}` : "";
182
+ lines.push(`${" ".repeat(depth)}${symbolKindName(symbol.kind)} ${symbol.name}${detail} :${line}`);
183
+ if (symbol.children?.length) walk(symbol.children, depth + 1);
184
+ }
185
+ };
186
+
187
+ const first = result[0] as Record<string, unknown>;
188
+ if (isRecord(first) && isRecord(first.location)) {
189
+ // Flat SymbolInformation[] — older servers, no hierarchy available.
190
+ for (const symbol of (result as LspSymbolInformation[]).slice(0, MAX_SYMBOLS)) {
191
+ const { line } = fromLspPosition(symbol.location?.range?.start);
192
+ const container = symbol.containerName ? ` (in ${symbol.containerName})` : "";
193
+ const file = displayPath(uriToPath(symbol.location?.uri ?? ""), cwd);
194
+ lines.push(`${symbolKindName(symbol.kind)} ${symbol.name}${container} ${file}:${line}`);
195
+ }
196
+ } else {
197
+ walk(result as LspDocumentSymbol[], 0);
198
+ }
199
+
200
+ const total = countSymbols(result as LspDocumentSymbol[]);
201
+ if (total > lines.length) lines.push(`... ${total - lines.length} more symbols`);
202
+ return lines.join("\n");
203
+ }
204
+
205
+ function countSymbols(symbols: LspDocumentSymbol[]): number {
206
+ let total = 0;
207
+ for (const symbol of symbols) {
208
+ total += 1 + (symbol.children ? countSymbols(symbol.children) : 0);
209
+ }
210
+ return total;
211
+ }
212
+
213
+ export function formatDiagnostics(diagnostics: LspDiagnostic[], filePath: string, cwd: string): string {
214
+ if (diagnostics.length === 0) return "";
215
+ const counts = [0, 0, 0, 0];
216
+ for (const diagnostic of diagnostics) counts[(diagnostic.severity ?? 1) - 1] += 1;
217
+ const summary = SEVERITY_NAMES.map((name, index) => (counts[index] > 0 ? `${counts[index]} ${name}${counts[index] === 1 ? "" : "s"}` : null))
218
+ .filter(Boolean)
219
+ .join(", ");
220
+
221
+ const file = displayPath(filePath, cwd);
222
+ const lines = diagnostics.slice(0, MAX_DIAGNOSTICS).map((diagnostic) => {
223
+ const { line, column } = fromLspPosition(diagnostic.range?.start);
224
+ const severity = SEVERITY_NAMES[(diagnostic.severity ?? 1) - 1] ?? "error";
225
+ const source = diagnostic.source ? ` [${diagnostic.source}]` : "";
226
+ return `${severity} ${file}:${line}:${column}: ${diagnostic.message.replace(/\s*\n\s*/g, " ")}${source}`;
227
+ });
228
+ if (diagnostics.length > lines.length) lines.push(`... ${diagnostics.length - lines.length} more`);
229
+ return [summary, ...lines].join("\n");
230
+ }