@hmharness/lsp 0.23.40 → 0.23.42
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/package.json +23 -23
- package/src/__tests__/deveco.test.ts +60 -60
- package/src/__tests__/fixtures/fake-server.cjs +89 -89
- package/src/__tests__/lsp.test.ts +131 -131
- package/src/__tests__/trust.test.ts +68 -68
- package/src/client.ts +137 -137
- package/src/index.ts +15 -15
- package/src/process-manager.ts +118 -118
- package/src/protocol.ts +113 -113
- package/src/registry.ts +130 -130
- package/src/tools.ts +229 -229
- package/src/trust.ts +108 -108
- package/tsconfig.build.json +18 -18
- package/verify-clangd.mts +40 -40
- package/verify-live.mts +27 -27
package/src/tools.ts
CHANGED
|
@@ -1,229 +1,229 @@
|
|
|
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, DocumentSymbol } from './protocol.ts';
|
|
14
|
-
|
|
15
|
-
/** What a read-only tool observed — fed to the caller's Code World Model
|
|
16
|
-
* sink. Same posture as the extension onPageRead hook: observation only,
|
|
17
|
-
* best-effort, never able to fail the tool that observed. */
|
|
18
|
-
export interface LspObservation {
|
|
19
|
-
uri: string;
|
|
20
|
-
symbols?: DocumentSymbol[];
|
|
21
|
-
diagnostics?: Diagnostic[];
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
export interface LspToolContext {
|
|
25
|
-
workspaceRoot: string;
|
|
26
|
-
/** HMH_HOME — required by the source-trust guard (Capability OS slice);
|
|
27
|
-
* when absent PATH servers are refused honestly */
|
|
28
|
-
home?: string;
|
|
29
|
-
/** Observation sink: symbols/diagnostics pulled by the tools ride into
|
|
30
|
-
* the persisted Code World Model. Optional; sink errors are swallowed. */
|
|
31
|
-
onObserve?: (obs: LspObservation) => void;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
function emitObservation(ctx: LspToolContext, obs: LspObservation): void {
|
|
35
|
-
try {
|
|
36
|
-
ctx.onObserve?.(obs);
|
|
37
|
-
} catch { /* an observation sink must never fail the tool that observed */ }
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
interface ManagedClient {
|
|
41
|
-
server: DiscoveredServer;
|
|
42
|
-
manager: ProcessManager;
|
|
43
|
-
client: LspClient;
|
|
44
|
-
diagnostics: Map<string, Diagnostic[]>;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/** One live client per server for the lifetime of the context. */
|
|
48
|
-
const clients = new Map<string, ManagedClient>();
|
|
49
|
-
|
|
50
|
-
/** Sync last-resort kill on process exit (async shutdown may not run when
|
|
51
|
-
* the host dies); children must never outlive the agent process. */
|
|
52
|
-
if (typeof process !== 'undefined') {
|
|
53
|
-
process.once('exit', () => {
|
|
54
|
-
for (const [, mc] of clients) mc.manager.killSync();
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
async function clientFor(server: DiscoveredServer, workspaceRoot: string, home?: string): Promise<ManagedClient> {
|
|
59
|
-
const existing = clients.get(server.id);
|
|
60
|
-
if (existing) return existing;
|
|
61
|
-
// Capability OS slice (03 方案 supply-chain guard): no binary executes
|
|
62
|
-
// without source trust + a matching sha256 pin. PATH servers need one-time
|
|
63
|
-
// `hmh lsp trust <id>`; DevEco-local auto-trusts WITH pinning; a changed
|
|
64
|
-
// binary is refused as tampering.
|
|
65
|
-
if (home) {
|
|
66
|
-
const { checkTrust } = await import('./trust.ts');
|
|
67
|
-
const verdict = await checkTrust(home, server);
|
|
68
|
-
if (!verdict.trusted) {
|
|
69
|
-
throw new Error(`lsp ${server.id} blocked by source trust: ${verdict.reason}`);
|
|
70
|
-
}
|
|
71
|
-
} else if (!server.origin.includes('DevEco-local')) {
|
|
72
|
-
throw new Error(`lsp ${server.id} blocked: PATH servers need one-time trust (hmh lsp trust ${server.id})`);
|
|
73
|
-
}
|
|
74
|
-
const manager = new ProcessManager(server, workspaceRoot);
|
|
75
|
-
const diagnostics = new Map<string, Diagnostic[]>();
|
|
76
|
-
const client = new LspClient(manager.start(), {
|
|
77
|
-
onDiagnostics: (uri, diags) => diagnostics.set(uri, diags),
|
|
78
|
-
});
|
|
79
|
-
await client.initialize(fileToUri(workspaceRoot));
|
|
80
|
-
const entry: ManagedClient = { server, manager, client, diagnostics };
|
|
81
|
-
clients.set(server.id, entry);
|
|
82
|
-
return entry;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/** Stop every client this module started (TUI/CLI shutdown path). */
|
|
86
|
-
export async function shutdownLsp(): Promise<void> {
|
|
87
|
-
for (const [, mc] of clients) {
|
|
88
|
-
await mc.client.shutdown().catch(() => undefined);
|
|
89
|
-
await mc.manager.stop();
|
|
90
|
-
}
|
|
91
|
-
clients.clear();
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function fmtDiags(diags: Diagnostic[]): string {
|
|
95
|
-
if (diags.length === 0) return 'no diagnostics';
|
|
96
|
-
const sev = ['ERROR', 'WARN', 'INFO', 'HINT'];
|
|
97
|
-
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');
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
export function diagnosticsSummary(diags: Diagnostic[]): string {
|
|
101
|
-
const errors = diags.filter((d) => (d.severity ?? 1) === 1).length;
|
|
102
|
-
const warnings = diags.filter((d) => (d.severity ?? 2) === 2).length;
|
|
103
|
-
return `${diags.length} diagnostics (${errors} errors, ${warnings} warnings) — source: lsp (feedback, not build/test proof)`;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/** Resolve the target file argument to an absolute path (workspace-bound). */
|
|
107
|
-
function resolveFile(ctx: LspToolContext, file: string): string {
|
|
108
|
-
const abs = file.match(/^[A-Za-z]:[\\/]/) || file.startsWith('/') ? file : `${ctx.workspaceRoot}/${file}`.replace(/\\/g, '/');
|
|
109
|
-
return abs;
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
export function lspTools(ctx: LspToolContext): Tool[] {
|
|
113
|
-
const servers = () => discoverServers();
|
|
114
|
-
const pick = (file: string) => serverForFile(servers(), file);
|
|
115
|
-
|
|
116
|
-
const withClient = async (file: string, fn: (mc: ManagedClient, uri: string) => Promise<string>) => {
|
|
117
|
-
const server = pick(file);
|
|
118
|
-
if (!server) return { output: `no language server for ${file} (available: ${servers().map((s) => s.id).join(', ') || 'none on PATH'})`, isError: true };
|
|
119
|
-
const abs = resolveFile(ctx, file);
|
|
120
|
-
const mc = await clientFor(server, ctx.workspaceRoot, ctx.home);
|
|
121
|
-
return { output: await fn(mc, fileToUri(abs)) };
|
|
122
|
-
};
|
|
123
|
-
|
|
124
|
-
return [
|
|
125
|
-
{
|
|
126
|
-
name: 'lsp_diagnostics',
|
|
127
|
-
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)',
|
|
128
|
-
parameters: { type: 'object', properties: { file: { type: 'string', description: 'source file path' } }, required: ['file'] },
|
|
129
|
-
async execute(args) {
|
|
130
|
-
const abs = resolveFile(ctx, String(args.file ?? ''));
|
|
131
|
-
const r = await withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
132
|
-
const diags = mc.diagnostics.get(uri) ?? [];
|
|
133
|
-
emitObservation(ctx, { uri, diagnostics: diags });
|
|
134
|
-
return `[${mc.server.id}${mc.server.official ? '' : ' (community/unofficial)'}] ${uri}\n` + fmtDiags(diags);
|
|
135
|
-
});
|
|
136
|
-
return r;
|
|
137
|
-
},
|
|
138
|
-
},
|
|
139
|
-
{
|
|
140
|
-
name: 'lsp_hover',
|
|
141
|
-
description: 'Hover info (types/docs) for a symbol at a position. Args: file, line (1-based), character (1-based)',
|
|
142
|
-
parameters: { type: 'object', properties: { file: { type: 'string' }, line: { type: 'number' }, character: { type: 'number' } }, required: ['file', 'line', 'character'] },
|
|
143
|
-
async execute(args) {
|
|
144
|
-
return withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
145
|
-
const h = await mc.client.hover({ uri }, { line: Number(args.line ?? 1) - 1, character: Number(args.character ?? 1) - 1 });
|
|
146
|
-
if (!h) return 'no hover info at position';
|
|
147
|
-
return `[${mc.server.id}] ` + JSON.stringify(h.contents).slice(0, 800);
|
|
148
|
-
});
|
|
149
|
-
},
|
|
150
|
-
},
|
|
151
|
-
{
|
|
152
|
-
name: 'lsp_definition',
|
|
153
|
-
description: 'Go to definition of the symbol at a position. Args: file, line (1-based), character (1-based)',
|
|
154
|
-
parameters: { type: 'object', properties: { file: { type: 'string' }, line: { type: 'number' }, character: { type: 'number' } }, required: ['file', 'line', 'character'] },
|
|
155
|
-
async execute(args) {
|
|
156
|
-
return withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
157
|
-
const loc = await mc.client.definition({ uri }, { line: Number(args.line ?? 1) - 1, character: Number(args.character ?? 1) - 1 });
|
|
158
|
-
if (!loc) return 'no definition found';
|
|
159
|
-
const list = Array.isArray(loc) ? loc : [loc];
|
|
160
|
-
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');
|
|
161
|
-
});
|
|
162
|
-
},
|
|
163
|
-
},
|
|
164
|
-
{
|
|
165
|
-
name: 'lsp_symbols',
|
|
166
|
-
description: 'Document symbols (outline) for a file. Args: file',
|
|
167
|
-
parameters: { type: 'object', properties: { file: { type: 'string' } }, required: ['file'] },
|
|
168
|
-
async execute(args) {
|
|
169
|
-
return withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
170
|
-
const syms = await mc.client.documentSymbols({ uri });
|
|
171
|
-
emitObservation(ctx, { uri, symbols: syms });
|
|
172
|
-
const flat: string[] = [];
|
|
173
|
-
const walk = (ss: typeof syms, depth: number) => {
|
|
174
|
-
for (const s of ss.slice(0, 30)) {
|
|
175
|
-
flat.push(' '.repeat(depth) + `${s.name} (kind ${s.kind}) L${s.range.start.line + 1}`);
|
|
176
|
-
if (s.children) walk(s.children, depth + 1);
|
|
177
|
-
}
|
|
178
|
-
};
|
|
179
|
-
walk(syms, 0);
|
|
180
|
-
return `[${mc.server.id}] ${syms.length} top-level symbols\n` + (flat.join('\n') || '(none)');
|
|
181
|
-
});
|
|
182
|
-
},
|
|
183
|
-
},
|
|
184
|
-
{
|
|
185
|
-
name: 'lsp_references',
|
|
186
|
-
description: 'Find references to the symbol at a position. Args: file, line (1-based), character (1-based)',
|
|
187
|
-
parameters: { type: 'object', properties: { file: { type: 'string' }, line: { type: 'number' }, character: { type: 'number' } }, required: ['file', 'line', 'character'] },
|
|
188
|
-
async execute(args) {
|
|
189
|
-
return withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
190
|
-
const refs = await mc.client.references({ uri }, { line: Number(args.line ?? 1) - 1, character: Number(args.character ?? 1) - 1 });
|
|
191
|
-
return `[${mc.server.id}] ${refs.length} references\n` + refs.slice(0, 10).map((l) => `${l.uri} L${l.range.start.line + 1}`).join('\n');
|
|
192
|
-
});
|
|
193
|
-
},
|
|
194
|
-
},
|
|
195
|
-
{
|
|
196
|
-
name: 'lsp_implementation',
|
|
197
|
-
description: 'Find implementations of the interface/method at a position. Args: file, line (1-based), character (1-based)',
|
|
198
|
-
parameters: { type: 'object', properties: { file: { type: 'string' }, line: { type: 'number' }, character: { type: 'number' } }, required: ['file', 'line', 'character'] },
|
|
199
|
-
async execute(args) {
|
|
200
|
-
return withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
201
|
-
const impls = await mc.client.implementation({ uri }, { line: Number(args.line ?? 1) - 1, character: Number(args.character ?? 1) - 1 });
|
|
202
|
-
if (!impls) return 'no implementations found';
|
|
203
|
-
const list = Array.isArray(impls) ? impls : [impls];
|
|
204
|
-
return `[${mc.server.id}] ${list.length} implementations\n` + list.slice(0, 10).map((l) => `${l.uri} L${l.range.start.line + 1}`).join('\n');
|
|
205
|
-
});
|
|
206
|
-
},
|
|
207
|
-
},
|
|
208
|
-
{
|
|
209
|
-
name: 'lsp_call_hierarchy',
|
|
210
|
-
description: 'Who calls this symbol, and what does it call (incoming/outgoing). Args: file, line (1-based), character (1-based), direction=incoming|outgoing',
|
|
211
|
-
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'] },
|
|
212
|
-
async execute(args) {
|
|
213
|
-
return withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
214
|
-
const item = await mc.client.prepareCallHierarchy({ uri }, { line: Number(args.line ?? 1) - 1, character: Number(args.character ?? 1) - 1 });
|
|
215
|
-
if (!item || (Array.isArray(item) && item.length === 0)) return 'no call hierarchy item at position';
|
|
216
|
-
const first = Array.isArray(item) ? item[0] : item;
|
|
217
|
-
const dir = String(args.direction ?? 'incoming');
|
|
218
|
-
const calls = dir === 'outgoing' ? await mc.client.callHierarchyOutgoing(first) : await mc.client.callHierarchyIncoming(first);
|
|
219
|
-
const label = (x: unknown) => {
|
|
220
|
-
const it = x as { name?: string; uri?: string; range?: { start?: { line?: number } } };
|
|
221
|
-
return `${it.name ?? 'unknown'} ${it.uri ? it.uri + ' ' : ''}L${((it.range?.start?.line ?? 0) + 1)}`;
|
|
222
|
-
};
|
|
223
|
-
const side = (c: { from?: unknown; to?: unknown }) => (dir === 'outgoing' ? c.to : c.from);
|
|
224
|
-
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');
|
|
225
|
-
});
|
|
226
|
-
},
|
|
227
|
-
},
|
|
228
|
-
];
|
|
229
|
-
}
|
|
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, DocumentSymbol } from './protocol.ts';
|
|
14
|
+
|
|
15
|
+
/** What a read-only tool observed — fed to the caller's Code World Model
|
|
16
|
+
* sink. Same posture as the extension onPageRead hook: observation only,
|
|
17
|
+
* best-effort, never able to fail the tool that observed. */
|
|
18
|
+
export interface LspObservation {
|
|
19
|
+
uri: string;
|
|
20
|
+
symbols?: DocumentSymbol[];
|
|
21
|
+
diagnostics?: Diagnostic[];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface LspToolContext {
|
|
25
|
+
workspaceRoot: string;
|
|
26
|
+
/** HMH_HOME — required by the source-trust guard (Capability OS slice);
|
|
27
|
+
* when absent PATH servers are refused honestly */
|
|
28
|
+
home?: string;
|
|
29
|
+
/** Observation sink: symbols/diagnostics pulled by the tools ride into
|
|
30
|
+
* the persisted Code World Model. Optional; sink errors are swallowed. */
|
|
31
|
+
onObserve?: (obs: LspObservation) => void;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function emitObservation(ctx: LspToolContext, obs: LspObservation): void {
|
|
35
|
+
try {
|
|
36
|
+
ctx.onObserve?.(obs);
|
|
37
|
+
} catch { /* an observation sink must never fail the tool that observed */ }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface ManagedClient {
|
|
41
|
+
server: DiscoveredServer;
|
|
42
|
+
manager: ProcessManager;
|
|
43
|
+
client: LspClient;
|
|
44
|
+
diagnostics: Map<string, Diagnostic[]>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** One live client per server for the lifetime of the context. */
|
|
48
|
+
const clients = new Map<string, ManagedClient>();
|
|
49
|
+
|
|
50
|
+
/** Sync last-resort kill on process exit (async shutdown may not run when
|
|
51
|
+
* the host dies); children must never outlive the agent process. */
|
|
52
|
+
if (typeof process !== 'undefined') {
|
|
53
|
+
process.once('exit', () => {
|
|
54
|
+
for (const [, mc] of clients) mc.manager.killSync();
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function clientFor(server: DiscoveredServer, workspaceRoot: string, home?: string): Promise<ManagedClient> {
|
|
59
|
+
const existing = clients.get(server.id);
|
|
60
|
+
if (existing) return existing;
|
|
61
|
+
// Capability OS slice (03 方案 supply-chain guard): no binary executes
|
|
62
|
+
// without source trust + a matching sha256 pin. PATH servers need one-time
|
|
63
|
+
// `hmh lsp trust <id>`; DevEco-local auto-trusts WITH pinning; a changed
|
|
64
|
+
// binary is refused as tampering.
|
|
65
|
+
if (home) {
|
|
66
|
+
const { checkTrust } = await import('./trust.ts');
|
|
67
|
+
const verdict = await checkTrust(home, server);
|
|
68
|
+
if (!verdict.trusted) {
|
|
69
|
+
throw new Error(`lsp ${server.id} blocked by source trust: ${verdict.reason}`);
|
|
70
|
+
}
|
|
71
|
+
} else if (!server.origin.includes('DevEco-local')) {
|
|
72
|
+
throw new Error(`lsp ${server.id} blocked: PATH servers need one-time trust (hmh lsp trust ${server.id})`);
|
|
73
|
+
}
|
|
74
|
+
const manager = new ProcessManager(server, workspaceRoot);
|
|
75
|
+
const diagnostics = new Map<string, Diagnostic[]>();
|
|
76
|
+
const client = new LspClient(manager.start(), {
|
|
77
|
+
onDiagnostics: (uri, diags) => diagnostics.set(uri, diags),
|
|
78
|
+
});
|
|
79
|
+
await client.initialize(fileToUri(workspaceRoot));
|
|
80
|
+
const entry: ManagedClient = { server, manager, client, diagnostics };
|
|
81
|
+
clients.set(server.id, entry);
|
|
82
|
+
return entry;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Stop every client this module started (TUI/CLI shutdown path). */
|
|
86
|
+
export async function shutdownLsp(): Promise<void> {
|
|
87
|
+
for (const [, mc] of clients) {
|
|
88
|
+
await mc.client.shutdown().catch(() => undefined);
|
|
89
|
+
await mc.manager.stop();
|
|
90
|
+
}
|
|
91
|
+
clients.clear();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function fmtDiags(diags: Diagnostic[]): string {
|
|
95
|
+
if (diags.length === 0) return 'no diagnostics';
|
|
96
|
+
const sev = ['ERROR', 'WARN', 'INFO', 'HINT'];
|
|
97
|
+
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');
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function diagnosticsSummary(diags: Diagnostic[]): string {
|
|
101
|
+
const errors = diags.filter((d) => (d.severity ?? 1) === 1).length;
|
|
102
|
+
const warnings = diags.filter((d) => (d.severity ?? 2) === 2).length;
|
|
103
|
+
return `${diags.length} diagnostics (${errors} errors, ${warnings} warnings) — source: lsp (feedback, not build/test proof)`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Resolve the target file argument to an absolute path (workspace-bound). */
|
|
107
|
+
function resolveFile(ctx: LspToolContext, file: string): string {
|
|
108
|
+
const abs = file.match(/^[A-Za-z]:[\\/]/) || file.startsWith('/') ? file : `${ctx.workspaceRoot}/${file}`.replace(/\\/g, '/');
|
|
109
|
+
return abs;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function lspTools(ctx: LspToolContext): Tool[] {
|
|
113
|
+
const servers = () => discoverServers();
|
|
114
|
+
const pick = (file: string) => serverForFile(servers(), file);
|
|
115
|
+
|
|
116
|
+
const withClient = async (file: string, fn: (mc: ManagedClient, uri: string) => Promise<string>) => {
|
|
117
|
+
const server = pick(file);
|
|
118
|
+
if (!server) return { output: `no language server for ${file} (available: ${servers().map((s) => s.id).join(', ') || 'none on PATH'})`, isError: true };
|
|
119
|
+
const abs = resolveFile(ctx, file);
|
|
120
|
+
const mc = await clientFor(server, ctx.workspaceRoot, ctx.home);
|
|
121
|
+
return { output: await fn(mc, fileToUri(abs)) };
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
return [
|
|
125
|
+
{
|
|
126
|
+
name: 'lsp_diagnostics',
|
|
127
|
+
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)',
|
|
128
|
+
parameters: { type: 'object', properties: { file: { type: 'string', description: 'source file path' } }, required: ['file'] },
|
|
129
|
+
async execute(args) {
|
|
130
|
+
const abs = resolveFile(ctx, String(args.file ?? ''));
|
|
131
|
+
const r = await withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
132
|
+
const diags = mc.diagnostics.get(uri) ?? [];
|
|
133
|
+
emitObservation(ctx, { uri, diagnostics: diags });
|
|
134
|
+
return `[${mc.server.id}${mc.server.official ? '' : ' (community/unofficial)'}] ${uri}\n` + fmtDiags(diags);
|
|
135
|
+
});
|
|
136
|
+
return r;
|
|
137
|
+
},
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
name: 'lsp_hover',
|
|
141
|
+
description: 'Hover info (types/docs) for a symbol at a position. Args: file, line (1-based), character (1-based)',
|
|
142
|
+
parameters: { type: 'object', properties: { file: { type: 'string' }, line: { type: 'number' }, character: { type: 'number' } }, required: ['file', 'line', 'character'] },
|
|
143
|
+
async execute(args) {
|
|
144
|
+
return withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
145
|
+
const h = await mc.client.hover({ uri }, { line: Number(args.line ?? 1) - 1, character: Number(args.character ?? 1) - 1 });
|
|
146
|
+
if (!h) return 'no hover info at position';
|
|
147
|
+
return `[${mc.server.id}] ` + JSON.stringify(h.contents).slice(0, 800);
|
|
148
|
+
});
|
|
149
|
+
},
|
|
150
|
+
},
|
|
151
|
+
{
|
|
152
|
+
name: 'lsp_definition',
|
|
153
|
+
description: 'Go to definition of the symbol at a position. Args: file, line (1-based), character (1-based)',
|
|
154
|
+
parameters: { type: 'object', properties: { file: { type: 'string' }, line: { type: 'number' }, character: { type: 'number' } }, required: ['file', 'line', 'character'] },
|
|
155
|
+
async execute(args) {
|
|
156
|
+
return withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
157
|
+
const loc = await mc.client.definition({ uri }, { line: Number(args.line ?? 1) - 1, character: Number(args.character ?? 1) - 1 });
|
|
158
|
+
if (!loc) return 'no definition found';
|
|
159
|
+
const list = Array.isArray(loc) ? loc : [loc];
|
|
160
|
+
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');
|
|
161
|
+
});
|
|
162
|
+
},
|
|
163
|
+
},
|
|
164
|
+
{
|
|
165
|
+
name: 'lsp_symbols',
|
|
166
|
+
description: 'Document symbols (outline) for a file. Args: file',
|
|
167
|
+
parameters: { type: 'object', properties: { file: { type: 'string' } }, required: ['file'] },
|
|
168
|
+
async execute(args) {
|
|
169
|
+
return withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
170
|
+
const syms = await mc.client.documentSymbols({ uri });
|
|
171
|
+
emitObservation(ctx, { uri, symbols: syms });
|
|
172
|
+
const flat: string[] = [];
|
|
173
|
+
const walk = (ss: typeof syms, depth: number) => {
|
|
174
|
+
for (const s of ss.slice(0, 30)) {
|
|
175
|
+
flat.push(' '.repeat(depth) + `${s.name} (kind ${s.kind}) L${s.range.start.line + 1}`);
|
|
176
|
+
if (s.children) walk(s.children, depth + 1);
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
walk(syms, 0);
|
|
180
|
+
return `[${mc.server.id}] ${syms.length} top-level symbols\n` + (flat.join('\n') || '(none)');
|
|
181
|
+
});
|
|
182
|
+
},
|
|
183
|
+
},
|
|
184
|
+
{
|
|
185
|
+
name: 'lsp_references',
|
|
186
|
+
description: 'Find references to the symbol at a position. Args: file, line (1-based), character (1-based)',
|
|
187
|
+
parameters: { type: 'object', properties: { file: { type: 'string' }, line: { type: 'number' }, character: { type: 'number' } }, required: ['file', 'line', 'character'] },
|
|
188
|
+
async execute(args) {
|
|
189
|
+
return withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
190
|
+
const refs = await mc.client.references({ uri }, { line: Number(args.line ?? 1) - 1, character: Number(args.character ?? 1) - 1 });
|
|
191
|
+
return `[${mc.server.id}] ${refs.length} references\n` + refs.slice(0, 10).map((l) => `${l.uri} L${l.range.start.line + 1}`).join('\n');
|
|
192
|
+
});
|
|
193
|
+
},
|
|
194
|
+
},
|
|
195
|
+
{
|
|
196
|
+
name: 'lsp_implementation',
|
|
197
|
+
description: 'Find implementations of the interface/method at a position. Args: file, line (1-based), character (1-based)',
|
|
198
|
+
parameters: { type: 'object', properties: { file: { type: 'string' }, line: { type: 'number' }, character: { type: 'number' } }, required: ['file', 'line', 'character'] },
|
|
199
|
+
async execute(args) {
|
|
200
|
+
return withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
201
|
+
const impls = await mc.client.implementation({ uri }, { line: Number(args.line ?? 1) - 1, character: Number(args.character ?? 1) - 1 });
|
|
202
|
+
if (!impls) return 'no implementations found';
|
|
203
|
+
const list = Array.isArray(impls) ? impls : [impls];
|
|
204
|
+
return `[${mc.server.id}] ${list.length} implementations\n` + list.slice(0, 10).map((l) => `${l.uri} L${l.range.start.line + 1}`).join('\n');
|
|
205
|
+
});
|
|
206
|
+
},
|
|
207
|
+
},
|
|
208
|
+
{
|
|
209
|
+
name: 'lsp_call_hierarchy',
|
|
210
|
+
description: 'Who calls this symbol, and what does it call (incoming/outgoing). Args: file, line (1-based), character (1-based), direction=incoming|outgoing',
|
|
211
|
+
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'] },
|
|
212
|
+
async execute(args) {
|
|
213
|
+
return withClient(String(args.file ?? ''), async (mc, uri) => {
|
|
214
|
+
const item = await mc.client.prepareCallHierarchy({ uri }, { line: Number(args.line ?? 1) - 1, character: Number(args.character ?? 1) - 1 });
|
|
215
|
+
if (!item || (Array.isArray(item) && item.length === 0)) return 'no call hierarchy item at position';
|
|
216
|
+
const first = Array.isArray(item) ? item[0] : item;
|
|
217
|
+
const dir = String(args.direction ?? 'incoming');
|
|
218
|
+
const calls = dir === 'outgoing' ? await mc.client.callHierarchyOutgoing(first) : await mc.client.callHierarchyIncoming(first);
|
|
219
|
+
const label = (x: unknown) => {
|
|
220
|
+
const it = x as { name?: string; uri?: string; range?: { start?: { line?: number } } };
|
|
221
|
+
return `${it.name ?? 'unknown'} ${it.uri ? it.uri + ' ' : ''}L${((it.range?.start?.line ?? 0) + 1)}`;
|
|
222
|
+
};
|
|
223
|
+
const side = (c: { from?: unknown; to?: unknown }) => (dir === 'outgoing' ? c.to : c.from);
|
|
224
|
+
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');
|
|
225
|
+
});
|
|
226
|
+
},
|
|
227
|
+
},
|
|
228
|
+
];
|
|
229
|
+
}
|