@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,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;
@@ -0,0 +1,92 @@
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
+ import type { ServerSpec } from './process-manager.ts';
13
+
14
+ interface KnownServer {
15
+ id: string;
16
+ command: string;
17
+ args: string[];
18
+ /** languages this server indexes (used by tools to pick a server for a file) */
19
+ languages: string[];
20
+ official?: boolean; // false = community fallback (flagged in tool output)
21
+ }
22
+
23
+ const KNOWN: KnownServer[] = [
24
+ { id: 'typescript', command: 'typescript-language-server', args: ['--stdio'], languages: ['typescript', 'javascript'], official: true },
25
+ { id: 'pyright', command: 'pyright-langserver', args: ['--stdio'], languages: ['python'], official: true },
26
+ { id: 'rust-analyzer', command: 'rust-analyzer', args: [], languages: ['rust'], official: true },
27
+ { id: 'gopls', command: 'gopls', args: [], languages: ['go'], official: true },
28
+ { id: 'clangd', command: 'clangd', args: [], languages: ['c', 'cpp'], official: true },
29
+ // ArkTS: community fallback only — 03 方案: 官方/DevEco 本地服务优先,
30
+ // 社区 server 必须明确标注
31
+ { id: 'arkts-community', command: 'arkts-language-server', args: ['--stdio'], languages: ['arkts'], official: false },
32
+ ];
33
+
34
+ function which(cmd: string): string | null {
35
+ const probe = process.platform === 'win32'
36
+ ? spawnSync('cmd.exe', ['/d', '/s', '/c', `where ${cmd}`], { encoding: 'utf8', timeout: 5_000, windowsHide: true })
37
+ : spawnSync('which', [cmd], { encoding: 'utf8', timeout: 5_000 });
38
+ if (probe.status !== 0) return null;
39
+ const first = (probe.stdout || '').split('\n').map((l) => l.trim()).filter(Boolean)[0];
40
+ return first ?? null;
41
+ }
42
+
43
+ export interface DiscoveredServer extends ServerSpec {
44
+ languages: string[];
45
+ official: boolean;
46
+ /** probe result: a shim whose toolchain lacks the component (e.g. rustup
47
+ * without rust-analyzer installed) fails --version and must not register */
48
+ healthy: boolean;
49
+ unhealthyReason?: string;
50
+ }
51
+
52
+ /** Cheap health probe: `--version` must exit 0 within 5s. A PATH shim whose
53
+ * toolchain lacks the component (rustup without rust-analyzer installed)
54
+ * fails here — better an absent tool than a dead one registered. */
55
+ function healthProbe(command: string, args: string[]): { healthy: boolean; reason?: string } {
56
+ const r = spawnSync(command, [...args, '--version'], { encoding: 'utf8', timeout: 5_000, windowsHide: true });
57
+ if (r.status === 0) return { healthy: true };
58
+ const tail = ((r.stderr || '') + (r.stdout || '')).trim().split('\n').filter(Boolean).slice(-1)[0] ?? '';
59
+ return { healthy: false, reason: `--version probe failed (exit ${r.status}): ${tail.slice(0, 120)}` };
60
+ }
61
+
62
+ /** Discover available first-batch servers on THIS machine (PATH only).
63
+ * Memoized — the registry is probed per tool assembly and per spawn.
64
+ * Health-probed: broken shims are returned with healthy=false so callers
65
+ * can skip registering them (discovery stays honest about what exists). */
66
+ let discoveryCache: DiscoveredServer[] | null = null;
67
+ export function discoverServers(force = false): DiscoveredServer[] {
68
+ if (!force && discoveryCache) return discoveryCache;
69
+ const out: DiscoveredServer[] = [];
70
+ for (const k of KNOWN) {
71
+ const path = which(k.command);
72
+ if (!path) continue;
73
+ const probe = k.id === 'arkts-community' ? { healthy: true } : healthProbe(path, k.args);
74
+ 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 });
75
+ }
76
+ discoveryCache = out;
77
+ return out;
78
+ }
79
+
80
+ /** Pick the server responsible for a file uri/path by extension. */
81
+ export function serverForFile(servers: DiscoveredServer[], file: string): DiscoveredServer | null {
82
+ const ext = file.slice(file.lastIndexOf('.') + 1).toLowerCase();
83
+ 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' };
84
+ const lang = langByExt[ext];
85
+ if (!lang) return null;
86
+ return servers.find((s) => s.languages.includes(lang)) ?? null;
87
+ }
88
+
89
+ export function fileToUri(absPath: string): string {
90
+ const norm = absPath.replace(/\\/g, '/');
91
+ return 'file:///' + norm.replace(/^([A-Za-z]):/, '$1:').replace(/^\/+/, '');
92
+ }
package/src/tools.ts ADDED
@@ -0,0 +1,160 @@
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 { ProcessManager } from './process-manager.ts';
11
+ import { LspClient } from './client.ts';
12
+ import { discoverServers, serverForFile, fileToUri, type DiscoveredServer } from './registry.ts';
13
+ import type { Diagnostic } from './protocol.ts';
14
+
15
+ export interface LspToolContext {
16
+ workspaceRoot: string;
17
+ }
18
+
19
+ interface ManagedClient {
20
+ server: DiscoveredServer;
21
+ manager: ProcessManager;
22
+ client: LspClient;
23
+ diagnostics: Map<string, Diagnostic[]>;
24
+ }
25
+
26
+ /** One live client per server for the lifetime of the context. */
27
+ const clients = new Map<string, ManagedClient>();
28
+
29
+ /** Sync last-resort kill on process exit (async shutdown may not run when
30
+ * the host dies); children must never outlive the agent process. */
31
+ if (typeof process !== 'undefined') {
32
+ process.once('exit', () => {
33
+ for (const [, mc] of clients) mc.manager.killSync();
34
+ });
35
+ }
36
+
37
+ async function clientFor(server: DiscoveredServer, workspaceRoot: string): Promise<ManagedClient> {
38
+ const existing = clients.get(server.id);
39
+ if (existing) return existing;
40
+ const manager = new ProcessManager(server, workspaceRoot);
41
+ const diagnostics = new Map<string, Diagnostic[]>();
42
+ const client = new LspClient(manager.start(), {
43
+ onDiagnostics: (uri, diags) => diagnostics.set(uri, diags),
44
+ });
45
+ await client.initialize(fileToUri(workspaceRoot));
46
+ const entry: ManagedClient = { server, manager, client, diagnostics };
47
+ clients.set(server.id, entry);
48
+ return entry;
49
+ }
50
+
51
+ /** Stop every client this module started (TUI/CLI shutdown path). */
52
+ export async function shutdownLsp(): Promise<void> {
53
+ for (const [, mc] of clients) {
54
+ await mc.client.shutdown().catch(() => undefined);
55
+ await mc.manager.stop();
56
+ }
57
+ clients.clear();
58
+ }
59
+
60
+ function fmtDiags(diags: Diagnostic[]): string {
61
+ if (diags.length === 0) return 'no diagnostics';
62
+ const sev = ['ERROR', 'WARN', 'INFO', 'HINT'];
63
+ 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');
64
+ }
65
+
66
+ export function diagnosticsSummary(diags: Diagnostic[]): string {
67
+ const errors = diags.filter((d) => (d.severity ?? 1) === 1).length;
68
+ const warnings = diags.filter((d) => (d.severity ?? 2) === 2).length;
69
+ return `${diags.length} diagnostics (${errors} errors, ${warnings} warnings) — source: lsp (feedback, not build/test proof)`;
70
+ }
71
+
72
+ /** Resolve the target file argument to an absolute path (workspace-bound). */
73
+ function resolveFile(ctx: LspToolContext, file: string): string {
74
+ const abs = file.match(/^[A-Za-z]:[\\/]/) || file.startsWith('/') ? file : `${ctx.workspaceRoot}/${file}`.replace(/\\/g, '/');
75
+ return abs;
76
+ }
77
+
78
+ export function lspTools(ctx: LspToolContext): Tool[] {
79
+ const servers = () => discoverServers();
80
+ const pick = (file: string) => serverForFile(servers(), file);
81
+
82
+ const withClient = async (file: string, fn: (mc: ManagedClient, uri: string) => Promise<string>) => {
83
+ const server = pick(file);
84
+ if (!server) return { output: `no language server for ${file} (available: ${servers().map((s) => s.id).join(', ') || 'none on PATH'})`, isError: true };
85
+ const abs = resolveFile(ctx, file);
86
+ const mc = await clientFor(server, ctx.workspaceRoot);
87
+ return { output: await fn(mc, fileToUri(abs)) };
88
+ };
89
+
90
+ return [
91
+ {
92
+ name: 'lsp_diagnostics',
93
+ 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)',
94
+ parameters: { type: 'object', properties: { file: { type: 'string', description: 'source file path' } }, required: ['file'] },
95
+ async execute(args) {
96
+ const abs = resolveFile(ctx, String(args.file ?? ''));
97
+ const r = await withClient(String(args.file ?? ''), async (mc, uri) => {
98
+ const diags = mc.diagnostics.get(uri) ?? [];
99
+ return `[${mc.server.id}${mc.server.official ? '' : ' (community/unofficial)'}] ${uri}\n` + fmtDiags(diags);
100
+ });
101
+ return r;
102
+ },
103
+ },
104
+ {
105
+ name: 'lsp_hover',
106
+ description: 'Hover info (types/docs) for a symbol at a position. Args: file, line (1-based), character (1-based)',
107
+ parameters: { type: 'object', properties: { file: { type: 'string' }, line: { type: 'number' }, character: { type: 'number' } }, required: ['file', 'line', 'character'] },
108
+ async execute(args) {
109
+ return withClient(String(args.file ?? ''), async (mc, uri) => {
110
+ const h = await mc.client.hover({ uri }, { line: Number(args.line ?? 1) - 1, character: Number(args.character ?? 1) - 1 });
111
+ if (!h) return 'no hover info at position';
112
+ return `[${mc.server.id}] ` + JSON.stringify(h.contents).slice(0, 800);
113
+ });
114
+ },
115
+ },
116
+ {
117
+ name: 'lsp_definition',
118
+ description: 'Go to definition of the symbol at a position. Args: file, line (1-based), character (1-based)',
119
+ parameters: { type: 'object', properties: { file: { type: 'string' }, line: { type: 'number' }, character: { type: 'number' } }, required: ['file', 'line', 'character'] },
120
+ async execute(args) {
121
+ return withClient(String(args.file ?? ''), async (mc, uri) => {
122
+ const loc = await mc.client.definition({ uri }, { line: Number(args.line ?? 1) - 1, character: Number(args.character ?? 1) - 1 });
123
+ if (!loc) return 'no definition found';
124
+ const list = Array.isArray(loc) ? loc : [loc];
125
+ 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');
126
+ });
127
+ },
128
+ },
129
+ {
130
+ name: 'lsp_symbols',
131
+ description: 'Document symbols (outline) for a file. Args: file',
132
+ parameters: { type: 'object', properties: { file: { type: 'string' } }, required: ['file'] },
133
+ async execute(args) {
134
+ return withClient(String(args.file ?? ''), async (mc, uri) => {
135
+ const syms = await mc.client.documentSymbols({ uri });
136
+ const flat: string[] = [];
137
+ const walk = (ss: typeof syms, depth: number) => {
138
+ for (const s of ss.slice(0, 30)) {
139
+ flat.push(' '.repeat(depth) + `${s.name} (kind ${s.kind}) L${s.range.start.line + 1}`);
140
+ if (s.children) walk(s.children, depth + 1);
141
+ }
142
+ };
143
+ walk(syms, 0);
144
+ return `[${mc.server.id}] ${syms.length} top-level symbols\n` + (flat.join('\n') || '(none)');
145
+ });
146
+ },
147
+ },
148
+ {
149
+ name: 'lsp_references',
150
+ description: 'Find references to the symbol at a position. Args: file, line (1-based), character (1-based)',
151
+ parameters: { type: 'object', properties: { file: { type: 'string' }, line: { type: 'number' }, character: { type: 'number' } }, required: ['file', 'line', 'character'] },
152
+ async execute(args) {
153
+ return withClient(String(args.file ?? ''), async (mc, uri) => {
154
+ const refs = await mc.client.references({ uri }, { line: Number(args.line ?? 1) - 1, character: Number(args.character ?? 1) - 1 });
155
+ return `[${mc.server.id}] ${refs.length} references\n` + refs.slice(0, 10).map((l) => `${l.uri} L${l.range.start.line + 1}`).join('\n');
156
+ });
157
+ },
158
+ },
159
+ ];
160
+ }
@@ -0,0 +1,18 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "noEmit": false,
5
+ "allowImportingTsExtensions": false,
6
+ "rewriteRelativeImportExtensions": true,
7
+ "declaration": true,
8
+ "outDir": "dist",
9
+ "rootDir": "src",
10
+ "paths": {}
11
+ },
12
+ "include": [
13
+ "src/**/*.ts"
14
+ ],
15
+ "exclude": [
16
+ "src/__tests__"
17
+ ]
18
+ }
@@ -0,0 +1,27 @@
1
+ // Real-machine LSP verification against the fake server via the public surface
2
+ import { shutdownLsp, discoverServers, ProcessManager, LspClient, fileToUri } from './src/index.ts';
3
+ import { writeFileSync, mkdirSync, rmSync } from 'node:fs';
4
+
5
+ const ws = 'G:/hmharness/.tmp-lsp-ws';
6
+ rmSync(ws, { recursive: true, force: true });
7
+ mkdirSync(ws, { recursive: true });
8
+ writeFileSync(ws + '/demo.ts', 'const x: number = 1;\nconsole.log(x);\n');
9
+
10
+ console.log('discovered real servers:', discoverServers().map((s) => s.id).join(', ') || '(none)');
11
+
12
+ const mgr = new ProcessManager({ id: 'fake', command: process.execPath, args: ['src/__tests__/fixtures/fake-server.cjs'], source: 'explicit' }, process.cwd());
13
+ const client = new LspClient(mgr.start(), { requestTimeoutMs: 10_000 });
14
+ const info = await client.initialize(fileToUri(ws));
15
+ console.log('initialized:', info.serverInfo?.name, info.serverInfo?.version);
16
+ const uri = fileToUri(ws + '/demo.ts');
17
+ client.openDoc(uri, 'typescript', 'const y = DELBERATE_ERROR_MARKER;\n');
18
+ await new Promise((r) => setTimeout(r, 400));
19
+ const hover = await client.hover({ uri }, { line: 0, character: 6 });
20
+ console.log('hover:', JSON.stringify(hover?.contents).slice(0, 80));
21
+ const def = await client.definition({ uri }, { line: 0, character: 6 });
22
+ console.log('definition:', Array.isArray(def) ? def[0]?.uri : def?.uri);
23
+ await client.shutdown();
24
+ await mgr.stop();
25
+ console.log('stopped:', mgr.running === false);
26
+ await shutdownLsp();
27
+ console.log('REAL-MACHINE (fake-server) LIFECYCLE OK — real typescript-language-server: NOT ON PATH (NOT VERIFIED against a real server this round)');