@hmharness/lsp 0.23.16

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,35 @@
1
+ /**
2
+ * @hmharness/lsp - LSP client over stdio
3
+ *
4
+ * Speaks the base protocol to ONE managed language-server process:
5
+ * initialize handshake -> requests (hover/definition/references/symbols)
6
+ * -> document sync notifications -> shutdown/exit. Diagnostics arrive as
7
+ * push notifications and land in the caller's callback (diagnostics-store
8
+ * behavior is the caller's; here we just route).
9
+ */
10
+ import type { ChildProcessWithoutNullStreams } from 'node:child_process';
11
+ import { type InitializeResult, type Diagnostic, type Hover, type Location, type DocumentSymbol, type Position, type TextDocumentIdentifier } from './protocol.js';
12
+ export interface LspClientOptions {
13
+ requestTimeoutMs?: number;
14
+ onDiagnostics?: (uri: string, diagnostics: Diagnostic[]) => void;
15
+ }
16
+ export declare class LspClient {
17
+ private proc;
18
+ private opts;
19
+ private seq;
20
+ private pending;
21
+ private decoder;
22
+ private serverInfo;
23
+ constructor(proc: ChildProcessWithoutNullStreams, opts?: LspClientOptions);
24
+ private handle;
25
+ request<T>(method: string, params?: unknown): Promise<T>;
26
+ notify(method: string, params?: unknown): void;
27
+ initialize(rootUri: string): Promise<InitializeResult>;
28
+ get info(): InitializeResult | null;
29
+ openDoc(uri: string, languageId: string, text: string): void;
30
+ hover(textDocument: TextDocumentIdentifier, position: Position): Promise<Hover | null>;
31
+ definition(textDocument: TextDocumentIdentifier, position: Position): Promise<Location | Location[] | null>;
32
+ references(textDocument: TextDocumentIdentifier, position: Position, includeDeclaration?: boolean): Promise<Location[]>;
33
+ documentSymbols(textDocument: TextDocumentIdentifier): Promise<DocumentSymbol[]>;
34
+ shutdown(): Promise<void>;
35
+ }
package/dist/client.js ADDED
@@ -0,0 +1,99 @@
1
+ import { encodeMessage, MessageDecoder, } from "./protocol.js";
2
+ export class LspClient {
3
+ proc;
4
+ opts;
5
+ seq = 0;
6
+ pending = new Map();
7
+ decoder = new MessageDecoder();
8
+ serverInfo = null;
9
+ constructor(proc, opts = {}) {
10
+ this.proc = proc;
11
+ this.opts = opts;
12
+ proc.stdout.on('data', (chunk) => {
13
+ for (const msg of this.decoder.push(chunk))
14
+ this.handle(msg);
15
+ });
16
+ proc.on('exit', () => {
17
+ for (const [, p] of this.pending) {
18
+ clearTimeout(p.timer);
19
+ p.reject(new Error('server exited'));
20
+ }
21
+ this.pending.clear();
22
+ });
23
+ }
24
+ handle(msg) {
25
+ if (msg.method === 'textDocument/publishDiagnostics') {
26
+ const p = msg.params;
27
+ this.opts.onDiagnostics?.(p.uri, p.diagnostics ?? []);
28
+ return;
29
+ }
30
+ if (typeof msg.id === 'number' && ('result' in msg || 'error' in msg)) {
31
+ const p = this.pending.get(msg.id);
32
+ if (!p)
33
+ return;
34
+ this.pending.delete(msg.id);
35
+ clearTimeout(p.timer);
36
+ const resp = msg;
37
+ if (resp.error)
38
+ p.reject(new Error(`LSP ${resp.error.code}: ${resp.error.message}`));
39
+ else
40
+ p.resolve(resp.result);
41
+ }
42
+ // window/logMessage etc: intentionally ignored (noise for the agent)
43
+ }
44
+ request(method, params) {
45
+ const id = ++this.seq;
46
+ return new Promise((resolve, reject) => {
47
+ const timer = setTimeout(() => {
48
+ this.pending.delete(id);
49
+ reject(new Error(`LSP request ${method} timed out`));
50
+ }, this.opts.requestTimeoutMs ?? 20_000);
51
+ this.pending.set(id, { resolve: resolve, reject, timer });
52
+ this.proc.stdin.write(encodeMessage({ jsonrpc: '2.0', id, method, params }));
53
+ });
54
+ }
55
+ notify(method, params) {
56
+ this.proc.stdin.write(encodeMessage({ jsonrpc: '2.0', method, params }));
57
+ }
58
+ async initialize(rootUri) {
59
+ const params = {
60
+ processId: process.pid,
61
+ rootUri,
62
+ workspaceFolders: [{ name: 'workspace', uri: rootUri }],
63
+ capabilities: { textDocument: { hover: {}, definition: {}, references: {}, documentSymbol: {}, publishDiagnostics: {} } },
64
+ };
65
+ const result = await this.request('initialize', params);
66
+ this.serverInfo = result;
67
+ this.notify('initialized', {});
68
+ return result;
69
+ }
70
+ get info() {
71
+ return this.serverInfo;
72
+ }
73
+ /* ---------------- document sync (minimal: open + full change) ---------------- */
74
+ openDoc(uri, languageId, text) {
75
+ const params = { textDocument: { uri, languageId, version: 1, text } };
76
+ this.notify('textDocument/didOpen', params);
77
+ }
78
+ /* ---------------- Tier-0 requests ---------------- */
79
+ hover(textDocument, position) {
80
+ return this.request('textDocument/hover', { textDocument, position });
81
+ }
82
+ definition(textDocument, position) {
83
+ return this.request('textDocument/definition', { textDocument, position });
84
+ }
85
+ references(textDocument, position, includeDeclaration = false) {
86
+ const params = { textDocument, position, context: { includeDeclaration } };
87
+ return this.request('textDocument/references', params);
88
+ }
89
+ documentSymbols(textDocument) {
90
+ return this.request('textDocument/documentSymbol', { textDocument });
91
+ }
92
+ async shutdown() {
93
+ try {
94
+ await this.request('shutdown');
95
+ this.notify('exit');
96
+ }
97
+ catch { /* best effort */ }
98
+ }
99
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @hmharness/lsp - LSP Client/Manager for agent code intelligence
3
+ *
4
+ * Client ONLY (master prompt rule): we drive external language servers
5
+ * over stdio (LSP 3.18 subset), never implement one. Security walls live
6
+ * in process-manager (workspace-bound cwd, scrubbed env, restart caps,
7
+ * timeouts). Tier-0 read-only tools in tools.ts; guarded rename/code
8
+ * actions are Tier-3 and NOT implemented here.
9
+ */
10
+ export * from './protocol.js';
11
+ export { ProcessManager, scrubEnv, fromPath, type ServerSpec, type ManagedServerOptions } from './process-manager.js';
12
+ export { LspClient, type LspClientOptions } from './client.js';
13
+ export { discoverServers, serverForFile, fileToUri, type DiscoveredServer } from './registry.js';
14
+ export { lspTools, shutdownLsp, diagnosticsSummary, type LspToolContext } from './tools.js';
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @hmharness/lsp - LSP Client/Manager for agent code intelligence
3
+ *
4
+ * Client ONLY (master prompt rule): we drive external language servers
5
+ * over stdio (LSP 3.18 subset), never implement one. Security walls live
6
+ * in process-manager (workspace-bound cwd, scrubbed env, restart caps,
7
+ * timeouts). Tier-0 read-only tools in tools.ts; guarded rename/code
8
+ * actions are Tier-3 and NOT implemented here.
9
+ */
10
+ export * from "./protocol.js";
11
+ export { ProcessManager, scrubEnv, fromPath } from "./process-manager.js";
12
+ export { LspClient } from "./client.js";
13
+ export { discoverServers, serverForFile, fileToUri } from "./registry.js";
14
+ export { lspTools, shutdownLsp, diagnosticsSummary } from "./tools.js";
@@ -0,0 +1,61 @@
1
+ /**
2
+ * @hmharness/lsp - process manager (master prompt security rules)
3
+ *
4
+ * Owns language-server child processes with the hard walls from the LSP
5
+ * 专项方案 (03):
6
+ * - cwd is BOUND to the workspace root (a server cannot wander)
7
+ * - environment is an ALLOWLIST (secret env vars never inherit)
8
+ * - crash restart has a cap + exponential backoff (a flapping server
9
+ * must not become a fork bomb)
10
+ * - every request has a timeout and can be cancelled
11
+ * - the server's identity (command/version) is recorded for audit
12
+ */
13
+ import { type ChildProcessWithoutNullStreams } from 'node:child_process';
14
+ export interface ServerSpec {
15
+ /** server id, e.g. 'typescript' | 'pyright' | 'rust-analyzer' */
16
+ id: string;
17
+ /** executable + args exactly as discovered (no auto-download here) */
18
+ command: string;
19
+ args: string[];
20
+ /** provenance recorded for audit: where this command came from */
21
+ source: 'PATH' | 'explicit';
22
+ }
23
+ export interface ManagedServerOptions {
24
+ /** secret-free env allowlist passed to the server (default: PATH/SYSTEMROOT/LANG only) */
25
+ envAllowlist?: string[];
26
+ maxRestarts?: number;
27
+ requestTimeoutMs?: number;
28
+ }
29
+ /** Environment scrub: language servers do NOT need API keys to index code.
30
+ * Default allowlist keeps PATH working on Windows without inheriting
31
+ * provider tokens or user secrets. */
32
+ export declare function scrubEnv(extraAllow?: string[]): NodeJS.ProcessEnv;
33
+ export declare class ProcessManager {
34
+ readonly spec: ServerSpec;
35
+ private cwd;
36
+ private opts;
37
+ private proc;
38
+ /** total spawns; spawns beyond the first are restarts (exit clears this.proc,
39
+ * so counting there would miss exactly the flapping case) */
40
+ private spawns;
41
+ readonly startedAt: string | null;
42
+ lastExit: {
43
+ code: number | null;
44
+ signal: NodeJS.Signals | null;
45
+ at: string;
46
+ } | null;
47
+ constructor(spec: ServerSpec, cwd: string, opts?: ManagedServerOptions);
48
+ get restartCount(): number;
49
+ get running(): boolean;
50
+ /** Spawn (or respawn after crash, up to the cap). Resolves with the
51
+ * child's stdio streams; rejects when the restart budget is spent. */
52
+ start(): ChildProcessWithoutNullStreams;
53
+ /** Graceful stop, then hard kill. Always resolves. */
54
+ stop(): Promise<void>;
55
+ /** Synchronous last-resort kill (process 'exit' hook: async cleanup will
56
+ * not run there). Never spawns; kills the live child if any. */
57
+ killSync(): void;
58
+ }
59
+ /** Discover a server binary from PATH (explicit, never auto-downloaded —
60
+ * 03 方案: 自动下载供应链风险,来源白名单+hash 是后续 Capability OS 的事). */
61
+ export declare function fromPath(id: string, command: string, args: string[]): ServerSpec | null;
@@ -0,0 +1,114 @@
1
+ /**
2
+ * @hmharness/lsp - process manager (master prompt security rules)
3
+ *
4
+ * Owns language-server child processes with the hard walls from the LSP
5
+ * 专项方案 (03):
6
+ * - cwd is BOUND to the workspace root (a server cannot wander)
7
+ * - environment is an ALLOWLIST (secret env vars never inherit)
8
+ * - crash restart has a cap + exponential backoff (a flapping server
9
+ * must not become a fork bomb)
10
+ * - every request has a timeout and can be cancelled
11
+ * - the server's identity (command/version) is recorded for audit
12
+ */
13
+ import { spawn } from 'node:child_process';
14
+ /** Environment scrub: language servers do NOT need API keys to index code.
15
+ * Default allowlist keeps PATH working on Windows without inheriting
16
+ * provider tokens or user secrets. */
17
+ export function scrubEnv(extraAllow = []) {
18
+ const allow = new Set(['PATH', 'Path', 'SYSTEMROOT', 'SystemRoot', 'TEMP', 'TMP', 'LANG', 'HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'PROGRAMFILES', ...extraAllow]);
19
+ const out = {};
20
+ for (const [k, v] of Object.entries(process.env)) {
21
+ if (v !== undefined && allow.has(k.toUpperCase()) === false && !allow.has(k))
22
+ continue;
23
+ if (v !== undefined)
24
+ out[k] = v;
25
+ }
26
+ return out;
27
+ }
28
+ export class ProcessManager {
29
+ spec;
30
+ cwd;
31
+ opts;
32
+ proc = null;
33
+ /** total spawns; spawns beyond the first are restarts (exit clears this.proc,
34
+ * so counting there would miss exactly the flapping case) */
35
+ spawns = 0;
36
+ startedAt = null;
37
+ lastExit = null;
38
+ constructor(spec, cwd, opts = {}) {
39
+ this.spec = spec;
40
+ this.cwd = cwd;
41
+ this.opts = opts;
42
+ }
43
+ get restartCount() {
44
+ return Math.max(0, this.spawns - 1);
45
+ }
46
+ get running() {
47
+ return this.proc !== null && this.proc.exitCode === null && !this.proc.killed;
48
+ }
49
+ /** Spawn (or respawn after crash, up to the cap). Resolves with the
50
+ * child's stdio streams; rejects when the restart budget is spent. */
51
+ start() {
52
+ if (this.running && this.proc)
53
+ return this.proc;
54
+ const max = this.opts.maxRestarts ?? 3;
55
+ // allowed total spawns = the initial one + maxRestarts
56
+ if (this.spawns >= 1 + max) {
57
+ throw new Error(`server ${this.spec.id} exceeded restart budget (${this.restartCount} restarts >= ${max}) — refusing to flap`);
58
+ }
59
+ this.spawns += 1;
60
+ const proc = spawn(this.spec.command, this.spec.args, {
61
+ cwd: this.cwd, // bound to the workspace (03 方案: workspace 外访问)
62
+ env: scrubEnv(),
63
+ stdio: ['pipe', 'pipe', 'pipe'],
64
+ windowsHide: true,
65
+ });
66
+ proc.on('exit', (code, signal) => {
67
+ this.lastExit = { code, signal, at: new Date().toISOString() };
68
+ if (this.proc === proc)
69
+ this.proc = null;
70
+ });
71
+ this.proc = proc;
72
+ return proc;
73
+ }
74
+ /** Graceful stop, then hard kill. Always resolves. */
75
+ async stop() {
76
+ const proc = this.proc;
77
+ if (!proc)
78
+ return;
79
+ this.proc = null;
80
+ await new Promise((resolve) => {
81
+ const killTimer = setTimeout(() => { try {
82
+ proc.kill('SIGKILL');
83
+ }
84
+ catch { /* gone */ } }, 3_000);
85
+ proc.once('exit', () => { clearTimeout(killTimer); resolve(); });
86
+ try {
87
+ proc.kill();
88
+ }
89
+ catch {
90
+ clearTimeout(killTimer);
91
+ resolve();
92
+ }
93
+ });
94
+ }
95
+ /** Synchronous last-resort kill (process 'exit' hook: async cleanup will
96
+ * not run there). Never spawns; kills the live child if any. */
97
+ killSync() {
98
+ const proc = this.proc;
99
+ this.proc = null;
100
+ if (proc) {
101
+ try {
102
+ proc.kill('SIGKILL');
103
+ }
104
+ catch { /* gone */ }
105
+ }
106
+ }
107
+ }
108
+ /** Discover a server binary from PATH (explicit, never auto-downloaded —
109
+ * 03 方案: 自动下载供应链风险,来源白名单+hash 是后续 Capability OS 的事). */
110
+ export function fromPath(id, command, args) {
111
+ // PATH lookup without spawning: `where` on win, `which` elsewhere — cheap
112
+ // probe done by the caller; here we just mark provenance
113
+ return { id, command, args, source: 'PATH' };
114
+ }
@@ -0,0 +1,116 @@
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
+ export interface JsonRpcRequest {
10
+ jsonrpc: '2.0';
11
+ id: number;
12
+ method: string;
13
+ params?: unknown;
14
+ }
15
+ export interface JsonRpcNotification {
16
+ jsonrpc: '2.0';
17
+ method: string;
18
+ params?: unknown;
19
+ }
20
+ export interface JsonRpcResponse {
21
+ jsonrpc: '2.0';
22
+ id: number;
23
+ result?: unknown;
24
+ error?: {
25
+ code: number;
26
+ message: string;
27
+ data?: unknown;
28
+ };
29
+ }
30
+ /** `Content-Length: N\r\n\r\n<payload>` framing (LSP base protocol). */
31
+ export declare function encodeMessage(obj: unknown): Buffer;
32
+ /** Incremental frame decoder: feed stdout chunks, get parsed messages. */
33
+ export declare class MessageDecoder {
34
+ private buf;
35
+ push(chunk: Buffer): unknown[];
36
+ }
37
+ export interface InitializeParams {
38
+ processId: number | null;
39
+ rootUri: string | null;
40
+ workspaceFolders: Array<{
41
+ name: string;
42
+ uri: string;
43
+ }> | null;
44
+ capabilities: Record<string, unknown>;
45
+ }
46
+ export interface InitializeResult {
47
+ capabilities: Record<string, unknown>;
48
+ serverInfo?: {
49
+ name?: string;
50
+ version?: string;
51
+ };
52
+ }
53
+ export interface Position {
54
+ line: number;
55
+ character: number;
56
+ }
57
+ export interface Range {
58
+ start: Position;
59
+ end: Position;
60
+ }
61
+ export interface Location {
62
+ uri: string;
63
+ range: Range;
64
+ }
65
+ export interface TextDocumentIdentifier {
66
+ uri: string;
67
+ }
68
+ export interface VersionedTextDocumentIdentifier {
69
+ uri: string;
70
+ version: number;
71
+ }
72
+ export interface DidOpenParams {
73
+ textDocument: {
74
+ uri: string;
75
+ languageId: string;
76
+ version: number;
77
+ text: string;
78
+ };
79
+ }
80
+ export interface DidChangeParams {
81
+ textDocument: VersionedTextDocumentIdentifier;
82
+ contentChanges: Array<{
83
+ range?: Range;
84
+ text: string;
85
+ }>;
86
+ }
87
+ export interface Diagnostic {
88
+ range: Range;
89
+ severity?: 1 | 2 | 3 | 4;
90
+ code?: number | string;
91
+ source?: string;
92
+ message: string;
93
+ }
94
+ export interface PublishDiagnosticsParams {
95
+ uri: string;
96
+ diagnostics: Diagnostic[];
97
+ }
98
+ export interface Hover {
99
+ contents: unknown;
100
+ range?: Range;
101
+ }
102
+ export interface DocumentSymbol {
103
+ name: string;
104
+ kind: number;
105
+ range: Range;
106
+ selectionRange?: Range;
107
+ children?: DocumentSymbol[];
108
+ }
109
+ export interface ReferenceParams {
110
+ textDocument: TextDocumentIdentifier;
111
+ position: Position;
112
+ context: {
113
+ includeDeclaration: boolean;
114
+ };
115
+ }
116
+ export declare const LSP_TIMEOUT_DEFAULT_MS = 20000;
@@ -0,0 +1,44 @@
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
+ /** `Content-Length: N\r\n\r\n<payload>` framing (LSP base protocol). */
10
+ export function encodeMessage(obj) {
11
+ const payload = Buffer.from(JSON.stringify(obj), 'utf8');
12
+ return Buffer.concat([Buffer.from(`Content-Length: ${payload.length}\r\n\r\n`, 'ascii'), payload]);
13
+ }
14
+ /** Incremental frame decoder: feed stdout chunks, get parsed messages. */
15
+ export class MessageDecoder {
16
+ buf = Buffer.alloc(0);
17
+ push(chunk) {
18
+ this.buf = Buffer.concat([this.buf, chunk]);
19
+ const out = [];
20
+ for (;;) {
21
+ const headerEnd = this.buf.indexOf('\r\n\r\n');
22
+ if (headerEnd < 0)
23
+ break;
24
+ const header = this.buf.subarray(0, headerEnd).toString('ascii');
25
+ const m = /Content-Length:\s*(\d+)/i.exec(header);
26
+ if (!m) {
27
+ this.buf = this.buf.subarray(headerEnd + 4);
28
+ continue;
29
+ }
30
+ const len = Number(m[1]);
31
+ const bodyStart = headerEnd + 4;
32
+ if (this.buf.length < bodyStart + len)
33
+ break; // partial body
34
+ const body = this.buf.subarray(bodyStart, bodyStart + len).toString('utf8');
35
+ this.buf = this.buf.subarray(bodyStart + len);
36
+ try {
37
+ out.push(JSON.parse(body));
38
+ }
39
+ catch { /* skip malformed frame */ }
40
+ }
41
+ return out;
42
+ }
43
+ }
44
+ export const LSP_TIMEOUT_DEFAULT_MS = 20_000;
@@ -0,0 +1,13 @@
1
+ import type { ServerSpec } from './process-manager.js';
2
+ export interface DiscoveredServer extends ServerSpec {
3
+ languages: string[];
4
+ official: boolean;
5
+ /** probe result: a shim whose toolchain lacks the component (e.g. rustup
6
+ * without rust-analyzer installed) fails --version and must not register */
7
+ healthy: boolean;
8
+ unhealthyReason?: string;
9
+ }
10
+ export declare function discoverServers(force?: boolean): DiscoveredServer[];
11
+ /** Pick the server responsible for a file uri/path by extension. */
12
+ export declare function serverForFile(servers: DiscoveredServer[], file: string): DiscoveredServer | null;
13
+ export declare function fileToUri(absPath: string): string;
@@ -0,0 +1,72 @@
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 and recorded with
6
+ * provenance — automatic downloads are explicitly NOT done here (supply
7
+ * chain; source allowlist + sha256 is the Capability OS layer's job).
8
+ * ArkTS: prefer official/DevEco-local servers when present; community
9
+ * servers are returned with an explicit `unofficial` flag.
10
+ */
11
+ import { spawnSync } from 'node:child_process';
12
+ const KNOWN = [
13
+ { id: 'typescript', command: 'typescript-language-server', args: ['--stdio'], languages: ['typescript', 'javascript'], official: true },
14
+ { id: 'pyright', command: 'pyright-langserver', args: ['--stdio'], languages: ['python'], official: true },
15
+ { id: 'rust-analyzer', command: 'rust-analyzer', args: [], languages: ['rust'], official: true },
16
+ { id: 'gopls', command: 'gopls', args: [], languages: ['go'], official: true },
17
+ { id: 'clangd', command: 'clangd', args: [], languages: ['c', 'cpp'], official: true },
18
+ // ArkTS: community fallback only — 03 方案: 官方/DevEco 本地服务优先,
19
+ // 社区 server 必须明确标注
20
+ { id: 'arkts-community', command: 'arkts-language-server', args: ['--stdio'], languages: ['arkts'], official: false },
21
+ ];
22
+ function which(cmd) {
23
+ const probe = process.platform === 'win32'
24
+ ? spawnSync('cmd.exe', ['/d', '/s', '/c', `where ${cmd}`], { encoding: 'utf8', timeout: 5_000, windowsHide: true })
25
+ : spawnSync('which', [cmd], { encoding: 'utf8', timeout: 5_000 });
26
+ if (probe.status !== 0)
27
+ return null;
28
+ const first = (probe.stdout || '').split('\n').map((l) => l.trim()).filter(Boolean)[0];
29
+ return first ?? null;
30
+ }
31
+ /** Cheap health probe: `--version` must exit 0 within 5s. A PATH shim whose
32
+ * toolchain lacks the component (rustup without rust-analyzer installed)
33
+ * fails here — better an absent tool than a dead one registered. */
34
+ function healthProbe(command, args) {
35
+ const r = spawnSync(command, [...args, '--version'], { encoding: 'utf8', timeout: 5_000, windowsHide: true });
36
+ if (r.status === 0)
37
+ return { healthy: true };
38
+ const tail = ((r.stderr || '') + (r.stdout || '')).trim().split('\n').filter(Boolean).slice(-1)[0] ?? '';
39
+ return { healthy: false, reason: `--version probe failed (exit ${r.status}): ${tail.slice(0, 120)}` };
40
+ }
41
+ /** Discover available first-batch servers on THIS machine (PATH only).
42
+ * Memoized — the registry is probed per tool assembly and per spawn.
43
+ * Health-probed: broken shims are returned with healthy=false so callers
44
+ * can skip registering them (discovery stays honest about what exists). */
45
+ let discoveryCache = null;
46
+ export function discoverServers(force = false) {
47
+ if (!force && discoveryCache)
48
+ return discoveryCache;
49
+ const out = [];
50
+ for (const k of KNOWN) {
51
+ const path = which(k.command);
52
+ if (!path)
53
+ continue;
54
+ const probe = k.id === 'arkts-community' ? { healthy: true } : healthProbe(path, k.args);
55
+ out.push({ id: k.id, command: path, args: k.args, source: 'PATH', languages: k.languages, official: k.official !== false, healthy: probe.healthy, unhealthyReason: probe.reason });
56
+ }
57
+ discoveryCache = out;
58
+ return out;
59
+ }
60
+ /** Pick the server responsible for a file uri/path by extension. */
61
+ export function serverForFile(servers, file) {
62
+ const ext = file.slice(file.lastIndexOf('.') + 1).toLowerCase();
63
+ const langByExt = { 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' };
64
+ const lang = langByExt[ext];
65
+ if (!lang)
66
+ return null;
67
+ return servers.find((s) => s.languages.includes(lang)) ?? null;
68
+ }
69
+ export function fileToUri(absPath) {
70
+ const norm = absPath.replace(/\\/g, '/');
71
+ return 'file:///' + norm.replace(/^([A-Za-z]):/, '$1:').replace(/^\/+/, '');
72
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @hmharness/lsp - agent tools (Tier 0, read-only)
3
+ *
4
+ * The agent-facing surface per the 03 方案 Tier-0 list: diagnostics,
5
+ * hover, definition, references, symbols. All read-only, all results
6
+ * marked `source: lsp` — LSP diagnostics are FEEDBACK, never build/test
7
+ * proof (master prompt prohibition).
8
+ */
9
+ import type { Tool } from '@hmharness/kernel';
10
+ import type { Diagnostic } from './protocol.js';
11
+ export interface LspToolContext {
12
+ workspaceRoot: string;
13
+ }
14
+ /** Stop every client this module started (TUI/CLI shutdown path). */
15
+ export declare function shutdownLsp(): Promise<void>;
16
+ export declare function diagnosticsSummary(diags: Diagnostic[]): string;
17
+ export declare function lspTools(ctx: LspToolContext): Tool[];