@hmharness/lsp 0.23.24 → 0.23.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/protocol.ts CHANGED
@@ -1,113 +1,113 @@
1
- /**
2
- * @hmharness/lsp - protocol (LSP 3.18 subset + JSON-RPC framing)
3
- *
4
- * Client-side types ONLY (master prompt: we implement the Client/Manager,
5
- * never a language server). The subset below covers the Tier-0/Tier-1
6
- * agent surface: lifecycle, diagnostics, hover, definition, references,
7
- * document symbols, plus the framing primitives every message rides on.
8
- */
9
-
10
- /* ---------------- JSON-RPC / framing ---------------- */
11
-
12
- export interface JsonRpcRequest {
13
- jsonrpc: '2.0';
14
- id: number;
15
- method: string;
16
- params?: unknown;
17
- }
18
- export interface JsonRpcNotification {
19
- jsonrpc: '2.0';
20
- method: string;
21
- params?: unknown;
22
- }
23
- export interface JsonRpcResponse {
24
- jsonrpc: '2.0';
25
- id: number;
26
- result?: unknown;
27
- error?: { code: number; message: string; data?: unknown };
28
- }
29
-
30
- /** `Content-Length: N\r\n\r\n<payload>` framing (LSP base protocol). */
31
- export function encodeMessage(obj: unknown): Buffer {
32
- const payload = Buffer.from(JSON.stringify(obj), 'utf8');
33
- return Buffer.concat([Buffer.from(`Content-Length: ${payload.length}\r\n\r\n`, 'ascii'), payload]);
34
- }
35
-
36
- /** Incremental frame decoder: feed stdout chunks, get parsed messages. */
37
- export class MessageDecoder {
38
- private buf = Buffer.alloc(0);
39
- push(chunk: Buffer): unknown[] {
40
- this.buf = Buffer.concat([this.buf, chunk]);
41
- const out: unknown[] = [];
42
- for (;;) {
43
- const headerEnd = this.buf.indexOf('\r\n\r\n');
44
- if (headerEnd < 0) break;
45
- const header = this.buf.subarray(0, headerEnd).toString('ascii');
46
- const m = /Content-Length:\s*(\d+)/i.exec(header);
47
- if (!m) { this.buf = this.buf.subarray(headerEnd + 4); continue; }
48
- const len = Number(m[1]);
49
- const bodyStart = headerEnd + 4;
50
- if (this.buf.length < bodyStart + len) break; // partial body
51
- const body = this.buf.subarray(bodyStart, bodyStart + len).toString('utf8');
52
- this.buf = this.buf.subarray(bodyStart + len);
53
- try { out.push(JSON.parse(body)); } catch { /* skip malformed frame */ }
54
- }
55
- return out;
56
- }
57
- }
58
-
59
- /* ---------------- lifecycle ---------------- */
60
-
61
- export interface InitializeParams {
62
- processId: number | null;
63
- rootUri: string | null;
64
- workspaceFolders: Array<{ name: string; uri: string }> | null;
65
- capabilities: Record<string, unknown>;
66
- }
67
- export interface InitializeResult {
68
- capabilities: Record<string, unknown>;
69
- serverInfo?: { name?: string; version?: string };
70
- }
71
-
72
- /* ---------------- positions / documents ---------------- */
73
-
74
- export interface Position { line: number; character: number }
75
- export interface Range { start: Position; end: Position }
76
- export interface Location { uri: string; range: Range }
77
- export interface TextDocumentIdentifier { uri: string }
78
- export interface VersionedTextDocumentIdentifier { uri: string; version: number }
79
-
80
- export interface DidOpenParams {
81
- textDocument: { uri: string; languageId: string; version: number; text: string };
82
- }
83
- export interface DidChangeParams {
84
- textDocument: VersionedTextDocumentIdentifier;
85
- contentChanges: Array<{ range?: Range; text: string }>;
86
- }
87
-
88
- /* ---------------- Tier-0 results ---------------- */
89
-
90
- export interface Diagnostic {
91
- range: Range;
92
- severity?: 1 | 2 | 3 | 4; // Error | Warning | Information | Hint
93
- code?: number | string;
94
- source?: string;
95
- message: string;
96
- }
97
- export interface PublishDiagnosticsParams { uri: string; diagnostics: Diagnostic[] }
98
-
99
- export interface Hover { contents: unknown; range?: Range }
100
- export interface DocumentSymbol {
101
- name: string;
102
- kind: number;
103
- range: Range;
104
- selectionRange?: Range;
105
- children?: DocumentSymbol[];
106
- }
107
- export interface ReferenceParams {
108
- textDocument: TextDocumentIdentifier;
109
- position: Position;
110
- context: { includeDeclaration: boolean };
111
- }
112
-
113
- export const LSP_TIMEOUT_DEFAULT_MS = 20_000;
1
+ /**
2
+ * @hmharness/lsp - protocol (LSP 3.18 subset + JSON-RPC framing)
3
+ *
4
+ * Client-side types ONLY (master prompt: we implement the Client/Manager,
5
+ * never a language server). The subset below covers the Tier-0/Tier-1
6
+ * agent surface: lifecycle, diagnostics, hover, definition, references,
7
+ * document symbols, plus the framing primitives every message rides on.
8
+ */
9
+
10
+ /* ---------------- JSON-RPC / framing ---------------- */
11
+
12
+ export interface JsonRpcRequest {
13
+ jsonrpc: '2.0';
14
+ id: number;
15
+ method: string;
16
+ params?: unknown;
17
+ }
18
+ export interface JsonRpcNotification {
19
+ jsonrpc: '2.0';
20
+ method: string;
21
+ params?: unknown;
22
+ }
23
+ export interface JsonRpcResponse {
24
+ jsonrpc: '2.0';
25
+ id: number;
26
+ result?: unknown;
27
+ error?: { code: number; message: string; data?: unknown };
28
+ }
29
+
30
+ /** `Content-Length: N\r\n\r\n<payload>` framing (LSP base protocol). */
31
+ export function encodeMessage(obj: unknown): Buffer {
32
+ const payload = Buffer.from(JSON.stringify(obj), 'utf8');
33
+ return Buffer.concat([Buffer.from(`Content-Length: ${payload.length}\r\n\r\n`, 'ascii'), payload]);
34
+ }
35
+
36
+ /** Incremental frame decoder: feed stdout chunks, get parsed messages. */
37
+ export class MessageDecoder {
38
+ private buf = Buffer.alloc(0);
39
+ push(chunk: Buffer): unknown[] {
40
+ this.buf = Buffer.concat([this.buf, chunk]);
41
+ const out: unknown[] = [];
42
+ for (;;) {
43
+ const headerEnd = this.buf.indexOf('\r\n\r\n');
44
+ if (headerEnd < 0) break;
45
+ const header = this.buf.subarray(0, headerEnd).toString('ascii');
46
+ const m = /Content-Length:\s*(\d+)/i.exec(header);
47
+ if (!m) { this.buf = this.buf.subarray(headerEnd + 4); continue; }
48
+ const len = Number(m[1]);
49
+ const bodyStart = headerEnd + 4;
50
+ if (this.buf.length < bodyStart + len) break; // partial body
51
+ const body = this.buf.subarray(bodyStart, bodyStart + len).toString('utf8');
52
+ this.buf = this.buf.subarray(bodyStart + len);
53
+ try { out.push(JSON.parse(body)); } catch { /* skip malformed frame */ }
54
+ }
55
+ return out;
56
+ }
57
+ }
58
+
59
+ /* ---------------- lifecycle ---------------- */
60
+
61
+ export interface InitializeParams {
62
+ processId: number | null;
63
+ rootUri: string | null;
64
+ workspaceFolders: Array<{ name: string; uri: string }> | null;
65
+ capabilities: Record<string, unknown>;
66
+ }
67
+ export interface InitializeResult {
68
+ capabilities: Record<string, unknown>;
69
+ serverInfo?: { name?: string; version?: string };
70
+ }
71
+
72
+ /* ---------------- positions / documents ---------------- */
73
+
74
+ export interface Position { line: number; character: number }
75
+ export interface Range { start: Position; end: Position }
76
+ export interface Location { uri: string; range: Range }
77
+ export interface TextDocumentIdentifier { uri: string }
78
+ export interface VersionedTextDocumentIdentifier { uri: string; version: number }
79
+
80
+ export interface DidOpenParams {
81
+ textDocument: { uri: string; languageId: string; version: number; text: string };
82
+ }
83
+ export interface DidChangeParams {
84
+ textDocument: VersionedTextDocumentIdentifier;
85
+ contentChanges: Array<{ range?: Range; text: string }>;
86
+ }
87
+
88
+ /* ---------------- Tier-0 results ---------------- */
89
+
90
+ export interface Diagnostic {
91
+ range: Range;
92
+ severity?: 1 | 2 | 3 | 4; // Error | Warning | Information | Hint
93
+ code?: number | string;
94
+ source?: string;
95
+ message: string;
96
+ }
97
+ export interface PublishDiagnosticsParams { uri: string; diagnostics: Diagnostic[] }
98
+
99
+ export interface Hover { contents: unknown; range?: Range }
100
+ export interface DocumentSymbol {
101
+ name: string;
102
+ kind: number;
103
+ range: Range;
104
+ selectionRange?: Range;
105
+ children?: DocumentSymbol[];
106
+ }
107
+ export interface ReferenceParams {
108
+ textDocument: TextDocumentIdentifier;
109
+ position: Position;
110
+ context: { includeDeclaration: boolean };
111
+ }
112
+
113
+ export const LSP_TIMEOUT_DEFAULT_MS = 20_000;
package/src/registry.ts CHANGED
@@ -1,130 +1,130 @@
1
- /**
2
- * @hmharness/lsp - server registry + discovery
3
- *
4
- * First-batch servers per the 03 方案: TypeScript/JavaScript, Pyright,
5
- * rust-analyzer, gopls, clangd. Discovery is PATH-ONLY plus DEVECO-LOCAL
6
- * (the IDE ships a real clangd under tools/llvm/server/lsp — an official
7
- * source we prefer over community downloads). Automatic downloads are
8
- * explicitly NOT done here (supply chain; source allowlist + sha256 is the
9
- * Capability OS layer's job). ArkTS: prefer official/DevEco-local servers
10
- * when present; community servers are returned with an explicit
11
- * `unofficial` flag.
12
- */
13
- import { spawnSync } from 'node:child_process';
14
- import { existsSync } from 'node:fs';
15
- import type { ServerSpec } from './process-manager.ts';
16
-
17
- interface KnownServer {
18
- id: string;
19
- command: string;
20
- args: string[];
21
- /** languages this server indexes (used by tools to pick a server for a file) */
22
- languages: string[];
23
- official?: boolean; // false = community fallback (flagged in tool output)
24
- }
25
-
26
- const KNOWN: KnownServer[] = [
27
- { id: 'typescript', command: 'typescript-language-server', args: ['--stdio'], languages: ['typescript', 'javascript'], official: true },
28
- { id: 'pyright', command: 'pyright-langserver', args: ['--stdio'], languages: ['python'], official: true },
29
- { id: 'rust-analyzer', command: 'rust-analyzer', args: [], languages: ['rust'], official: true },
30
- { id: 'gopls', command: 'gopls', args: [], languages: ['go'], official: true },
31
- { id: 'clangd', command: 'clangd', args: [], languages: ['c', 'cpp'], official: true },
32
- // ArkTS: community fallback only — 03 方案: 官方/DevEco 本地服务优先,
33
- // 社区 server 必须明确标注
34
- { id: 'arkts-community', command: 'arkts-language-server', args: ['--stdio'], languages: ['arkts'], official: false },
35
- ];
36
-
37
- function which(cmd: string): string | null {
38
- const probe = process.platform === 'win32'
39
- ? spawnSync('cmd.exe', ['/d', '/s', '/c', `where ${cmd}`], { encoding: 'utf8', timeout: 5_000, windowsHide: true })
40
- : spawnSync('which', [cmd], { encoding: 'utf8', timeout: 5_000 });
41
- if (probe.status !== 0) return null;
42
- const first = (probe.stdout || '').split('\n').map((l) => l.trim()).filter(Boolean)[0];
43
- return first ?? null;
44
- }
45
-
46
- export interface DiscoveredServer extends ServerSpec {
47
- languages: string[];
48
- official: boolean;
49
- /** probe result: a shim whose toolchain lacks the component (e.g. rustup
50
- * without rust-analyzer installed) fails --version and must not register */
51
- healthy: boolean;
52
- unhealthyReason?: string;
53
- /** where this server came from: PATH | PATH-community | DevEco-local | DevEco-local-community */
54
- origin: string;
55
- }
56
-
57
- /** DevEco Studio install roots to scan for bundled (official) servers. */
58
- export const DEVECO_ROOTS = [
59
- 'C:/Program Files/Huawei/DevEco Studio',
60
- 'D:/Program Files/Huawei/DevEco Studio',
61
- process.env.LOCALAPPDATA ? process.env.LOCALAPPDATA + '/Huawei/DevEco Studio' : '',
62
- ].filter(Boolean);
63
-
64
- /** well-known bundled-server layouts inside a DevEco install (03 方案:
65
- * 优先发现 DevEco/SDK 本地服务,记录来源——绝不自动下载) */
66
- function devecoBundled(devecoRoots: string[]): Array<{ id: string; command: string; args: string[]; languages: string[]; official: boolean; origin: string }> {
67
- const out: Array<{ id: string; command: string; args: string[]; languages: string[]; official: boolean; origin: string }> = [];
68
- for (const root of devecoRoots) {
69
- // clangd ships with the IDE's native toolchain (versioned per release)
70
- const clangd = root + '/tools/llvm/server/lsp/win/clangd.exe';
71
- if (existsSync(clangd)) out.push({ id: 'clangd', command: clangd, args: [], languages: ['c', 'cpp'], official: true, origin: 'DevEco-local' });
72
- }
73
- return out;
74
- }
75
-
76
- /** Cheap health probe: `--version` must exit 0 within 5s. A PATH shim whose
77
- * toolchain lacks the component (rustup without rust-analyzer installed)
78
- * fails here — better an absent tool than a dead one registered. */
79
- function healthProbe(command: string, args: string[]): { healthy: boolean; reason?: string } {
80
- const r = spawnSync(command, [...args, '--version'], { encoding: 'utf8', timeout: 5_000, windowsHide: true });
81
- if (r.status === 0) return { healthy: true };
82
- const tail = ((r.stderr || '') + (r.stdout || '')).trim().split('\n').filter(Boolean).slice(-1)[0] ?? '';
83
- return { healthy: false, reason: `--version probe failed (exit ${r.status}): ${tail.slice(0, 120)}` };
84
- }
85
-
86
- /** Discover available servers on THIS machine (PATH + DevEco-local).
87
- * Memoized — the registry is probed per tool assembly and per spawn.
88
- * Health-probed: broken shims are returned with healthy=false so callers
89
- * can skip registering them (discovery stays honest about what exists). */
90
- let discoveryCache: DiscoveredServer[] | null = null;
91
- export function discoverServers(force = false, opts: { devecoRoots?: string[] } = {}): DiscoveredServer[] {
92
- if (!force && discoveryCache) return discoveryCache;
93
- const out: DiscoveredServer[] = [];
94
- const seen = new Map<string, DiscoveredServer>();
95
- const push = (id: string, command: string, args: string[], languages: string[], official: boolean, origin: string, probe: boolean) => {
96
- const h = probe ? healthProbe(command, args) : { healthy: true as const };
97
- const entry: DiscoveredServer = { id, command, args, source: origin.includes('DevEco') ? 'explicit' : 'PATH', languages, official, healthy: h.healthy, unhealthyReason: (h as { reason?: string }).reason, origin };
98
- // first (preferred) source wins per id: DevEco-local beats PATH beats community
99
- const existing = seen.get(id);
100
- if (!existing || (existing.origin.includes('community') && !origin.includes('community'))) {
101
- seen.set(id, entry);
102
- }
103
- };
104
- // PATH servers
105
- for (const k of KNOWN) {
106
- const path = which(k.command);
107
- if (!path) continue;
108
- push(k.id, path, k.args, k.languages, k.official !== false, k.official !== false ? 'PATH' : 'PATH-community', true);
109
- }
110
- // DevEco-local bundled servers (official, no download ever)
111
- for (const b of devecoBundled(opts.devecoRoots ?? DEVECO_ROOTS)) {
112
- push(b.id, b.command, b.args, b.languages, b.official, b.origin, true);
113
- }
114
- discoveryCache = [...seen.values()];
115
- return discoveryCache;
116
- }
117
-
118
- /** Pick the server responsible for a file uri/path by extension. */
119
- export function serverForFile(servers: DiscoveredServer[], file: string): DiscoveredServer | null {
120
- const ext = file.slice(file.lastIndexOf('.') + 1).toLowerCase();
121
- const langByExt: Record<string, string> = { ts: 'typescript', tsx: 'typescript', mts: 'typescript', cts: 'typescript', js: 'javascript', mjs: 'javascript', cjs: 'javascript', py: 'python', rs: 'rust', go: 'go', c: 'c', h: 'c', cpp: 'cpp', hpp: 'cpp', cc: 'cpp', ets: 'arkts' };
122
- const lang = langByExt[ext];
123
- if (!lang) return null;
124
- return servers.find((s) => s.languages.includes(lang)) ?? null;
125
- }
126
-
127
- export function fileToUri(absPath: string): string {
128
- const norm = absPath.replace(/\\/g, '/');
129
- return 'file:///' + norm.replace(/^([A-Za-z]):/, '$1:').replace(/^\/+/, '');
130
- }
1
+ /**
2
+ * @hmharness/lsp - server registry + discovery
3
+ *
4
+ * First-batch servers per the 03 方案: TypeScript/JavaScript, Pyright,
5
+ * rust-analyzer, gopls, clangd. Discovery is PATH-ONLY plus DEVECO-LOCAL
6
+ * (the IDE ships a real clangd under tools/llvm/server/lsp — an official
7
+ * source we prefer over community downloads). Automatic downloads are
8
+ * explicitly NOT done here (supply chain; source allowlist + sha256 is the
9
+ * Capability OS layer's job). ArkTS: prefer official/DevEco-local servers
10
+ * when present; community servers are returned with an explicit
11
+ * `unofficial` flag.
12
+ */
13
+ import { spawnSync } from 'node:child_process';
14
+ import { existsSync } from 'node:fs';
15
+ import type { ServerSpec } from './process-manager.ts';
16
+
17
+ interface KnownServer {
18
+ id: string;
19
+ command: string;
20
+ args: string[];
21
+ /** languages this server indexes (used by tools to pick a server for a file) */
22
+ languages: string[];
23
+ official?: boolean; // false = community fallback (flagged in tool output)
24
+ }
25
+
26
+ const KNOWN: KnownServer[] = [
27
+ { id: 'typescript', command: 'typescript-language-server', args: ['--stdio'], languages: ['typescript', 'javascript'], official: true },
28
+ { id: 'pyright', command: 'pyright-langserver', args: ['--stdio'], languages: ['python'], official: true },
29
+ { id: 'rust-analyzer', command: 'rust-analyzer', args: [], languages: ['rust'], official: true },
30
+ { id: 'gopls', command: 'gopls', args: [], languages: ['go'], official: true },
31
+ { id: 'clangd', command: 'clangd', args: [], languages: ['c', 'cpp'], official: true },
32
+ // ArkTS: community fallback only — 03 方案: 官方/DevEco 本地服务优先,
33
+ // 社区 server 必须明确标注
34
+ { id: 'arkts-community', command: 'arkts-language-server', args: ['--stdio'], languages: ['arkts'], official: false },
35
+ ];
36
+
37
+ function which(cmd: string): string | null {
38
+ const probe = process.platform === 'win32'
39
+ ? spawnSync('cmd.exe', ['/d', '/s', '/c', `where ${cmd}`], { encoding: 'utf8', timeout: 5_000, windowsHide: true })
40
+ : spawnSync('which', [cmd], { encoding: 'utf8', timeout: 5_000 });
41
+ if (probe.status !== 0) return null;
42
+ const first = (probe.stdout || '').split('\n').map((l) => l.trim()).filter(Boolean)[0];
43
+ return first ?? null;
44
+ }
45
+
46
+ export interface DiscoveredServer extends ServerSpec {
47
+ languages: string[];
48
+ official: boolean;
49
+ /** probe result: a shim whose toolchain lacks the component (e.g. rustup
50
+ * without rust-analyzer installed) fails --version and must not register */
51
+ healthy: boolean;
52
+ unhealthyReason?: string;
53
+ /** where this server came from: PATH | PATH-community | DevEco-local | DevEco-local-community */
54
+ origin: string;
55
+ }
56
+
57
+ /** DevEco Studio install roots to scan for bundled (official) servers. */
58
+ export const DEVECO_ROOTS = [
59
+ 'C:/Program Files/Huawei/DevEco Studio',
60
+ 'D:/Program Files/Huawei/DevEco Studio',
61
+ process.env.LOCALAPPDATA ? process.env.LOCALAPPDATA + '/Huawei/DevEco Studio' : '',
62
+ ].filter(Boolean);
63
+
64
+ /** well-known bundled-server layouts inside a DevEco install (03 方案:
65
+ * 优先发现 DevEco/SDK 本地服务,记录来源——绝不自动下载) */
66
+ function devecoBundled(devecoRoots: string[]): Array<{ id: string; command: string; args: string[]; languages: string[]; official: boolean; origin: string }> {
67
+ const out: Array<{ id: string; command: string; args: string[]; languages: string[]; official: boolean; origin: string }> = [];
68
+ for (const root of devecoRoots) {
69
+ // clangd ships with the IDE's native toolchain (versioned per release)
70
+ const clangd = root + '/tools/llvm/server/lsp/win/clangd.exe';
71
+ if (existsSync(clangd)) out.push({ id: 'clangd', command: clangd, args: [], languages: ['c', 'cpp'], official: true, origin: 'DevEco-local' });
72
+ }
73
+ return out;
74
+ }
75
+
76
+ /** Cheap health probe: `--version` must exit 0 within 5s. A PATH shim whose
77
+ * toolchain lacks the component (rustup without rust-analyzer installed)
78
+ * fails here — better an absent tool than a dead one registered. */
79
+ function healthProbe(command: string, args: string[]): { healthy: boolean; reason?: string } {
80
+ const r = spawnSync(command, [...args, '--version'], { encoding: 'utf8', timeout: 5_000, windowsHide: true });
81
+ if (r.status === 0) return { healthy: true };
82
+ const tail = ((r.stderr || '') + (r.stdout || '')).trim().split('\n').filter(Boolean).slice(-1)[0] ?? '';
83
+ return { healthy: false, reason: `--version probe failed (exit ${r.status}): ${tail.slice(0, 120)}` };
84
+ }
85
+
86
+ /** Discover available servers on THIS machine (PATH + DevEco-local).
87
+ * Memoized — the registry is probed per tool assembly and per spawn.
88
+ * Health-probed: broken shims are returned with healthy=false so callers
89
+ * can skip registering them (discovery stays honest about what exists). */
90
+ let discoveryCache: DiscoveredServer[] | null = null;
91
+ export function discoverServers(force = false, opts: { devecoRoots?: string[] } = {}): DiscoveredServer[] {
92
+ if (!force && discoveryCache) return discoveryCache;
93
+ const out: DiscoveredServer[] = [];
94
+ const seen = new Map<string, DiscoveredServer>();
95
+ const push = (id: string, command: string, args: string[], languages: string[], official: boolean, origin: string, probe: boolean) => {
96
+ const h = probe ? healthProbe(command, args) : { healthy: true as const };
97
+ const entry: DiscoveredServer = { id, command, args, source: origin.includes('DevEco') ? 'explicit' : 'PATH', languages, official, healthy: h.healthy, unhealthyReason: (h as { reason?: string }).reason, origin };
98
+ // first (preferred) source wins per id: DevEco-local beats PATH beats community
99
+ const existing = seen.get(id);
100
+ if (!existing || (existing.origin.includes('community') && !origin.includes('community'))) {
101
+ seen.set(id, entry);
102
+ }
103
+ };
104
+ // PATH servers
105
+ for (const k of KNOWN) {
106
+ const path = which(k.command);
107
+ if (!path) continue;
108
+ push(k.id, path, k.args, k.languages, k.official !== false, k.official !== false ? 'PATH' : 'PATH-community', true);
109
+ }
110
+ // DevEco-local bundled servers (official, no download ever)
111
+ for (const b of devecoBundled(opts.devecoRoots ?? DEVECO_ROOTS)) {
112
+ push(b.id, b.command, b.args, b.languages, b.official, b.origin, true);
113
+ }
114
+ discoveryCache = [...seen.values()];
115
+ return discoveryCache;
116
+ }
117
+
118
+ /** Pick the server responsible for a file uri/path by extension. */
119
+ export function serverForFile(servers: DiscoveredServer[], file: string): DiscoveredServer | null {
120
+ const ext = file.slice(file.lastIndexOf('.') + 1).toLowerCase();
121
+ const langByExt: Record<string, string> = { ts: 'typescript', tsx: 'typescript', mts: 'typescript', cts: 'typescript', js: 'javascript', mjs: 'javascript', cjs: 'javascript', py: 'python', rs: 'rust', go: 'go', c: 'c', h: 'c', cpp: 'cpp', hpp: 'cpp', cc: 'cpp', ets: 'arkts' };
122
+ const lang = langByExt[ext];
123
+ if (!lang) return null;
124
+ return servers.find((s) => s.languages.includes(lang)) ?? null;
125
+ }
126
+
127
+ export function fileToUri(absPath: string): string {
128
+ const norm = absPath.replace(/\\/g, '/');
129
+ return 'file:///' + norm.replace(/^([A-Za-z]):/, '$1:').replace(/^\/+/, '');
130
+ }