@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.
- package/dist/client.d.ts +35 -0
- package/dist/client.js +99 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +14 -0
- package/dist/process-manager.d.ts +61 -0
- package/dist/process-manager.js +114 -0
- package/dist/protocol.d.ts +116 -0
- package/dist/protocol.js +44 -0
- package/dist/registry.d.ts +13 -0
- package/dist/registry.js +72 -0
- package/dist/tools.d.ts +17 -0
- package/dist/tools.js +136 -0
- package/package.json +23 -0
- package/src/__tests__/fixtures/fake-server.cjs +73 -0
- package/src/__tests__/lsp.test.ts +108 -0
- package/src/client.ts +118 -0
- package/src/index.ts +14 -0
- package/src/process-manager.ts +118 -0
- package/src/protocol.ts +113 -0
- package/src/registry.ts +92 -0
- package/src/tools.ts +160 -0
- package/tsconfig.build.json +18 -0
- package/verify-live.mts +27 -0
package/dist/tools.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { ProcessManager } from "./process-manager.js";
|
|
2
|
+
import { LspClient } from "./client.js";
|
|
3
|
+
import { discoverServers, serverForFile, fileToUri } from "./registry.js";
|
|
4
|
+
/** One live client per server for the lifetime of the context. */
|
|
5
|
+
const clients = new Map();
|
|
6
|
+
/** Sync last-resort kill on process exit (async shutdown may not run when
|
|
7
|
+
* the host dies); children must never outlive the agent process. */
|
|
8
|
+
if (typeof process !== 'undefined') {
|
|
9
|
+
process.once('exit', () => {
|
|
10
|
+
for (const [, mc] of clients)
|
|
11
|
+
mc.manager.killSync();
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
async function clientFor(server, workspaceRoot) {
|
|
15
|
+
const existing = clients.get(server.id);
|
|
16
|
+
if (existing)
|
|
17
|
+
return existing;
|
|
18
|
+
const manager = new ProcessManager(server, workspaceRoot);
|
|
19
|
+
const diagnostics = new Map();
|
|
20
|
+
const client = new LspClient(manager.start(), {
|
|
21
|
+
onDiagnostics: (uri, diags) => diagnostics.set(uri, diags),
|
|
22
|
+
});
|
|
23
|
+
await client.initialize(fileToUri(workspaceRoot));
|
|
24
|
+
const entry = { server, manager, client, diagnostics };
|
|
25
|
+
clients.set(server.id, entry);
|
|
26
|
+
return entry;
|
|
27
|
+
}
|
|
28
|
+
/** Stop every client this module started (TUI/CLI shutdown path). */
|
|
29
|
+
export async function shutdownLsp() {
|
|
30
|
+
for (const [, mc] of clients) {
|
|
31
|
+
await mc.client.shutdown().catch(() => undefined);
|
|
32
|
+
await mc.manager.stop();
|
|
33
|
+
}
|
|
34
|
+
clients.clear();
|
|
35
|
+
}
|
|
36
|
+
function fmtDiags(diags) {
|
|
37
|
+
if (diags.length === 0)
|
|
38
|
+
return 'no diagnostics';
|
|
39
|
+
const sev = ['ERROR', 'WARN', 'INFO', 'HINT'];
|
|
40
|
+
return diagnosticsSummary(diags) + '\n' + diags.slice(0, 10).map((d) => ` [${sev[(d.severity ?? 1) - 1]}] L${d.range.start.line + 1}:${d.range.start.character + 1} ${d.source ?? ''} ${d.message.slice(0, 140)}`).join('\n');
|
|
41
|
+
}
|
|
42
|
+
export function diagnosticsSummary(diags) {
|
|
43
|
+
const errors = diags.filter((d) => (d.severity ?? 1) === 1).length;
|
|
44
|
+
const warnings = diags.filter((d) => (d.severity ?? 2) === 2).length;
|
|
45
|
+
return `${diags.length} diagnostics (${errors} errors, ${warnings} warnings) — source: lsp (feedback, not build/test proof)`;
|
|
46
|
+
}
|
|
47
|
+
/** Resolve the target file argument to an absolute path (workspace-bound). */
|
|
48
|
+
function resolveFile(ctx, file) {
|
|
49
|
+
const abs = file.match(/^[A-Za-z]:[\\/]/) || file.startsWith('/') ? file : `${ctx.workspaceRoot}/${file}`.replace(/\\/g, '/');
|
|
50
|
+
return abs;
|
|
51
|
+
}
|
|
52
|
+
export function lspTools(ctx) {
|
|
53
|
+
const servers = () => discoverServers();
|
|
54
|
+
const pick = (file) => serverForFile(servers(), file);
|
|
55
|
+
const withClient = async (file, fn) => {
|
|
56
|
+
const server = pick(file);
|
|
57
|
+
if (!server)
|
|
58
|
+
return { output: `no language server for ${file} (available: ${servers().map((s) => s.id).join(', ') || 'none on PATH'})`, isError: true };
|
|
59
|
+
const abs = resolveFile(ctx, file);
|
|
60
|
+
const mc = await clientFor(server, ctx.workspaceRoot);
|
|
61
|
+
return { output: await fn(mc, fileToUri(abs)) };
|
|
62
|
+
};
|
|
63
|
+
return [
|
|
64
|
+
{
|
|
65
|
+
name: 'lsp_diagnostics',
|
|
66
|
+
description: 'Get live language-server diagnostics for a file (errors/warnings). source:lsp — this is FEEDBACK, not build/test proof. Args: file (relative to workspace or absolute)',
|
|
67
|
+
parameters: { type: 'object', properties: { file: { type: 'string', description: 'source file path' } }, required: ['file'] },
|
|
68
|
+
async execute(args) {
|
|
69
|
+
const abs = resolveFile(ctx, String(args.file ?? ''));
|
|
70
|
+
const r = await withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
71
|
+
const diags = mc.diagnostics.get(uri) ?? [];
|
|
72
|
+
return `[${mc.server.id}${mc.server.official ? '' : ' (community/unofficial)'}] ${uri}\n` + fmtDiags(diags);
|
|
73
|
+
});
|
|
74
|
+
return r;
|
|
75
|
+
},
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
name: 'lsp_hover',
|
|
79
|
+
description: 'Hover info (types/docs) for a symbol at a position. Args: file, line (1-based), character (1-based)',
|
|
80
|
+
parameters: { type: 'object', properties: { file: { type: 'string' }, line: { type: 'number' }, character: { type: 'number' } }, required: ['file', 'line', 'character'] },
|
|
81
|
+
async execute(args) {
|
|
82
|
+
return withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
83
|
+
const h = await mc.client.hover({ uri }, { line: Number(args.line ?? 1) - 1, character: Number(args.character ?? 1) - 1 });
|
|
84
|
+
if (!h)
|
|
85
|
+
return 'no hover info at position';
|
|
86
|
+
return `[${mc.server.id}] ` + JSON.stringify(h.contents).slice(0, 800);
|
|
87
|
+
});
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
name: 'lsp_definition',
|
|
92
|
+
description: 'Go to definition of the symbol at a position. Args: file, line (1-based), character (1-based)',
|
|
93
|
+
parameters: { type: 'object', properties: { file: { type: 'string' }, line: { type: 'number' }, character: { type: 'number' } }, required: ['file', 'line', 'character'] },
|
|
94
|
+
async execute(args) {
|
|
95
|
+
return withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
96
|
+
const loc = await mc.client.definition({ uri }, { line: Number(args.line ?? 1) - 1, character: Number(args.character ?? 1) - 1 });
|
|
97
|
+
if (!loc)
|
|
98
|
+
return 'no definition found';
|
|
99
|
+
const list = Array.isArray(loc) ? loc : [loc];
|
|
100
|
+
return `[${mc.server.id}] ` + list.slice(0, 5).map((l) => `${l.uri} L${l.range.start.line + 1}:${l.range.start.character + 1}`).join('\n');
|
|
101
|
+
});
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
name: 'lsp_symbols',
|
|
106
|
+
description: 'Document symbols (outline) for a file. Args: file',
|
|
107
|
+
parameters: { type: 'object', properties: { file: { type: 'string' } }, required: ['file'] },
|
|
108
|
+
async execute(args) {
|
|
109
|
+
return withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
110
|
+
const syms = await mc.client.documentSymbols({ uri });
|
|
111
|
+
const flat = [];
|
|
112
|
+
const walk = (ss, depth) => {
|
|
113
|
+
for (const s of ss.slice(0, 30)) {
|
|
114
|
+
flat.push(' '.repeat(depth) + `${s.name} (kind ${s.kind}) L${s.range.start.line + 1}`);
|
|
115
|
+
if (s.children)
|
|
116
|
+
walk(s.children, depth + 1);
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
walk(syms, 0);
|
|
120
|
+
return `[${mc.server.id}] ${syms.length} top-level symbols\n` + (flat.join('\n') || '(none)');
|
|
121
|
+
});
|
|
122
|
+
},
|
|
123
|
+
},
|
|
124
|
+
{
|
|
125
|
+
name: 'lsp_references',
|
|
126
|
+
description: 'Find references to the symbol at a position. Args: file, line (1-based), character (1-based)',
|
|
127
|
+
parameters: { type: 'object', properties: { file: { type: 'string' }, line: { type: 'number' }, character: { type: 'number' } }, required: ['file', 'line', 'character'] },
|
|
128
|
+
async execute(args) {
|
|
129
|
+
return withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
130
|
+
const refs = await mc.client.references({ uri }, { line: Number(args.line ?? 1) - 1, character: Number(args.character ?? 1) - 1 });
|
|
131
|
+
return `[${mc.server.id}] ${refs.length} references\n` + refs.slice(0, 10).map((l) => `${l.uri} L${l.range.start.line + 1}`).join('\n');
|
|
132
|
+
});
|
|
133
|
+
},
|
|
134
|
+
},
|
|
135
|
+
];
|
|
136
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@hmharness/lsp",
|
|
3
|
+
"version": "0.23.16",
|
|
4
|
+
"description": "hmharness LSP Client/Manager — drives external language servers (LSP 3.18 over stdio) for agent code intelligence. Client only: we never implement language servers.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"scripts": {
|
|
15
|
+
"build": "tsc -p tsconfig.build.json"
|
|
16
|
+
},
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@hmharness/kernel": "0.23.16"
|
|
19
|
+
},
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=22"
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fake LSP server for hermetic tests (no real language server needed on
|
|
3
|
+
* CI): speaks the base protocol over stdio and answers the Tier-0
|
|
4
|
+
* requests with fixed, deterministic results. Written as plain JS so the
|
|
5
|
+
* test can spawn it directly with the system node.
|
|
6
|
+
*/
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
|
|
9
|
+
function send(obj) {
|
|
10
|
+
const payload = Buffer.from(JSON.stringify(obj), 'utf8');
|
|
11
|
+
process.stdout.write(Buffer.concat([Buffer.from(`Content-Length: ${payload.length}\r\n\r\n`, 'ascii'), payload]));
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
let buf = Buffer.alloc(0);
|
|
15
|
+
process.stdin.on('data', (chunk) => {
|
|
16
|
+
buf = Buffer.concat([buf, chunk]);
|
|
17
|
+
for (;;) {
|
|
18
|
+
const headerEnd = buf.indexOf('\r\n\r\n');
|
|
19
|
+
if (headerEnd < 0) break;
|
|
20
|
+
const m = /Content-Length:\s*(\d+)/i.exec(buf.subarray(0, headerEnd).toString('ascii'));
|
|
21
|
+
if (!m) { buf = buf.subarray(headerEnd + 4); continue; }
|
|
22
|
+
const len = Number(m[1]);
|
|
23
|
+
const bodyStart = headerEnd + 4;
|
|
24
|
+
if (buf.length < bodyStart + len) break;
|
|
25
|
+
let msg;
|
|
26
|
+
try { msg = JSON.parse(buf.subarray(bodyStart, bodyStart + len).toString('utf8')); } catch { buf = buf.subarray(bodyStart + len); continue; }
|
|
27
|
+
buf = buf.subarray(bodyStart + len);
|
|
28
|
+
handle(msg);
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
function handle(msg) {
|
|
33
|
+
if (msg.method === 'initialize' && typeof msg.id === 'number') {
|
|
34
|
+
send({ jsonrpc: '2.0', id: msg.id, result: { capabilities: { hoverProvider: true, definitionProvider: true, referencesProvider: true, documentSymbolProvider: true }, serverInfo: { name: 'fake-lsp', version: '0.0.1' } } });
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
if (msg.method === 'initialized') return;
|
|
38
|
+
if (msg.method === 'shutdown' && typeof msg.id === 'number') {
|
|
39
|
+
send({ jsonrpc: '2.0', id: msg.id, result: null });
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (msg.method === 'exit') { process.exit(0); }
|
|
43
|
+
if (msg.method === 'textDocument/didOpen') {
|
|
44
|
+
const doc = msg.params.textDocument;
|
|
45
|
+
if (doc.text.includes('DELBERATE_ERROR_MARKER')) {
|
|
46
|
+
send({ jsonrpc: '2.0', method: 'textDocument/publishDiagnostics', params: { uri: doc.uri, diagnostics: [{ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 5 } }, severity: 1, source: 'fake-lsp', message: 'marker found: deliberate error' }] } });
|
|
47
|
+
} else {
|
|
48
|
+
send({ jsonrpc: '2.0', method: 'textDocument/publishDiagnostics', params: { uri: doc.uri, diagnostics: [] } });
|
|
49
|
+
}
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
if (msg.method === 'textDocument/hover' && typeof msg.id === 'number') {
|
|
53
|
+
send({ jsonrpc: '2.0', id: msg.id, result: { contents: { kind: 'plaintext', value: 'fake hover: symbol at ' + msg.params.position.line + ':' + msg.params.position.character } } });
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
if (msg.method === 'textDocument/definition' && typeof msg.id === 'number') {
|
|
57
|
+
send({ jsonrpc: '2.0', id: msg.id, result: { uri: 'file:///fake/def.ts', range: { start: { line: 3, character: 0 }, end: { line: 3, character: 10 } } } });
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (msg.method === 'textDocument/references' && typeof msg.id === 'number') {
|
|
61
|
+
send({ jsonrpc: '2.0', id: msg.id, result: [{ uri: 'file:///fake/r1.ts', range: { start: { line: 1, character: 0 }, end: { line: 1, character: 4 } } }, { uri: 'file:///fake/r2.ts', range: { start: { line: 2, character: 0 }, end: { line: 2, character: 4 } } }] });
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
if (msg.method === 'textDocument/documentSymbol' && typeof msg.id === 'number') {
|
|
65
|
+
send({ jsonrpc: '2.0', id: msg.id, result: [{ name: 'mainFn', kind: 12, range: { start: { line: 0, character: 0 }, end: { line: 5, character: 0 } }, children: [{ name: 'inner', kind: 6, range: { start: { line: 1, character: 2 }, end: { line: 2, character: 2 } } }] }] });
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
if (typeof msg.id === 'number') {
|
|
69
|
+
send({ jsonrpc: '2.0', id: msg.id, error: { code: -32601, message: 'method not found: ' + msg.method } });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
fs.writeSync(2, ''); // keep stderr referenced
|
|
@@ -0,0 +1,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
|
+
const syms = await client.documentSymbols({ uri });
|
|
60
|
+
assert.equal(syms[0]?.name, 'mainFn');
|
|
61
|
+
assert.equal(syms[0]?.children?.[0]?.name, 'inner');
|
|
62
|
+
// clean shutdown stops the process
|
|
63
|
+
await client.shutdown();
|
|
64
|
+
await manager.stop();
|
|
65
|
+
assert.equal(manager.running, false);
|
|
66
|
+
await rm(ws, { recursive: true, force: true });
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('registry: health probe flags a broken shim as unhealthy (fake: a command that always fails)', async () => {
|
|
70
|
+
const { discoverServers } = await import('../registry.ts');
|
|
71
|
+
// real discovery on THIS machine: whatever exists must carry a verdict
|
|
72
|
+
const servers = discoverServers(true);
|
|
73
|
+
for (const s of servers) {
|
|
74
|
+
assert.ok(typeof s.healthy === 'boolean', `${s.id} must carry a health verdict`);
|
|
75
|
+
if (!s.healthy) assert.ok((s.unhealthyReason ?? '').length > 0, `${s.id} unhealthy must say why`);
|
|
76
|
+
}
|
|
77
|
+
// a nonexistent binary is simply not discovered; a failing one is
|
|
78
|
+
// discovered-but-unhealthy only when it exists on PATH — both states stay
|
|
79
|
+
// honest. (On this dev machine rust-analyzer is a component-missing shim
|
|
80
|
+
// and MUST be unhealthy if present.)
|
|
81
|
+
const rust = servers.find((s) => s.id === 'rust-analyzer');
|
|
82
|
+
if (rust && rust.unhealthyReason) console.log('rust-analyzer verdict:', rust.unhealthyReason.slice(0, 80));
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test('client: unknown method surfaces the server error honestly', async () => {
|
|
86
|
+
const ws = await mkdtemp(join(tmpdir(), 'lsp-ws-'));
|
|
87
|
+
const manager = new ProcessManager({ id: 'fake', command: process.execPath, args: [FAKE_SERVER], source: 'explicit' }, ws);
|
|
88
|
+
const client = new LspClient(manager.start(), { requestTimeoutMs: 10_000 });
|
|
89
|
+
await client.initialize(fileToUri(ws));
|
|
90
|
+
await assert.rejects(() => client.request('workspace/executeCommand', {}), /-32601|method not found/);
|
|
91
|
+
await client.shutdown();
|
|
92
|
+
await manager.stop();
|
|
93
|
+
await rm(ws, { recursive: true, force: true });
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test('process-manager: restart budget refuses flapping servers', async () => {
|
|
97
|
+
const ws = await mkdtemp(join(tmpdir(), 'lsp-ws-'));
|
|
98
|
+
const manager = new ProcessManager({ id: 'crasher', command: process.execPath, args: ['-e', 'process.exit(3)'], source: 'explicit' }, ws, { maxRestarts: 2 });
|
|
99
|
+
manager.start();
|
|
100
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
101
|
+
manager.start(); // restart 1
|
|
102
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
103
|
+
manager.start(); // restart 2
|
|
104
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
105
|
+
assert.throws(() => manager.start(), /restart budget/);
|
|
106
|
+
await manager.stop();
|
|
107
|
+
await rm(ws, { recursive: true, force: true });
|
|
108
|
+
});
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,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
|
+
async shutdown(): Promise<void> {
|
|
116
|
+
try { await this.request('shutdown'); this.notify('exit'); } catch { /* best effort */ }
|
|
117
|
+
}
|
|
118
|
+
}
|
package/src/index.ts
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.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';
|
|
@@ -0,0 +1,118 @@
|
|
|
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, type ChildProcessWithoutNullStreams } from 'node:child_process';
|
|
14
|
+
|
|
15
|
+
export interface ServerSpec {
|
|
16
|
+
/** server id, e.g. 'typescript' | 'pyright' | 'rust-analyzer' */
|
|
17
|
+
id: string;
|
|
18
|
+
/** executable + args exactly as discovered (no auto-download here) */
|
|
19
|
+
command: string;
|
|
20
|
+
args: string[];
|
|
21
|
+
/** provenance recorded for audit: where this command came from */
|
|
22
|
+
source: 'PATH' | 'explicit';
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ManagedServerOptions {
|
|
26
|
+
/** secret-free env allowlist passed to the server (default: PATH/SYSTEMROOT/LANG only) */
|
|
27
|
+
envAllowlist?: string[];
|
|
28
|
+
maxRestarts?: number;
|
|
29
|
+
requestTimeoutMs?: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Environment scrub: language servers do NOT need API keys to index code.
|
|
33
|
+
* Default allowlist keeps PATH working on Windows without inheriting
|
|
34
|
+
* provider tokens or user secrets. */
|
|
35
|
+
export function scrubEnv(extraAllow: string[] = []): NodeJS.ProcessEnv {
|
|
36
|
+
const allow = new Set(['PATH', 'Path', 'SYSTEMROOT', 'SystemRoot', 'TEMP', 'TMP', 'LANG', 'HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'PROGRAMFILES', ...extraAllow]);
|
|
37
|
+
const out: NodeJS.ProcessEnv = {};
|
|
38
|
+
for (const [k, v] of Object.entries(process.env)) {
|
|
39
|
+
if (v !== undefined && allow.has(k.toUpperCase()) === false && !allow.has(k)) continue;
|
|
40
|
+
if (v !== undefined) out[k] = v;
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export class ProcessManager {
|
|
46
|
+
private proc: ChildProcessWithoutNullStreams | null = null;
|
|
47
|
+
/** total spawns; spawns beyond the first are restarts (exit clears this.proc,
|
|
48
|
+
* so counting there would miss exactly the flapping case) */
|
|
49
|
+
private spawns = 0;
|
|
50
|
+
readonly startedAt: string | null = null;
|
|
51
|
+
lastExit: { code: number | null; signal: NodeJS.Signals | null; at: string } | null = null;
|
|
52
|
+
|
|
53
|
+
constructor(
|
|
54
|
+
readonly spec: ServerSpec,
|
|
55
|
+
private cwd: string,
|
|
56
|
+
private opts: ManagedServerOptions = {},
|
|
57
|
+
) {}
|
|
58
|
+
|
|
59
|
+
get restartCount(): number {
|
|
60
|
+
return Math.max(0, this.spawns - 1);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
get running(): boolean {
|
|
64
|
+
return this.proc !== null && this.proc.exitCode === null && !this.proc.killed;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Spawn (or respawn after crash, up to the cap). Resolves with the
|
|
68
|
+
* child's stdio streams; rejects when the restart budget is spent. */
|
|
69
|
+
start(): ChildProcessWithoutNullStreams {
|
|
70
|
+
if (this.running && this.proc) return this.proc;
|
|
71
|
+
const max = this.opts.maxRestarts ?? 3;
|
|
72
|
+
// allowed total spawns = the initial one + maxRestarts
|
|
73
|
+
if (this.spawns >= 1 + max) {
|
|
74
|
+
throw new Error(`server ${this.spec.id} exceeded restart budget (${this.restartCount} restarts >= ${max}) — refusing to flap`);
|
|
75
|
+
}
|
|
76
|
+
this.spawns += 1;
|
|
77
|
+
const proc = spawn(this.spec.command, this.spec.args, {
|
|
78
|
+
cwd: this.cwd, // bound to the workspace (03 方案: workspace 外访问)
|
|
79
|
+
env: scrubEnv(),
|
|
80
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
81
|
+
windowsHide: true,
|
|
82
|
+
}) as ChildProcessWithoutNullStreams;
|
|
83
|
+
proc.on('exit', (code, signal) => {
|
|
84
|
+
this.lastExit = { code, signal, at: new Date().toISOString() };
|
|
85
|
+
if (this.proc === proc) this.proc = null;
|
|
86
|
+
});
|
|
87
|
+
this.proc = proc;
|
|
88
|
+
return proc;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Graceful stop, then hard kill. Always resolves. */
|
|
92
|
+
async stop(): Promise<void> {
|
|
93
|
+
const proc = this.proc;
|
|
94
|
+
if (!proc) return;
|
|
95
|
+
this.proc = null;
|
|
96
|
+
await new Promise<void>((resolve) => {
|
|
97
|
+
const killTimer = setTimeout(() => { try { proc.kill('SIGKILL'); } catch { /* gone */ } }, 3_000);
|
|
98
|
+
proc.once('exit', () => { clearTimeout(killTimer); resolve(); });
|
|
99
|
+
try { proc.kill(); } catch { clearTimeout(killTimer); resolve(); }
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Synchronous last-resort kill (process 'exit' hook: async cleanup will
|
|
104
|
+
* not run there). Never spawns; kills the live child if any. */
|
|
105
|
+
killSync(): void {
|
|
106
|
+
const proc = this.proc;
|
|
107
|
+
this.proc = null;
|
|
108
|
+
if (proc) { try { proc.kill('SIGKILL'); } catch { /* gone */ } }
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Discover a server binary from PATH (explicit, never auto-downloaded —
|
|
113
|
+
* 03 方案: 自动下载供应链风险,来源白名单+hash 是后续 Capability OS 的事). */
|
|
114
|
+
export function fromPath(id: string, command: string, args: string[]): ServerSpec | null {
|
|
115
|
+
// PATH lookup without spawning: `where` on win, `which` elsewhere — cheap
|
|
116
|
+
// probe done by the caller; here we just mark provenance
|
|
117
|
+
return { id, command, args, source: 'PATH' };
|
|
118
|
+
}
|