@hmharness/lsp 0.23.16 → 0.23.18
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/dist/client.d.ts +11 -0
- package/dist/client.js +14 -0
- package/dist/registry.d.ts +7 -1
- package/dist/registry.js +46 -11
- package/dist/tools.js +35 -0
- package/package.json +23 -23
- package/src/__tests__/deveco.test.ts +60 -0
- package/src/__tests__/fixtures/fake-server.cjs +89 -73
- package/src/__tests__/lsp.test.ts +119 -108
- package/src/client.ts +137 -118
- package/src/index.ts +14 -14
- package/src/process-manager.ts +118 -118
- package/src/protocol.ts +113 -113
- package/src/registry.ts +130 -92
- package/src/tools.ts +193 -160
- package/tsconfig.build.json +18 -18
- package/verify-clangd.mts +40 -0
- package/verify-live.mts +27 -27
|
@@ -1,108 +1,119 @@
|
|
|
1
|
-
import { test } from 'node:test';
|
|
2
|
-
import assert from 'node:assert/strict';
|
|
3
|
-
import { mkdtemp, rm } from 'node:fs/promises';
|
|
4
|
-
import { tmpdir } from 'node:os';
|
|
5
|
-
import { join, dirname } from 'node:path';
|
|
6
|
-
import { fileURLToPath } from 'node:url';
|
|
7
|
-
import { encodeMessage, MessageDecoder } from '../protocol.ts';
|
|
8
|
-
import { scrubEnv, ProcessManager } from '../process-manager.ts';
|
|
9
|
-
import { LspClient } from '../client.ts';
|
|
10
|
-
import { fileToUri } from '../registry.ts';
|
|
11
|
-
|
|
12
|
-
const FAKE_SERVER = join(dirname(fileURLToPath(import.meta.url)), 'fixtures', 'fake-server.cjs');
|
|
13
|
-
|
|
14
|
-
test('protocol: Content-Length framing round-trips through the decoder', () => {
|
|
15
|
-
const dec = new MessageDecoder();
|
|
16
|
-
const msg = { jsonrpc: '2.0' as const, id: 7, method: 'x', params: { s: '中文内容' } };
|
|
17
|
-
const wire = encodeMessage(msg);
|
|
18
|
-
// feed in two chunks to prove incremental decoding
|
|
19
|
-
const mid = Math.floor(wire.length / 2);
|
|
20
|
-
const out1 = dec.push(wire.subarray(0, mid));
|
|
21
|
-
const out2 = dec.push(wire.subarray(mid));
|
|
22
|
-
assert.deepEqual(out1, []);
|
|
23
|
-
assert.deepEqual(out2, [msg]);
|
|
24
|
-
// two messages in one chunk
|
|
25
|
-
const dec2 = new MessageDecoder();
|
|
26
|
-
const both = dec2.push(Buffer.concat([encodeMessage({ jsonrpc: '2.0', id: 1, method: 'a' }), encodeMessage({ jsonrpc: '2.0', id: 2, method: 'b' })]));
|
|
27
|
-
assert.equal(both.length, 2);
|
|
28
|
-
});
|
|
29
|
-
|
|
30
|
-
test('process-manager: env scrub keeps PATH, drops secret-looking vars', () => {
|
|
31
|
-
const env = scrubEnv([]);
|
|
32
|
-
assert.ok(env.PATH !== undefined || env.Path !== undefined, 'PATH survives');
|
|
33
|
-
const probeKeys = ['NODE_AUTH_TOKEN', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'BIGMODEL_API_KEY'];
|
|
34
|
-
for (const k of probeKeys) assert.equal((env as Record<string, unknown>)[k], undefined, `${k} must not inherit`);
|
|
35
|
-
});
|
|
36
|
-
|
|
37
|
-
test('client: full lifecycle against the fake server (initialize→sync→tier0→shutdown)', async () => {
|
|
38
|
-
const ws = await mkdtemp(join(tmpdir(), 'lsp-ws-'));
|
|
39
|
-
const manager = new ProcessManager({ id: 'fake', command: process.execPath, args: [FAKE_SERVER], source: 'explicit' }, ws);
|
|
40
|
-
const got: Array<{ uri: string; n: number }> = [];
|
|
41
|
-
const client = new LspClient(manager.start(), {
|
|
42
|
-
requestTimeoutMs: 10_000,
|
|
43
|
-
onDiagnostics: (uri, diags) => got.push({ uri, n: diags.length }),
|
|
44
|
-
});
|
|
45
|
-
const init = await client.initialize(fileToUri(ws));
|
|
46
|
-
assert.equal(init.serverInfo?.name, 'fake-lsp');
|
|
47
|
-
// document sync drives push diagnostics
|
|
48
|
-
const uri = fileToUri(join(ws, 'probe.ts'));
|
|
49
|
-
client.openDoc(uri, 'typescript', 'const x: number = DELBERATE_ERROR_MARKER;\n');
|
|
50
|
-
await new Promise((r) => setTimeout(r, 500));
|
|
51
|
-
assert.ok(got.some((g) => g.uri === uri && g.n === 1), 'one diagnostic pushed for the marker file');
|
|
52
|
-
// tier-0 requests
|
|
53
|
-
const hover = await client.hover({ uri }, { line: 0, character: 6 });
|
|
54
|
-
assert.match(JSON.stringify(hover?.contents), /fake hover/);
|
|
55
|
-
const def = await client.definition({ uri }, { line: 0, character: 6 });
|
|
56
|
-
assert.equal(Array.isArray(def) ? def[0]?.uri : def?.uri, 'file:///fake/def.ts');
|
|
57
|
-
const refs = await client.references({ uri }, { line: 0, character: 6 });
|
|
58
|
-
assert.equal(refs.length, 2);
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
assert.equal(
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
await
|
|
65
|
-
assert.equal(
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
});
|
|
95
|
-
|
|
96
|
-
test('
|
|
97
|
-
const ws = await mkdtemp(join(tmpdir(), 'lsp-ws-'));
|
|
98
|
-
const manager = new ProcessManager({ id: '
|
|
99
|
-
manager.start();
|
|
100
|
-
await
|
|
101
|
-
|
|
102
|
-
await
|
|
103
|
-
manager.
|
|
104
|
-
await
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { mkdtemp, rm } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { join, dirname } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { encodeMessage, MessageDecoder } from '../protocol.ts';
|
|
8
|
+
import { scrubEnv, ProcessManager } from '../process-manager.ts';
|
|
9
|
+
import { LspClient } from '../client.ts';
|
|
10
|
+
import { fileToUri } from '../registry.ts';
|
|
11
|
+
|
|
12
|
+
const FAKE_SERVER = join(dirname(fileURLToPath(import.meta.url)), 'fixtures', 'fake-server.cjs');
|
|
13
|
+
|
|
14
|
+
test('protocol: Content-Length framing round-trips through the decoder', () => {
|
|
15
|
+
const dec = new MessageDecoder();
|
|
16
|
+
const msg = { jsonrpc: '2.0' as const, id: 7, method: 'x', params: { s: '中文内容' } };
|
|
17
|
+
const wire = encodeMessage(msg);
|
|
18
|
+
// feed in two chunks to prove incremental decoding
|
|
19
|
+
const mid = Math.floor(wire.length / 2);
|
|
20
|
+
const out1 = dec.push(wire.subarray(0, mid));
|
|
21
|
+
const out2 = dec.push(wire.subarray(mid));
|
|
22
|
+
assert.deepEqual(out1, []);
|
|
23
|
+
assert.deepEqual(out2, [msg]);
|
|
24
|
+
// two messages in one chunk
|
|
25
|
+
const dec2 = new MessageDecoder();
|
|
26
|
+
const both = dec2.push(Buffer.concat([encodeMessage({ jsonrpc: '2.0', id: 1, method: 'a' }), encodeMessage({ jsonrpc: '2.0', id: 2, method: 'b' })]));
|
|
27
|
+
assert.equal(both.length, 2);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
test('process-manager: env scrub keeps PATH, drops secret-looking vars', () => {
|
|
31
|
+
const env = scrubEnv([]);
|
|
32
|
+
assert.ok(env.PATH !== undefined || env.Path !== undefined, 'PATH survives');
|
|
33
|
+
const probeKeys = ['NODE_AUTH_TOKEN', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'BIGMODEL_API_KEY'];
|
|
34
|
+
for (const k of probeKeys) assert.equal((env as Record<string, unknown>)[k], undefined, `${k} must not inherit`);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test('client: full lifecycle against the fake server (initialize→sync→tier0→shutdown)', async () => {
|
|
38
|
+
const ws = await mkdtemp(join(tmpdir(), 'lsp-ws-'));
|
|
39
|
+
const manager = new ProcessManager({ id: 'fake', command: process.execPath, args: [FAKE_SERVER], source: 'explicit' }, ws);
|
|
40
|
+
const got: Array<{ uri: string; n: number }> = [];
|
|
41
|
+
const client = new LspClient(manager.start(), {
|
|
42
|
+
requestTimeoutMs: 10_000,
|
|
43
|
+
onDiagnostics: (uri, diags) => got.push({ uri, n: diags.length }),
|
|
44
|
+
});
|
|
45
|
+
const init = await client.initialize(fileToUri(ws));
|
|
46
|
+
assert.equal(init.serverInfo?.name, 'fake-lsp');
|
|
47
|
+
// document sync drives push diagnostics
|
|
48
|
+
const uri = fileToUri(join(ws, 'probe.ts'));
|
|
49
|
+
client.openDoc(uri, 'typescript', 'const x: number = DELBERATE_ERROR_MARKER;\n');
|
|
50
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
51
|
+
assert.ok(got.some((g) => g.uri === uri && g.n === 1), 'one diagnostic pushed for the marker file');
|
|
52
|
+
// tier-0 requests
|
|
53
|
+
const hover = await client.hover({ uri }, { line: 0, character: 6 });
|
|
54
|
+
assert.match(JSON.stringify(hover?.contents), /fake hover/);
|
|
55
|
+
const def = await client.definition({ uri }, { line: 0, character: 6 });
|
|
56
|
+
assert.equal(Array.isArray(def) ? def[0]?.uri : def?.uri, 'file:///fake/def.ts');
|
|
57
|
+
const refs = await client.references({ uri }, { line: 0, character: 6 });
|
|
58
|
+
assert.equal(refs.length, 2);
|
|
59
|
+
// Tier-1: implementation + call hierarchy
|
|
60
|
+
const impls = await client.implementation({ uri }, { line: 0, character: 6 });
|
|
61
|
+
assert.equal(Array.isArray(impls) ? impls.length : 1, 2);
|
|
62
|
+
const item = await client.prepareCallHierarchy({ uri }, { line: 0, character: 6 });
|
|
63
|
+
const first = Array.isArray(item) ? item[0] : item;
|
|
64
|
+
const incoming = await client.callHierarchyIncoming(first);
|
|
65
|
+
assert.equal(incoming.length, 2);
|
|
66
|
+
assert.equal((incoming[0]!.from as { name?: string }).name, 'callerOne');
|
|
67
|
+
const outgoing = await client.callHierarchyOutgoing(first);
|
|
68
|
+
assert.equal(outgoing.length, 1);
|
|
69
|
+
assert.equal((outgoing[0]!.to as { name?: string }).name, 'helperFn');
|
|
70
|
+
const syms = await client.documentSymbols({ uri });
|
|
71
|
+
assert.equal(syms[0]?.name, 'mainFn');
|
|
72
|
+
assert.equal(syms[0]?.children?.[0]?.name, 'inner');
|
|
73
|
+
// clean shutdown stops the process
|
|
74
|
+
await client.shutdown();
|
|
75
|
+
await manager.stop();
|
|
76
|
+
assert.equal(manager.running, false);
|
|
77
|
+
await rm(ws, { recursive: true, force: true });
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test('registry: health probe flags a broken shim as unhealthy (fake: a command that always fails)', async () => {
|
|
81
|
+
const { discoverServers } = await import('../registry.ts');
|
|
82
|
+
// real discovery on THIS machine: whatever exists must carry a verdict
|
|
83
|
+
const servers = discoverServers(true);
|
|
84
|
+
for (const s of servers) {
|
|
85
|
+
assert.ok(typeof s.healthy === 'boolean', `${s.id} must carry a health verdict`);
|
|
86
|
+
if (!s.healthy) assert.ok((s.unhealthyReason ?? '').length > 0, `${s.id} unhealthy must say why`);
|
|
87
|
+
}
|
|
88
|
+
// a nonexistent binary is simply not discovered; a failing one is
|
|
89
|
+
// discovered-but-unhealthy only when it exists on PATH — both states stay
|
|
90
|
+
// honest. (On this dev machine rust-analyzer is a component-missing shim
|
|
91
|
+
// and MUST be unhealthy if present.)
|
|
92
|
+
const rust = servers.find((s) => s.id === 'rust-analyzer');
|
|
93
|
+
if (rust && rust.unhealthyReason) console.log('rust-analyzer verdict:', rust.unhealthyReason.slice(0, 80));
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test('client: unknown method surfaces the server error honestly', async () => {
|
|
97
|
+
const ws = await mkdtemp(join(tmpdir(), 'lsp-ws-'));
|
|
98
|
+
const manager = new ProcessManager({ id: 'fake', command: process.execPath, args: [FAKE_SERVER], source: 'explicit' }, ws);
|
|
99
|
+
const client = new LspClient(manager.start(), { requestTimeoutMs: 10_000 });
|
|
100
|
+
await client.initialize(fileToUri(ws));
|
|
101
|
+
await assert.rejects(() => client.request('workspace/executeCommand', {}), /-32601|method not found/);
|
|
102
|
+
await client.shutdown();
|
|
103
|
+
await manager.stop();
|
|
104
|
+
await rm(ws, { recursive: true, force: true });
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
test('process-manager: restart budget refuses flapping servers', async () => {
|
|
108
|
+
const ws = await mkdtemp(join(tmpdir(), 'lsp-ws-'));
|
|
109
|
+
const manager = new ProcessManager({ id: 'crasher', command: process.execPath, args: ['-e', 'process.exit(3)'], source: 'explicit' }, ws, { maxRestarts: 2 });
|
|
110
|
+
manager.start();
|
|
111
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
112
|
+
manager.start(); // restart 1
|
|
113
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
114
|
+
manager.start(); // restart 2
|
|
115
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
116
|
+
assert.throws(() => manager.start(), /restart budget/);
|
|
117
|
+
await manager.stop();
|
|
118
|
+
await rm(ws, { recursive: true, force: true });
|
|
119
|
+
});
|
package/src/client.ts
CHANGED
|
@@ -1,118 +1,137 @@
|
|
|
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 {
|
|
12
|
-
encodeMessage, MessageDecoder,
|
|
13
|
-
type InitializeParams, type InitializeResult, type JsonRpcResponse,
|
|
14
|
-
type Diagnostic, type DidOpenParams, type Hover, type Location, type DocumentSymbol, type ReferenceParams, type Position, type TextDocumentIdentifier,
|
|
15
|
-
} from './protocol.ts';
|
|
16
|
-
|
|
17
|
-
export interface LspClientOptions {
|
|
18
|
-
requestTimeoutMs?: number;
|
|
19
|
-
onDiagnostics?: (uri: string, diagnostics: Diagnostic[]) => void;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export class LspClient {
|
|
23
|
-
private seq = 0;
|
|
24
|
-
private pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }>();
|
|
25
|
-
private decoder = new MessageDecoder();
|
|
26
|
-
private serverInfo: InitializeResult | null = null;
|
|
27
|
-
|
|
28
|
-
constructor(private proc: ChildProcessWithoutNullStreams, private opts: LspClientOptions = {}) {
|
|
29
|
-
proc.stdout.on('data', (chunk: Buffer) => {
|
|
30
|
-
for (const msg of this.decoder.push(chunk)) this.handle(msg as Record<string, unknown>);
|
|
31
|
-
});
|
|
32
|
-
proc.on('exit', () => {
|
|
33
|
-
for (const [, p] of this.pending) { clearTimeout(p.timer); p.reject(new Error('server exited')); }
|
|
34
|
-
this.pending.clear();
|
|
35
|
-
});
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
private handle(msg: Record<string, unknown>): void {
|
|
39
|
-
if (msg.method === 'textDocument/publishDiagnostics') {
|
|
40
|
-
const p = msg.params as { uri: string; diagnostics: Diagnostic[] };
|
|
41
|
-
this.opts.onDiagnostics?.(p.uri, p.diagnostics ?? []);
|
|
42
|
-
return;
|
|
43
|
-
}
|
|
44
|
-
if (typeof msg.id === 'number' && ('result' in msg || 'error' in msg)) {
|
|
45
|
-
const p = this.pending.get(msg.id);
|
|
46
|
-
if (!p) return;
|
|
47
|
-
this.pending.delete(msg.id);
|
|
48
|
-
clearTimeout(p.timer);
|
|
49
|
-
const resp = msg as unknown as JsonRpcResponse;
|
|
50
|
-
if (resp.error) p.reject(new Error(`LSP ${resp.error.code}: ${resp.error.message}`));
|
|
51
|
-
else p.resolve(resp.result);
|
|
52
|
-
}
|
|
53
|
-
// window/logMessage etc: intentionally ignored (noise for the agent)
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
request<T>(method: string, params?: unknown): Promise<T> {
|
|
57
|
-
const id = ++this.seq;
|
|
58
|
-
return new Promise<T>((resolve, reject) => {
|
|
59
|
-
const timer = setTimeout(() => {
|
|
60
|
-
this.pending.delete(id);
|
|
61
|
-
reject(new Error(`LSP request ${method} timed out`));
|
|
62
|
-
}, this.opts.requestTimeoutMs ?? 20_000);
|
|
63
|
-
this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });
|
|
64
|
-
this.proc.stdin.write(encodeMessage({ jsonrpc: '2.0', id, method, params }));
|
|
65
|
-
});
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
notify(method: string, params?: unknown): void {
|
|
69
|
-
this.proc.stdin.write(encodeMessage({ jsonrpc: '2.0', method, params }));
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
async initialize(rootUri: string): Promise<InitializeResult> {
|
|
73
|
-
const params: InitializeParams = {
|
|
74
|
-
processId: process.pid,
|
|
75
|
-
rootUri,
|
|
76
|
-
workspaceFolders: [{ name: 'workspace', uri: rootUri }],
|
|
77
|
-
capabilities: { textDocument: { hover: {}, definition: {}, references: {}, documentSymbol: {}, publishDiagnostics: {} } },
|
|
78
|
-
};
|
|
79
|
-
const result = await this.request<InitializeResult>('initialize', params);
|
|
80
|
-
this.serverInfo = result;
|
|
81
|
-
this.notify('initialized', {});
|
|
82
|
-
return result;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
get info(): InitializeResult | null {
|
|
86
|
-
return this.serverInfo;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/* ---------------- document sync (minimal: open + full change) ---------------- */
|
|
90
|
-
|
|
91
|
-
openDoc(uri: string, languageId: string, text: string): void {
|
|
92
|
-
const params: DidOpenParams = { textDocument: { uri, languageId, version: 1, text } };
|
|
93
|
-
this.notify('textDocument/didOpen', params);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/* ---------------- Tier-0 requests ---------------- */
|
|
97
|
-
|
|
98
|
-
hover(textDocument: TextDocumentIdentifier, position: Position): Promise<Hover | null> {
|
|
99
|
-
return this.request<Hover | null>('textDocument/hover', { textDocument, position });
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
definition(textDocument: TextDocumentIdentifier, position: Position): Promise<Location | Location[] | null> {
|
|
103
|
-
return this.request<Location | Location[] | null>('textDocument/definition', { textDocument, position });
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
references(textDocument: TextDocumentIdentifier, position: Position, includeDeclaration = false): Promise<Location[]> {
|
|
107
|
-
const params: ReferenceParams = { textDocument, position, context: { includeDeclaration } };
|
|
108
|
-
return this.request<Location[]>('textDocument/references', params);
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
documentSymbols(textDocument: TextDocumentIdentifier): Promise<DocumentSymbol[]> {
|
|
112
|
-
return this.request<DocumentSymbol[]>('textDocument/documentSymbol', { textDocument });
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
}
|
|
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 {
|
|
12
|
+
encodeMessage, MessageDecoder,
|
|
13
|
+
type InitializeParams, type InitializeResult, type JsonRpcResponse,
|
|
14
|
+
type Diagnostic, type DidOpenParams, type Hover, type Location, type DocumentSymbol, type ReferenceParams, type Position, type TextDocumentIdentifier,
|
|
15
|
+
} from './protocol.ts';
|
|
16
|
+
|
|
17
|
+
export interface LspClientOptions {
|
|
18
|
+
requestTimeoutMs?: number;
|
|
19
|
+
onDiagnostics?: (uri: string, diagnostics: Diagnostic[]) => void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export class LspClient {
|
|
23
|
+
private seq = 0;
|
|
24
|
+
private pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }>();
|
|
25
|
+
private decoder = new MessageDecoder();
|
|
26
|
+
private serverInfo: InitializeResult | null = null;
|
|
27
|
+
|
|
28
|
+
constructor(private proc: ChildProcessWithoutNullStreams, private opts: LspClientOptions = {}) {
|
|
29
|
+
proc.stdout.on('data', (chunk: Buffer) => {
|
|
30
|
+
for (const msg of this.decoder.push(chunk)) this.handle(msg as Record<string, unknown>);
|
|
31
|
+
});
|
|
32
|
+
proc.on('exit', () => {
|
|
33
|
+
for (const [, p] of this.pending) { clearTimeout(p.timer); p.reject(new Error('server exited')); }
|
|
34
|
+
this.pending.clear();
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
private handle(msg: Record<string, unknown>): void {
|
|
39
|
+
if (msg.method === 'textDocument/publishDiagnostics') {
|
|
40
|
+
const p = msg.params as { uri: string; diagnostics: Diagnostic[] };
|
|
41
|
+
this.opts.onDiagnostics?.(p.uri, p.diagnostics ?? []);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
if (typeof msg.id === 'number' && ('result' in msg || 'error' in msg)) {
|
|
45
|
+
const p = this.pending.get(msg.id);
|
|
46
|
+
if (!p) return;
|
|
47
|
+
this.pending.delete(msg.id);
|
|
48
|
+
clearTimeout(p.timer);
|
|
49
|
+
const resp = msg as unknown as JsonRpcResponse;
|
|
50
|
+
if (resp.error) p.reject(new Error(`LSP ${resp.error.code}: ${resp.error.message}`));
|
|
51
|
+
else p.resolve(resp.result);
|
|
52
|
+
}
|
|
53
|
+
// window/logMessage etc: intentionally ignored (noise for the agent)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
request<T>(method: string, params?: unknown): Promise<T> {
|
|
57
|
+
const id = ++this.seq;
|
|
58
|
+
return new Promise<T>((resolve, reject) => {
|
|
59
|
+
const timer = setTimeout(() => {
|
|
60
|
+
this.pending.delete(id);
|
|
61
|
+
reject(new Error(`LSP request ${method} timed out`));
|
|
62
|
+
}, this.opts.requestTimeoutMs ?? 20_000);
|
|
63
|
+
this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });
|
|
64
|
+
this.proc.stdin.write(encodeMessage({ jsonrpc: '2.0', id, method, params }));
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
notify(method: string, params?: unknown): void {
|
|
69
|
+
this.proc.stdin.write(encodeMessage({ jsonrpc: '2.0', method, params }));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async initialize(rootUri: string): Promise<InitializeResult> {
|
|
73
|
+
const params: InitializeParams = {
|
|
74
|
+
processId: process.pid,
|
|
75
|
+
rootUri,
|
|
76
|
+
workspaceFolders: [{ name: 'workspace', uri: rootUri }],
|
|
77
|
+
capabilities: { textDocument: { hover: {}, definition: {}, references: {}, documentSymbol: {}, publishDiagnostics: {} } },
|
|
78
|
+
};
|
|
79
|
+
const result = await this.request<InitializeResult>('initialize', params);
|
|
80
|
+
this.serverInfo = result;
|
|
81
|
+
this.notify('initialized', {});
|
|
82
|
+
return result;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
get info(): InitializeResult | null {
|
|
86
|
+
return this.serverInfo;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/* ---------------- document sync (minimal: open + full change) ---------------- */
|
|
90
|
+
|
|
91
|
+
openDoc(uri: string, languageId: string, text: string): void {
|
|
92
|
+
const params: DidOpenParams = { textDocument: { uri, languageId, version: 1, text } };
|
|
93
|
+
this.notify('textDocument/didOpen', params);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/* ---------------- Tier-0 requests ---------------- */
|
|
97
|
+
|
|
98
|
+
hover(textDocument: TextDocumentIdentifier, position: Position): Promise<Hover | null> {
|
|
99
|
+
return this.request<Hover | null>('textDocument/hover', { textDocument, position });
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
definition(textDocument: TextDocumentIdentifier, position: Position): Promise<Location | Location[] | null> {
|
|
103
|
+
return this.request<Location | Location[] | null>('textDocument/definition', { textDocument, position });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
references(textDocument: TextDocumentIdentifier, position: Position, includeDeclaration = false): Promise<Location[]> {
|
|
107
|
+
const params: ReferenceParams = { textDocument, position, context: { includeDeclaration } };
|
|
108
|
+
return this.request<Location[]>('textDocument/references', params);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
documentSymbols(textDocument: TextDocumentIdentifier): Promise<DocumentSymbol[]> {
|
|
112
|
+
return this.request<DocumentSymbol[]>('textDocument/documentSymbol', { textDocument });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/* ---------------- Tier-1 requests ---------------- */
|
|
116
|
+
|
|
117
|
+
implementation(textDocument: TextDocumentIdentifier, position: Position): Promise<Location | Location[] | null> {
|
|
118
|
+
return this.request<Location | Location[] | null>('textDocument/implementation', { textDocument, position });
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** call hierarchy: prepare the item at a position, then incoming/outgoing */
|
|
122
|
+
async prepareCallHierarchy(textDocument: TextDocumentIdentifier, position: Position): Promise<unknown> {
|
|
123
|
+
return this.request<unknown>('textDocument/prepareCallHierarchy', { textDocument, position });
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
callHierarchyIncoming(item: unknown): Promise<Array<{ from: unknown; fromRanges: Location['range'][] }>> {
|
|
127
|
+
return this.request('callHierarchy/incomingCalls', { item });
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
callHierarchyOutgoing(item: unknown): Promise<Array<{ to: unknown; toRanges: Location['range'][] }>> {
|
|
131
|
+
return this.request('callHierarchy/outgoingCalls', { item });
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async shutdown(): Promise<void> {
|
|
135
|
+
try { await this.request('shutdown'); this.notify('exit'); } catch { /* best effort */ }
|
|
136
|
+
}
|
|
137
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,14 +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.ts';
|
|
11
|
-
export { ProcessManager, scrubEnv, fromPath, type ServerSpec, type ManagedServerOptions } from './process-manager.ts';
|
|
12
|
-
export { LspClient, type LspClientOptions } from './client.ts';
|
|
13
|
-
export { discoverServers, serverForFile, fileToUri, type DiscoveredServer } from './registry.ts';
|
|
14
|
-
export { lspTools, shutdownLsp, diagnosticsSummary, type LspToolContext } from './tools.ts';
|
|
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.ts';
|
|
11
|
+
export { ProcessManager, scrubEnv, fromPath, type ServerSpec, type ManagedServerOptions } from './process-manager.ts';
|
|
12
|
+
export { LspClient, type LspClientOptions } from './client.ts';
|
|
13
|
+
export { discoverServers, serverForFile, fileToUri, type DiscoveredServer } from './registry.ts';
|
|
14
|
+
export { lspTools, shutdownLsp, diagnosticsSummary, type LspToolContext } from './tools.ts';
|