@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
package/src/registry.ts
CHANGED
|
@@ -1,92 +1,130 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @hmharness/lsp - server registry + discovery
|
|
3
|
-
*
|
|
4
|
-
* First-batch servers per the 03 方案: TypeScript/JavaScript, Pyright,
|
|
5
|
-
* rust-analyzer, gopls, clangd. Discovery is PATH-ONLY
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
{ id: '
|
|
28
|
-
{ id: '
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
{ id: '
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
*
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
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 plus DEVECO-LOCAL
|
|
6
|
+
* (the IDE ships a real clangd under tools/llvm/server/lsp — an official
|
|
7
|
+
* source we prefer over community downloads). Automatic downloads are
|
|
8
|
+
* explicitly NOT done here (supply chain; source allowlist + sha256 is the
|
|
9
|
+
* Capability OS layer's job). ArkTS: prefer official/DevEco-local servers
|
|
10
|
+
* when present; community servers are returned with an explicit
|
|
11
|
+
* `unofficial` flag.
|
|
12
|
+
*/
|
|
13
|
+
import { spawnSync } from 'node:child_process';
|
|
14
|
+
import { existsSync } from 'node:fs';
|
|
15
|
+
import type { ServerSpec } from './process-manager.ts';
|
|
16
|
+
|
|
17
|
+
interface KnownServer {
|
|
18
|
+
id: string;
|
|
19
|
+
command: string;
|
|
20
|
+
args: string[];
|
|
21
|
+
/** languages this server indexes (used by tools to pick a server for a file) */
|
|
22
|
+
languages: string[];
|
|
23
|
+
official?: boolean; // false = community fallback (flagged in tool output)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const KNOWN: KnownServer[] = [
|
|
27
|
+
{ id: 'typescript', command: 'typescript-language-server', args: ['--stdio'], languages: ['typescript', 'javascript'], official: true },
|
|
28
|
+
{ id: 'pyright', command: 'pyright-langserver', args: ['--stdio'], languages: ['python'], official: true },
|
|
29
|
+
{ id: 'rust-analyzer', command: 'rust-analyzer', args: [], languages: ['rust'], official: true },
|
|
30
|
+
{ id: 'gopls', command: 'gopls', args: [], languages: ['go'], official: true },
|
|
31
|
+
{ id: 'clangd', command: 'clangd', args: [], languages: ['c', 'cpp'], official: true },
|
|
32
|
+
// ArkTS: community fallback only — 03 方案: 官方/DevEco 本地服务优先,
|
|
33
|
+
// 社区 server 必须明确标注
|
|
34
|
+
{ id: 'arkts-community', command: 'arkts-language-server', args: ['--stdio'], languages: ['arkts'], official: false },
|
|
35
|
+
];
|
|
36
|
+
|
|
37
|
+
function which(cmd: string): string | null {
|
|
38
|
+
const probe = process.platform === 'win32'
|
|
39
|
+
? spawnSync('cmd.exe', ['/d', '/s', '/c', `where ${cmd}`], { encoding: 'utf8', timeout: 5_000, windowsHide: true })
|
|
40
|
+
: spawnSync('which', [cmd], { encoding: 'utf8', timeout: 5_000 });
|
|
41
|
+
if (probe.status !== 0) return null;
|
|
42
|
+
const first = (probe.stdout || '').split('\n').map((l) => l.trim()).filter(Boolean)[0];
|
|
43
|
+
return first ?? null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface DiscoveredServer extends ServerSpec {
|
|
47
|
+
languages: string[];
|
|
48
|
+
official: boolean;
|
|
49
|
+
/** probe result: a shim whose toolchain lacks the component (e.g. rustup
|
|
50
|
+
* without rust-analyzer installed) fails --version and must not register */
|
|
51
|
+
healthy: boolean;
|
|
52
|
+
unhealthyReason?: string;
|
|
53
|
+
/** where this server came from: PATH | PATH-community | DevEco-local | DevEco-local-community */
|
|
54
|
+
origin: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** DevEco Studio install roots to scan for bundled (official) servers. */
|
|
58
|
+
export const DEVECO_ROOTS = [
|
|
59
|
+
'C:/Program Files/Huawei/DevEco Studio',
|
|
60
|
+
'D:/Program Files/Huawei/DevEco Studio',
|
|
61
|
+
process.env.LOCALAPPDATA ? process.env.LOCALAPPDATA + '/Huawei/DevEco Studio' : '',
|
|
62
|
+
].filter(Boolean);
|
|
63
|
+
|
|
64
|
+
/** well-known bundled-server layouts inside a DevEco install (03 方案:
|
|
65
|
+
* 优先发现 DevEco/SDK 本地服务,记录来源——绝不自动下载) */
|
|
66
|
+
function devecoBundled(devecoRoots: string[]): Array<{ id: string; command: string; args: string[]; languages: string[]; official: boolean; origin: string }> {
|
|
67
|
+
const out: Array<{ id: string; command: string; args: string[]; languages: string[]; official: boolean; origin: string }> = [];
|
|
68
|
+
for (const root of devecoRoots) {
|
|
69
|
+
// clangd ships with the IDE's native toolchain (versioned per release)
|
|
70
|
+
const clangd = root + '/tools/llvm/server/lsp/win/clangd.exe';
|
|
71
|
+
if (existsSync(clangd)) out.push({ id: 'clangd', command: clangd, args: [], languages: ['c', 'cpp'], official: true, origin: 'DevEco-local' });
|
|
72
|
+
}
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Cheap health probe: `--version` must exit 0 within 5s. A PATH shim whose
|
|
77
|
+
* toolchain lacks the component (rustup without rust-analyzer installed)
|
|
78
|
+
* fails here — better an absent tool than a dead one registered. */
|
|
79
|
+
function healthProbe(command: string, args: string[]): { healthy: boolean; reason?: string } {
|
|
80
|
+
const r = spawnSync(command, [...args, '--version'], { encoding: 'utf8', timeout: 5_000, windowsHide: true });
|
|
81
|
+
if (r.status === 0) return { healthy: true };
|
|
82
|
+
const tail = ((r.stderr || '') + (r.stdout || '')).trim().split('\n').filter(Boolean).slice(-1)[0] ?? '';
|
|
83
|
+
return { healthy: false, reason: `--version probe failed (exit ${r.status}): ${tail.slice(0, 120)}` };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Discover available servers on THIS machine (PATH + DevEco-local).
|
|
87
|
+
* Memoized — the registry is probed per tool assembly and per spawn.
|
|
88
|
+
* Health-probed: broken shims are returned with healthy=false so callers
|
|
89
|
+
* can skip registering them (discovery stays honest about what exists). */
|
|
90
|
+
let discoveryCache: DiscoveredServer[] | null = null;
|
|
91
|
+
export function discoverServers(force = false, opts: { devecoRoots?: string[] } = {}): DiscoveredServer[] {
|
|
92
|
+
if (!force && discoveryCache) return discoveryCache;
|
|
93
|
+
const out: DiscoveredServer[] = [];
|
|
94
|
+
const seen = new Map<string, DiscoveredServer>();
|
|
95
|
+
const push = (id: string, command: string, args: string[], languages: string[], official: boolean, origin: string, probe: boolean) => {
|
|
96
|
+
const h = probe ? healthProbe(command, args) : { healthy: true as const };
|
|
97
|
+
const entry: DiscoveredServer = { id, command, args, source: origin.includes('DevEco') ? 'explicit' : 'PATH', languages, official, healthy: h.healthy, unhealthyReason: (h as { reason?: string }).reason, origin };
|
|
98
|
+
// first (preferred) source wins per id: DevEco-local beats PATH beats community
|
|
99
|
+
const existing = seen.get(id);
|
|
100
|
+
if (!existing || (existing.origin.includes('community') && !origin.includes('community'))) {
|
|
101
|
+
seen.set(id, entry);
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
// PATH servers
|
|
105
|
+
for (const k of KNOWN) {
|
|
106
|
+
const path = which(k.command);
|
|
107
|
+
if (!path) continue;
|
|
108
|
+
push(k.id, path, k.args, k.languages, k.official !== false, k.official !== false ? 'PATH' : 'PATH-community', true);
|
|
109
|
+
}
|
|
110
|
+
// DevEco-local bundled servers (official, no download ever)
|
|
111
|
+
for (const b of devecoBundled(opts.devecoRoots ?? DEVECO_ROOTS)) {
|
|
112
|
+
push(b.id, b.command, b.args, b.languages, b.official, b.origin, true);
|
|
113
|
+
}
|
|
114
|
+
discoveryCache = [...seen.values()];
|
|
115
|
+
return discoveryCache;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Pick the server responsible for a file uri/path by extension. */
|
|
119
|
+
export function serverForFile(servers: DiscoveredServer[], file: string): DiscoveredServer | null {
|
|
120
|
+
const ext = file.slice(file.lastIndexOf('.') + 1).toLowerCase();
|
|
121
|
+
const langByExt: Record<string, string> = { ts: 'typescript', tsx: 'typescript', mts: 'typescript', cts: 'typescript', js: 'javascript', mjs: 'javascript', cjs: 'javascript', py: 'python', rs: 'rust', go: 'go', c: 'c', h: 'c', cpp: 'cpp', hpp: 'cpp', cc: 'cpp', ets: 'arkts' };
|
|
122
|
+
const lang = langByExt[ext];
|
|
123
|
+
if (!lang) return null;
|
|
124
|
+
return servers.find((s) => s.languages.includes(lang)) ?? null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function fileToUri(absPath: string): string {
|
|
128
|
+
const norm = absPath.replace(/\\/g, '/');
|
|
129
|
+
return 'file:///' + norm.replace(/^([A-Za-z]):/, '$1:').replace(/^\/+/, '');
|
|
130
|
+
}
|
package/src/tools.ts
CHANGED
|
@@ -1,160 +1,193 @@
|
|
|
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
|
-
|
|
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
|
+
name: 'lsp_implementation',
|
|
161
|
+
description: 'Find implementations of the interface/method at a position. Args: file, line (1-based), character (1-based)',
|
|
162
|
+
parameters: { type: 'object', properties: { file: { type: 'string' }, line: { type: 'number' }, character: { type: 'number' } }, required: ['file', 'line', 'character'] },
|
|
163
|
+
async execute(args) {
|
|
164
|
+
return withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
165
|
+
const impls = await mc.client.implementation({ uri }, { line: Number(args.line ?? 1) - 1, character: Number(args.character ?? 1) - 1 });
|
|
166
|
+
if (!impls) return 'no implementations found';
|
|
167
|
+
const list = Array.isArray(impls) ? impls : [impls];
|
|
168
|
+
return `[${mc.server.id}] ${list.length} implementations\n` + list.slice(0, 10).map((l) => `${l.uri} L${l.range.start.line + 1}`).join('\n');
|
|
169
|
+
});
|
|
170
|
+
},
|
|
171
|
+
},
|
|
172
|
+
{
|
|
173
|
+
name: 'lsp_call_hierarchy',
|
|
174
|
+
description: 'Who calls this symbol, and what does it call (incoming/outgoing). Args: file, line (1-based), character (1-based), direction=incoming|outgoing',
|
|
175
|
+
parameters: { type: 'object', properties: { file: { type: 'string' }, line: { type: 'number' }, character: { type: 'number' }, direction: { type: 'string', description: 'incoming (who calls this) or outgoing (what this calls)' } }, required: ['file', 'line', 'character'] },
|
|
176
|
+
async execute(args) {
|
|
177
|
+
return withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
178
|
+
const item = await mc.client.prepareCallHierarchy({ uri }, { line: Number(args.line ?? 1) - 1, character: Number(args.character ?? 1) - 1 });
|
|
179
|
+
if (!item || (Array.isArray(item) && item.length === 0)) return 'no call hierarchy item at position';
|
|
180
|
+
const first = Array.isArray(item) ? item[0] : item;
|
|
181
|
+
const dir = String(args.direction ?? 'incoming');
|
|
182
|
+
const calls = dir === 'outgoing' ? await mc.client.callHierarchyOutgoing(first) : await mc.client.callHierarchyIncoming(first);
|
|
183
|
+
const label = (x: unknown) => {
|
|
184
|
+
const it = x as { name?: string; uri?: string; range?: { start?: { line?: number } } };
|
|
185
|
+
return `${it.name ?? 'unknown'} ${it.uri ? it.uri + ' ' : ''}L${((it.range?.start?.line ?? 0) + 1)}`;
|
|
186
|
+
};
|
|
187
|
+
const side = (c: { from?: unknown; to?: unknown }) => (dir === 'outgoing' ? c.to : c.from);
|
|
188
|
+
return `[${mc.server.id}] ${dir} calls: ${calls.length}\n` + calls.slice(0, 10).map((c) => label(side(c as { from?: unknown; to?: unknown }))).join('\n');
|
|
189
|
+
});
|
|
190
|
+
},
|
|
191
|
+
},
|
|
192
|
+
];
|
|
193
|
+
}
|
package/tsconfig.build.json
CHANGED
|
@@ -1,18 +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
|
-
}
|
|
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
|
+
}
|