@floydous/pi-agent-kernel 0.4.3 → 0.5.0
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/AGENT_KERNEL_SYS_PROMPT.md +1 -7
- package/CHANGELOG.md +36 -0
- package/README.md +6 -53
- package/config.example.toml +0 -8
- package/docs/README.md +1 -2
- package/docs/architecture.md +2 -3
- package/docs/configuration.md +10 -9
- package/docs/editing-and-verification.md +1 -3
- package/docs/retrieval.md +6 -11
- package/docs/testing.md +3 -3
- package/package.json +4 -2
- package/src/config/agent_kernel_command.ts +8 -39
- package/src/config/kernel_config.ts +30 -68
- package/src/config/toml.ts +6 -1
- package/src/editing/auto_heal.ts +1 -1
- package/src/editing/patch.ts +27 -16
- package/src/editing/post_edit_verification.ts +12 -10
- package/src/editing/smart_anchor.ts +7 -5
- package/src/editing/syntax-verify.ts +9 -5
- package/src/index.ts +15 -257
- package/src/retrieval/search_bm25.ts +4 -2
- package/src/retrieval/search_chunker.ts +1 -1
- package/src/retrieval/search_config.ts +4 -6
- package/src/retrieval/search_embedder.ts +3 -2
- package/src/retrieval/search_index.ts +82 -35
- package/src/retrieval/search_modal.ts +7 -8
- package/src/retrieval/{repomap.ts → tag_extractor.ts} +5 -292
- package/src/retrieval/tree_sitter_engine.ts +70 -34
- package/src/retrieval/workspace_walker.ts +6 -2
- package/src/safety/atomic_write.ts +1 -1
- package/src/safety/epistemic_guard.ts +105 -31
- package/src/safety/output_clamper.ts +14 -8
- package/src/tools/code_search_output.ts +2 -1
- package/src/tools/code_search_tool.ts +2 -5
- package/src/tools/context.ts +0 -14
- package/src/tools/edit_tool.ts +82 -115
- package/src/tools/read_tool.ts +42 -178
- package/src/ui/footer.ts +7 -7
- package/docs/lsp.md +0 -31
- package/src/lsp/adapters/base.ts +0 -42
- package/src/lsp/adapters/index.ts +0 -21
- package/src/lsp/adapters/python.ts +0 -37
- package/src/lsp/adapters/rust.ts +0 -35
- package/src/lsp/adapters/typescript.ts +0 -40
- package/src/lsp/index.ts +0 -13
- package/src/lsp/lsp_client.ts +0 -765
- package/src/lsp/lsp_detector.ts +0 -52
- package/src/lsp/lsp_formatter.ts +0 -323
- package/src/lsp/lsp_installer.ts +0 -320
- package/src/lsp/lsp_manager.ts +0 -202
- package/src/lsp/lsp_modal.ts +0 -675
- package/src/lsp/lsp_registry.ts +0 -600
- package/src/lsp/lsp_types.ts +0 -143
- package/src/retrieval/ast_search.ts +0 -999
- package/src/retrieval/symbol_reader.ts +0 -228
- package/src/tools/ast_search_formatter.ts +0 -161
- package/src/tools/ast_search_tool.ts +0 -146
- package/src/tools/lsp_tool.ts +0 -794
- package/src/tools/repo_map_tool.ts +0 -56
package/src/tools/lsp_tool.ts
DELETED
|
@@ -1,794 +0,0 @@
|
|
|
1
|
-
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import { Type } from "typebox";
|
|
3
|
-
import { Text, makeOutputText } from "../ui/tui_utils";
|
|
4
|
-
import * as path from "node:path";
|
|
5
|
-
import * as fs from "node:fs";
|
|
6
|
-
import {
|
|
7
|
-
LspManager,
|
|
8
|
-
formatDiagnostics,
|
|
9
|
-
formatDefinitions,
|
|
10
|
-
formatReferences,
|
|
11
|
-
formatHover,
|
|
12
|
-
formatDocumentSymbols,
|
|
13
|
-
uriToPath,
|
|
14
|
-
windowAround,
|
|
15
|
-
} from "../lsp";
|
|
16
|
-
import {
|
|
17
|
-
extractDocumentSymbols,
|
|
18
|
-
findSymbolReferences,
|
|
19
|
-
extractLocalSymbolHover,
|
|
20
|
-
searchAstSymbols,
|
|
21
|
-
} from "../retrieval/ast_search";
|
|
22
|
-
import { checkSyntax } from "../editing/syntax-verify";
|
|
23
|
-
import { kernelDebug } from "../safety/kernel_debug";
|
|
24
|
-
import { speculativeToolsEnabled, type SessionDeps } from "./context";
|
|
25
|
-
|
|
26
|
-
/** Extracted from index.ts — registers the `lsp` tool. */
|
|
27
|
-
export function registerLspTool(pi: ExtensionAPI, deps?: SessionDeps): void {
|
|
28
|
-
// 8. Tool: `lsp` (Language Server Protocol Symbol Resolution, Definitions, References, & Diagnostics)
|
|
29
|
-
pi.registerTool({
|
|
30
|
-
name: "lsp",
|
|
31
|
-
label: "Language Server Protocol (LSP)",
|
|
32
|
-
description:
|
|
33
|
-
"LSP definitions, references, hover, document_symbols, or diagnostics with Tree-sitter fallback.",
|
|
34
|
-
promptSnippet: "Query LSP for definitions, references, hover, and diagnostics",
|
|
35
|
-
renderShell: "default",
|
|
36
|
-
parameters: Type.Object({
|
|
37
|
-
action: Type.String({
|
|
38
|
-
enum: [
|
|
39
|
-
"definition",
|
|
40
|
-
"references",
|
|
41
|
-
"hover",
|
|
42
|
-
"document_symbols",
|
|
43
|
-
"diagnostics",
|
|
44
|
-
],
|
|
45
|
-
description: "LSP operation",
|
|
46
|
-
}),
|
|
47
|
-
path: Type.Optional(Type.String({ description: "File path (optional for definition if symbol given)" })),
|
|
48
|
-
line: Type.Optional(
|
|
49
|
-
Type.Number({
|
|
50
|
-
description: "1-based line number (for definition, references, hover)",
|
|
51
|
-
}),
|
|
52
|
-
),
|
|
53
|
-
character: Type.Optional(
|
|
54
|
-
Type.Number({
|
|
55
|
-
description: "1-based column number (default: 1)",
|
|
56
|
-
}),
|
|
57
|
-
),
|
|
58
|
-
symbol: Type.Optional(
|
|
59
|
-
Type.String({
|
|
60
|
-
description: "Symbol name (avoids line/character coordinates)",
|
|
61
|
-
}),
|
|
62
|
-
),
|
|
63
|
-
exclude_tests: Type.Optional(
|
|
64
|
-
Type.Boolean({
|
|
65
|
-
description: "Exclude references in tests (default: false)",
|
|
66
|
-
}),
|
|
67
|
-
),
|
|
68
|
-
exclude_declaration: Type.Optional(
|
|
69
|
-
Type.Boolean({
|
|
70
|
-
description: "Exclude declaration site from references (default: false)",
|
|
71
|
-
}),
|
|
72
|
-
),
|
|
73
|
-
}),
|
|
74
|
-
async execute(
|
|
75
|
-
_toolCallId: string,
|
|
76
|
-
params: any,
|
|
77
|
-
_signal: any,
|
|
78
|
-
onUpdate: any,
|
|
79
|
-
ctx: any,
|
|
80
|
-
): Promise<any> {
|
|
81
|
-
if (
|
|
82
|
-
!params ||
|
|
83
|
-
typeof params !== "object" ||
|
|
84
|
-
!["definition", "references", "hover", "document_symbols", "diagnostics"].includes(params.action)
|
|
85
|
-
) {
|
|
86
|
-
return {
|
|
87
|
-
content: [{ type: "text", text: "[LSP ERROR] Invalid action or parameters." }],
|
|
88
|
-
isError: true,
|
|
89
|
-
};
|
|
90
|
-
}
|
|
91
|
-
const action = params.action;
|
|
92
|
-
const targetPath = typeof params.path === "string" ? params.path.trim() : "";
|
|
93
|
-
const requestedSymbol = typeof params.symbol === "string" ? params.symbol.trim() : "";
|
|
94
|
-
|
|
95
|
-
const result = (
|
|
96
|
-
text: string,
|
|
97
|
-
source?: "lsp" | "tree-sitter" | "syntax-check",
|
|
98
|
-
extra: Record<string, unknown> = {},
|
|
99
|
-
isError = false,
|
|
100
|
-
) => ({
|
|
101
|
-
content: [{ type: "text", text }],
|
|
102
|
-
details: { action, ...(source ? { source } : {}), ...extra },
|
|
103
|
-
...(isError ? { isError: true } : {}),
|
|
104
|
-
});
|
|
105
|
-
|
|
106
|
-
// Bare-symbol definition lookup: path is omitted, resolve workspace-wide
|
|
107
|
-
if (!targetPath) {
|
|
108
|
-
if (action !== "definition") {
|
|
109
|
-
return result(
|
|
110
|
-
`[LSP ERROR] 'path' is required for action '${action}'.`,
|
|
111
|
-
undefined,
|
|
112
|
-
{ error: "missing_path" },
|
|
113
|
-
true,
|
|
114
|
-
);
|
|
115
|
-
}
|
|
116
|
-
if (!requestedSymbol) {
|
|
117
|
-
return result(
|
|
118
|
-
"[LSP ERROR] 'symbol' is required for workspace definition lookup when 'path' is omitted.",
|
|
119
|
-
undefined,
|
|
120
|
-
{ error: "missing_symbol" },
|
|
121
|
-
true,
|
|
122
|
-
);
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
// Resolve workspace-wide using searchAstSymbols with exact match first
|
|
126
|
-
let astHits = searchAstSymbols(ctx.cwd, {
|
|
127
|
-
name: requestedSymbol,
|
|
128
|
-
exactMatch: true,
|
|
129
|
-
});
|
|
130
|
-
if (astHits.length === 0) {
|
|
131
|
-
astHits = searchAstSymbols(ctx.cwd, {
|
|
132
|
-
name: requestedSymbol,
|
|
133
|
-
exactMatch: false,
|
|
134
|
-
});
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
if (astHits.length === 0) {
|
|
138
|
-
return result(
|
|
139
|
-
`Definition not found for symbol '${requestedSymbol}' in workspace.`,
|
|
140
|
-
"tree-sitter",
|
|
141
|
-
{ count: 0, symbol: requestedSymbol },
|
|
142
|
-
);
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
if (astHits.length === 1) {
|
|
146
|
-
const hit = astHits[0];
|
|
147
|
-
const aliasInfo = hit.aliasedFrom
|
|
148
|
-
? `\n (aliased from '${hit.aliasedFrom.originalName}' in ${hit.aliasedFrom.module || "workspace"})`
|
|
149
|
-
: "";
|
|
150
|
-
return result(
|
|
151
|
-
`[Tree-sitter AST Definition - unique match for '${requestedSymbol}']\n → [${hit.kind}] ${hit.name} (${hit.filePath}:${hit.line})\n Signature: ${hit.signature}${aliasInfo}`,
|
|
152
|
-
"tree-sitter",
|
|
153
|
-
{ count: 1, symbol: requestedSymbol },
|
|
154
|
-
);
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
// Ambiguous matches: bounded candidate list (up to 5 candidates)
|
|
158
|
-
const formatted = astHits
|
|
159
|
-
.slice(0, 5)
|
|
160
|
-
.map((h) => {
|
|
161
|
-
const aliasInfo = h.aliasedFrom
|
|
162
|
-
? `\n (aliased from '${h.aliasedFrom.originalName}' in ${h.aliasedFrom.module || "workspace"})`
|
|
163
|
-
: "";
|
|
164
|
-
return ` → [${h.kind}] ${h.name} (${h.filePath}:${h.line})\n Signature: ${h.signature}${aliasInfo}`;
|
|
165
|
-
})
|
|
166
|
-
.join("\n");
|
|
167
|
-
return result(
|
|
168
|
-
`[Tree-sitter AST Definition - ${astHits.length} matches for '${requestedSymbol}']\n${formatted}`,
|
|
169
|
-
"tree-sitter",
|
|
170
|
-
{ count: astHits.length, symbol: requestedSymbol },
|
|
171
|
-
);
|
|
172
|
-
}
|
|
173
|
-
const absPath = path.isAbsolute(targetPath)
|
|
174
|
-
? targetPath
|
|
175
|
-
: path.resolve(ctx.cwd, targetPath);
|
|
176
|
-
|
|
177
|
-
if (!fs.existsSync(absPath)) {
|
|
178
|
-
return result(`[LSP ERROR] File not found: ${targetPath}`, undefined, { error: "file_not_found" }, true);
|
|
179
|
-
}
|
|
180
|
-
if (fs.statSync(absPath).isDirectory()) {
|
|
181
|
-
return result(
|
|
182
|
-
`[LSP ERROR] Diagnostics requires a file, not directory: ${targetPath}`,
|
|
183
|
-
undefined,
|
|
184
|
-
{ error: "directory_path" },
|
|
185
|
-
true,
|
|
186
|
-
);
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
// Read the source only for local cursor/symbol resolution. An LSP query
|
|
190
|
-
// returns metadata, not model-visible source coverage, so it must not
|
|
191
|
-
// authorize a later mutation.
|
|
192
|
-
let observedContent: Buffer;
|
|
193
|
-
try {
|
|
194
|
-
observedContent = fs.readFileSync(absPath);
|
|
195
|
-
} catch (error: any) {
|
|
196
|
-
return result(
|
|
197
|
-
`[LSP ERROR] Unable to read ${targetPath}: ${error.message}`,
|
|
198
|
-
undefined,
|
|
199
|
-
{ error: "read_failed" },
|
|
200
|
-
true,
|
|
201
|
-
);
|
|
202
|
-
}
|
|
203
|
-
// Intentionally no epistemic read record: the source buffer is an
|
|
204
|
-
// implementation input, not content returned by the LSP operation.
|
|
205
|
-
|
|
206
|
-
let line0 = Math.max(0, (params.line || 1) - 1);
|
|
207
|
-
let col0 = Math.max(0, (params.character || 1) - 1);
|
|
208
|
-
|
|
209
|
-
// If a symbol is requested or column coordinate is defaulted to 1 (col0 = 0),
|
|
210
|
-
// check if line0 points to leading whitespace or reserved keywords (e.g. `pub fn`, `export async`).
|
|
211
|
-
// Advance col0 to the actual declared identifier so LSP and AST queries resolve cleanly.
|
|
212
|
-
const fileLines = observedContent.toString("utf8").split("\n");
|
|
213
|
-
if (requestedSymbol && (params.line === undefined || params.character === undefined)) {
|
|
214
|
-
const lineIdx = fileLines.findIndex((l) => {
|
|
215
|
-
const escaped = requestedSymbol.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
216
|
-
return new RegExp(`\\b${escaped}\\b`).test(l);
|
|
217
|
-
});
|
|
218
|
-
if (lineIdx !== -1) {
|
|
219
|
-
line0 = lineIdx;
|
|
220
|
-
const charIdx = fileLines[lineIdx].indexOf(requestedSymbol);
|
|
221
|
-
if (charIdx !== -1) col0 = charIdx;
|
|
222
|
-
}
|
|
223
|
-
} else if (params.character === undefined || params.character === 1) {
|
|
224
|
-
const lineText = fileLines[line0] || "";
|
|
225
|
-
const declMatch = lineText.match(/(?:pub(?:\([^)]*\))?\s+|async\s+|fn\s+|function\s+|def\s+|class\s+|interface\s+|type\s+|struct\s+|enum\s+|export\s+|let\s+|const\s+|var\s+)+([a-zA-Z_][a-zA-Z0-9_]*)/);
|
|
226
|
-
if (declMatch && declMatch.index !== undefined && declMatch[1]) {
|
|
227
|
-
const symName = declMatch[1];
|
|
228
|
-
const symOffset = lineText.indexOf(symName, declMatch.index);
|
|
229
|
-
if (symOffset !== -1) {
|
|
230
|
-
col0 = symOffset;
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
// Helper: extract identifier / qualified symbol under cursor (supports `foo.bar`, `crate::state::KeyUsage`)
|
|
236
|
-
const getSymbolUnderCursor = (): {
|
|
237
|
-
full: string;
|
|
238
|
-
leaf: string;
|
|
239
|
-
isModule: boolean;
|
|
240
|
-
} => {
|
|
241
|
-
try {
|
|
242
|
-
const fileContent = observedContent.toString("utf8");
|
|
243
|
-
const lines = fileContent.split("\n");
|
|
244
|
-
const lineText = lines[line0] || "";
|
|
245
|
-
const qualifiedWords = Array.from(
|
|
246
|
-
lineText.matchAll(
|
|
247
|
-
/[a-zA-Z_][a-zA-Z0-9_]*(?:(?:::|\.)[a-zA-Z_][a-zA-Z0-9_]*)*/g,
|
|
248
|
-
),
|
|
249
|
-
);
|
|
250
|
-
|
|
251
|
-
for (const w of qualifiedWords) {
|
|
252
|
-
if (
|
|
253
|
-
w.index !== undefined &&
|
|
254
|
-
col0 >= w.index &&
|
|
255
|
-
col0 <= w.index + w[0].length
|
|
256
|
-
) {
|
|
257
|
-
const fullExpr = w[0];
|
|
258
|
-
const separator = fullExpr.includes("::") ? "::" : ".";
|
|
259
|
-
const parts = fullExpr.split(separator);
|
|
260
|
-
|
|
261
|
-
let currentOffset = w.index;
|
|
262
|
-
for (let idx = 0; idx < parts.length; idx++) {
|
|
263
|
-
const part = parts[idx];
|
|
264
|
-
const partEnd = currentOffset + part.length;
|
|
265
|
-
if (col0 >= currentOffset && col0 <= partEnd) {
|
|
266
|
-
const isModule =
|
|
267
|
-
idx < parts.length - 1 ||
|
|
268
|
-
part === "crate" ||
|
|
269
|
-
part === "super" ||
|
|
270
|
-
part === "self";
|
|
271
|
-
return { full: fullExpr, leaf: part, isModule };
|
|
272
|
-
}
|
|
273
|
-
currentOffset = partEnd + separator.length;
|
|
274
|
-
}
|
|
275
|
-
return {
|
|
276
|
-
full: fullExpr,
|
|
277
|
-
leaf: parts[parts.length - 1],
|
|
278
|
-
isModule: false,
|
|
279
|
-
};
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
} catch (e) {
|
|
283
|
-
kernelDebug(e);
|
|
284
|
-
}
|
|
285
|
-
return { full: "", leaf: "", isModule: false };
|
|
286
|
-
};
|
|
287
|
-
|
|
288
|
-
onUpdate?.({
|
|
289
|
-
content: [{ type: "text", text: `Querying LSP (${action})...` }],
|
|
290
|
-
});
|
|
291
|
-
|
|
292
|
-
const lspMgr = LspManager.getInstance();
|
|
293
|
-
const client = await lspMgr.getClientForFile(absPath, ctx.cwd);
|
|
294
|
-
// LSP results are metadata, not source visibility. Keep the native buffer
|
|
295
|
-
// local for cursor resolution and never treat it as read evidence.
|
|
296
|
-
|
|
297
|
-
// If no client available, fall back cleanly to AST intelligence
|
|
298
|
-
if (!client) {
|
|
299
|
-
if (action === "document_symbols") {
|
|
300
|
-
const docSyms = extractDocumentSymbols(absPath);
|
|
301
|
-
if (docSyms.length > 0) {
|
|
302
|
-
const formatted = docSyms
|
|
303
|
-
.map((s) => `${s.line}: [${s.kind}] ${s.name} - ${s.signature}`)
|
|
304
|
-
.join("\n");
|
|
305
|
-
return result(formatted, "tree-sitter", { count: docSyms.length });
|
|
306
|
-
}
|
|
307
|
-
return result(
|
|
308
|
-
`No symbols found in ${path.basename(absPath)}.`,
|
|
309
|
-
"tree-sitter",
|
|
310
|
-
{ count: 0 },
|
|
311
|
-
);
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
if (action === "references") {
|
|
315
|
-
const sym = getSymbolUnderCursor();
|
|
316
|
-
const targetSym = requestedSymbol || sym.leaf || sym.full;
|
|
317
|
-
if (targetSym) {
|
|
318
|
-
const refs = findSymbolReferences(ctx.cwd, targetSym);
|
|
319
|
-
if (refs.length > 0) {
|
|
320
|
-
const formatted = refs
|
|
321
|
-
.map((r) => {
|
|
322
|
-
const col0 = Math.max(0, r.column - 1);
|
|
323
|
-
const endCol0 = col0 + targetSym.length;
|
|
324
|
-
const snippet = windowAround(r.lineText, col0, endCol0, 50);
|
|
325
|
-
return `${r.filePath}:${r.line}:${r.column}: ${snippet}`;
|
|
326
|
-
})
|
|
327
|
-
.join("\n");
|
|
328
|
-
return result(formatted, "tree-sitter", { count: refs.length });
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
return result("No references found in workspace.", "tree-sitter", { count: 0 });
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
if (action === "hover") {
|
|
335
|
-
const sym = getSymbolUnderCursor();
|
|
336
|
-
const targetSym = sym.leaf || sym.full;
|
|
337
|
-
if (targetSym) {
|
|
338
|
-
const localHover = extractLocalSymbolHover(
|
|
339
|
-
absPath,
|
|
340
|
-
line0,
|
|
341
|
-
col0,
|
|
342
|
-
targetSym,
|
|
343
|
-
);
|
|
344
|
-
if (localHover) {
|
|
345
|
-
return result(localHover, "tree-sitter");
|
|
346
|
-
}
|
|
347
|
-
const astHits = searchAstSymbols(ctx.cwd, {
|
|
348
|
-
name: targetSym,
|
|
349
|
-
exactMatch: true,
|
|
350
|
-
currentFilePath: absPath,
|
|
351
|
-
});
|
|
352
|
-
if (astHits.length > 0) {
|
|
353
|
-
const hit = astHits[0];
|
|
354
|
-
return result(
|
|
355
|
-
`[Tree-sitter AST Hover - ${hit.kind} ${hit.name}]\n${hit.signature}\nDeclared in ${hit.filePath}:${hit.line}`,
|
|
356
|
-
"tree-sitter",
|
|
357
|
-
);
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
return result("No hover information available at this position.", "tree-sitter");
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
if (action === "definition") {
|
|
364
|
-
const sym = getSymbolUnderCursor();
|
|
365
|
-
const targetSym = requestedSymbol || sym.leaf || sym.full;
|
|
366
|
-
if (targetSym) {
|
|
367
|
-
// 1. Check if targetSym is a module/file in the workspace (e.g. `state` -> `src/state.rs` or `state/mod.rs`)
|
|
368
|
-
const candidates = [
|
|
369
|
-
path.join(ctx.cwd, "src", `${targetSym}.rs`),
|
|
370
|
-
path.join(ctx.cwd, "src", targetSym, "mod.rs"),
|
|
371
|
-
path.join(ctx.cwd, `${targetSym}.rs`),
|
|
372
|
-
path.join(ctx.cwd, "src", `${targetSym}.ts`),
|
|
373
|
-
path.join(ctx.cwd, `${targetSym}.ts`),
|
|
374
|
-
path.join(ctx.cwd, `${targetSym}.py`),
|
|
375
|
-
path.join(path.dirname(absPath), `${targetSym}.rs`),
|
|
376
|
-
path.join(path.dirname(absPath), targetSym, "mod.rs"),
|
|
377
|
-
];
|
|
378
|
-
for (const cand of candidates) {
|
|
379
|
-
if (fs.existsSync(cand) && cand !== absPath) {
|
|
380
|
-
const rel = path.relative(ctx.cwd, cand).replace(/\\/g, "/");
|
|
381
|
-
return result(
|
|
382
|
-
`[Tree-sitter AST Definition - module '${targetSym}']\n → [module] ${targetSym} (${rel}:1)\n Module file in workspace`,
|
|
383
|
-
"tree-sitter",
|
|
384
|
-
);
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
// 2. Search AST symbol declarations across workspace
|
|
389
|
-
let astHits = searchAstSymbols(ctx.cwd, {
|
|
390
|
-
name: targetSym,
|
|
391
|
-
exactMatch: true,
|
|
392
|
-
currentFilePath: absPath,
|
|
393
|
-
});
|
|
394
|
-
if (astHits.length === 0 && sym.full && sym.full !== targetSym) {
|
|
395
|
-
astHits = searchAstSymbols(ctx.cwd, {
|
|
396
|
-
name: sym.full,
|
|
397
|
-
exactMatch: true,
|
|
398
|
-
currentFilePath: absPath,
|
|
399
|
-
});
|
|
400
|
-
}
|
|
401
|
-
if (astHits.length === 0) {
|
|
402
|
-
astHits = searchAstSymbols(ctx.cwd, {
|
|
403
|
-
name: targetSym,
|
|
404
|
-
exactMatch: false,
|
|
405
|
-
currentFilePath: absPath,
|
|
406
|
-
});
|
|
407
|
-
}
|
|
408
|
-
if (astHits.length === 0 && sym.full && sym.full !== targetSym) {
|
|
409
|
-
astHits = searchAstSymbols(ctx.cwd, {
|
|
410
|
-
name: sym.full,
|
|
411
|
-
exactMatch: false,
|
|
412
|
-
currentFilePath: absPath,
|
|
413
|
-
});
|
|
414
|
-
}
|
|
415
|
-
if (astHits.length > 0) {
|
|
416
|
-
const formatted = astHits
|
|
417
|
-
.slice(0, 5)
|
|
418
|
-
.map((h) => {
|
|
419
|
-
const aliasInfo = h.aliasedFrom
|
|
420
|
-
? `\n (aliased from '${h.aliasedFrom.originalName}' in ${h.aliasedFrom.module || "workspace"})`
|
|
421
|
-
: "";
|
|
422
|
-
return ` → [${h.kind}] ${h.name} (${h.filePath}:${h.line})\n Signature: ${h.signature}${aliasInfo}`;
|
|
423
|
-
})
|
|
424
|
-
.join("\n");
|
|
425
|
-
return result(
|
|
426
|
-
`[Tree-sitter AST Definition - ${astHits.length} match(es) for '${targetSym}']\n${formatted}`,
|
|
427
|
-
"tree-sitter",
|
|
428
|
-
{ count: astHits.length },
|
|
429
|
-
);
|
|
430
|
-
}
|
|
431
|
-
}
|
|
432
|
-
return result("Definition not found.", "tree-sitter", { count: 0 });
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
if (action === "diagnostics") {
|
|
436
|
-
const syn = checkSyntax(absPath);
|
|
437
|
-
if (!syn.valid) {
|
|
438
|
-
const status = syn.status || "failed";
|
|
439
|
-
return result(
|
|
440
|
-
`- [1:1] [${status.toUpperCase()}] Syntax validation: ${syn.error}`,
|
|
441
|
-
"syntax-check",
|
|
442
|
-
{ status },
|
|
443
|
-
);
|
|
444
|
-
}
|
|
445
|
-
const relPath = path.relative(ctx.cwd, absPath).replace(/\\/g, "/") || absPath;
|
|
446
|
-
return result(`${relPath} clean`, "syntax-check", { status: "clean" });
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
return result(
|
|
450
|
-
`[LSP Notice] No installed LSP server found for ${path.basename(absPath)}. ` +
|
|
451
|
-
(speculativeToolsEnabled(deps.getConfig, ctx.cwd)
|
|
452
|
-
? `Use 'ast_search' or run '/lsp install' to configure an LSP server.`
|
|
453
|
-
: `Run '/lsp install' to configure an LSP server.`),
|
|
454
|
-
"tree-sitter",
|
|
455
|
-
{ status: "unavailable" },
|
|
456
|
-
);
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
try {
|
|
460
|
-
if (action === "definition") {
|
|
461
|
-
const defs = await client.gotoDefinition(absPath, line0, col0);
|
|
462
|
-
if (defs.length > 0) {
|
|
463
|
-
return result(formatDefinitions(defs, ctx.cwd), "lsp", { count: defs.length });
|
|
464
|
-
}
|
|
465
|
-
// Only fallback to Tree-sitter AST for programming languages when LSP is unavailable or errored
|
|
466
|
-
const ext = path.extname(absPath).toLowerCase();
|
|
467
|
-
const nonCodeExts = [".md", ".markdown", ".json", ".jsonc", ".yaml", ".yml", ".toml", ".proto", ".txt"];
|
|
468
|
-
if (nonCodeExts.includes(ext)) {
|
|
469
|
-
return result(formatDefinitions(defs, ctx.cwd), "lsp", { count: defs.length });
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
// Tree-sitter fallback with exact symbol ranking
|
|
473
|
-
const sym = getSymbolUnderCursor();
|
|
474
|
-
const targetSym = requestedSymbol || sym.leaf || sym.full;
|
|
475
|
-
if (targetSym) {
|
|
476
|
-
let astHits = searchAstSymbols(ctx.cwd, {
|
|
477
|
-
name: targetSym,
|
|
478
|
-
exactMatch: true,
|
|
479
|
-
});
|
|
480
|
-
if (astHits.length === 0 && sym.full && sym.full !== targetSym) {
|
|
481
|
-
astHits = searchAstSymbols(ctx.cwd, {
|
|
482
|
-
name: sym.full,
|
|
483
|
-
exactMatch: true,
|
|
484
|
-
});
|
|
485
|
-
}
|
|
486
|
-
if (astHits.length === 0) {
|
|
487
|
-
astHits = searchAstSymbols(ctx.cwd, {
|
|
488
|
-
name: targetSym,
|
|
489
|
-
exactMatch: false,
|
|
490
|
-
});
|
|
491
|
-
}
|
|
492
|
-
if (astHits.length === 0 && sym.full && sym.full !== targetSym) {
|
|
493
|
-
astHits = searchAstSymbols(ctx.cwd, {
|
|
494
|
-
name: sym.full,
|
|
495
|
-
exactMatch: false,
|
|
496
|
-
});
|
|
497
|
-
}
|
|
498
|
-
if (astHits.length > 0) {
|
|
499
|
-
const formatted = astHits
|
|
500
|
-
.slice(0, 5)
|
|
501
|
-
.map((h) => {
|
|
502
|
-
const aliasInfo = h.aliasedFrom
|
|
503
|
-
? `\n (aliased from '${h.aliasedFrom.originalName}' in ${h.aliasedFrom.module || "workspace"})`
|
|
504
|
-
: "";
|
|
505
|
-
return ` → [${h.kind}] ${h.name} (${h.filePath}:${h.line})\n Signature: ${h.signature}${aliasInfo}`;
|
|
506
|
-
})
|
|
507
|
-
.join("\n");
|
|
508
|
-
return result(
|
|
509
|
-
`[Tree-sitter AST Local Fallback - ${astHits.length} declaration match(es) for '${targetSym}']\n${formatted}`,
|
|
510
|
-
"tree-sitter",
|
|
511
|
-
{ count: astHits.length },
|
|
512
|
-
);
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
|
|
516
|
-
return result(formatDefinitions(defs, ctx.cwd), "lsp", { count: defs.length });
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
if (action === "references") {
|
|
520
|
-
const filterRefs = (locations: any[]) => {
|
|
521
|
-
let res = locations;
|
|
522
|
-
if (params.exclude_declaration) {
|
|
523
|
-
res = res.filter((loc) => {
|
|
524
|
-
const locPath = uriToPath(loc.uri);
|
|
525
|
-
const isWindows = process.platform === "win32";
|
|
526
|
-
const normLoc = path.resolve(locPath);
|
|
527
|
-
const normAbs = path.resolve(absPath);
|
|
528
|
-
const sameFile = isWindows
|
|
529
|
-
? normLoc.toLowerCase() === normAbs.toLowerCase()
|
|
530
|
-
: normLoc === normAbs;
|
|
531
|
-
const sameLine = loc.range?.start?.line === line0;
|
|
532
|
-
return !(sameFile && sameLine);
|
|
533
|
-
});
|
|
534
|
-
}
|
|
535
|
-
if (params.exclude_tests) {
|
|
536
|
-
res = res.filter((loc) => {
|
|
537
|
-
const locPath = uriToPath(loc.uri).replace(/\\/g, "/").toLowerCase();
|
|
538
|
-
const fileName = path.basename(locPath);
|
|
539
|
-
const isTestPath =
|
|
540
|
-
locPath.includes("/test/") ||
|
|
541
|
-
locPath.includes("/tests/") ||
|
|
542
|
-
locPath.startsWith("tests/") ||
|
|
543
|
-
locPath.startsWith("test/") ||
|
|
544
|
-
locPath.includes("__tests__") ||
|
|
545
|
-
fileName.startsWith("test_") ||
|
|
546
|
-
fileName.endsWith("_test.rs") ||
|
|
547
|
-
fileName.endsWith("_test.go") ||
|
|
548
|
-
fileName.endsWith("_test.py") ||
|
|
549
|
-
fileName.endsWith(".test.ts") ||
|
|
550
|
-
fileName.endsWith(".spec.ts") ||
|
|
551
|
-
fileName.endsWith(".test.js");
|
|
552
|
-
return !isTestPath;
|
|
553
|
-
});
|
|
554
|
-
}
|
|
555
|
-
return res;
|
|
556
|
-
};
|
|
557
|
-
|
|
558
|
-
let refs = await client.findReferences(absPath, line0, col0);
|
|
559
|
-
if (refs.length > 0) {
|
|
560
|
-
refs = filterRefs(refs);
|
|
561
|
-
if (refs.length > 0) {
|
|
562
|
-
return result(formatReferences(refs, ctx.cwd), "lsp", { count: refs.length });
|
|
563
|
-
}
|
|
564
|
-
}
|
|
565
|
-
const ext = path.extname(absPath).toLowerCase();
|
|
566
|
-
const nonCodeExts = [".md", ".markdown", ".json", ".jsonc", ".yaml", ".yml", ".toml", ".proto", ".txt"];
|
|
567
|
-
if (nonCodeExts.includes(ext)) {
|
|
568
|
-
return result(formatReferences(refs, ctx.cwd), "lsp", { count: refs.length });
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
// Workspace-wide symbol reference search fallback
|
|
572
|
-
const sym = getSymbolUnderCursor();
|
|
573
|
-
const targetSym = requestedSymbol || sym.leaf || sym.full;
|
|
574
|
-
if (targetSym) {
|
|
575
|
-
let astRefs = findSymbolReferences(ctx.cwd, targetSym);
|
|
576
|
-
if (params.exclude_declaration) {
|
|
577
|
-
astRefs = astRefs.filter((r) => {
|
|
578
|
-
const isWindows = process.platform === "win32";
|
|
579
|
-
const normRef = path.resolve(ctx.cwd, r.filePath);
|
|
580
|
-
const normAbs = path.resolve(absPath);
|
|
581
|
-
const sameFile = isWindows
|
|
582
|
-
? normRef.toLowerCase() === normAbs.toLowerCase()
|
|
583
|
-
: normRef === normAbs;
|
|
584
|
-
return !(sameFile && r.line === (line0 + 1));
|
|
585
|
-
});
|
|
586
|
-
}
|
|
587
|
-
if (params.exclude_tests) {
|
|
588
|
-
astRefs = astRefs.filter((r) => {
|
|
589
|
-
const norm = r.filePath.replace(/\\/g, "/").toLowerCase();
|
|
590
|
-
const fileName = path.basename(norm);
|
|
591
|
-
return !(
|
|
592
|
-
norm.includes("/test/") ||
|
|
593
|
-
norm.includes("/tests/") ||
|
|
594
|
-
norm.startsWith("tests/") ||
|
|
595
|
-
norm.startsWith("test/") ||
|
|
596
|
-
norm.includes("__tests__") ||
|
|
597
|
-
fileName.startsWith("test_") ||
|
|
598
|
-
fileName.endsWith("_test.rs") ||
|
|
599
|
-
fileName.endsWith("_test.go") ||
|
|
600
|
-
fileName.endsWith("_test.py") ||
|
|
601
|
-
fileName.endsWith(".test.ts") ||
|
|
602
|
-
fileName.endsWith(".spec.ts") ||
|
|
603
|
-
fileName.endsWith(".test.js")
|
|
604
|
-
);
|
|
605
|
-
});
|
|
606
|
-
}
|
|
607
|
-
if (astRefs.length > 0) {
|
|
608
|
-
const formatted = astRefs
|
|
609
|
-
.map((r) => {
|
|
610
|
-
const col0 = Math.max(0, r.column - 1);
|
|
611
|
-
const endCol0 = col0 + targetSym.length;
|
|
612
|
-
const snippet = windowAround(r.lineText, col0, endCol0, 50);
|
|
613
|
-
return `${r.filePath}:${r.line}:${r.column}: ${snippet}`;
|
|
614
|
-
})
|
|
615
|
-
.join("\n");
|
|
616
|
-
return result(formatted, "tree-sitter", { count: astRefs.length });
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
return result(formatReferences(refs, ctx.cwd), "lsp", { count: refs.length });
|
|
620
|
-
}
|
|
621
|
-
|
|
622
|
-
if (action === "hover") {
|
|
623
|
-
if (requestedSymbol) {
|
|
624
|
-
const candidates = searchAstSymbols(ctx.cwd, {
|
|
625
|
-
name: requestedSymbol,
|
|
626
|
-
exactMatch: true,
|
|
627
|
-
currentFilePath: absPath,
|
|
628
|
-
});
|
|
629
|
-
if (candidates.length === 1) {
|
|
630
|
-
const candidate = candidates[0];
|
|
631
|
-
const candidatePath = path.isAbsolute(candidate.filePath)
|
|
632
|
-
? candidate.filePath
|
|
633
|
-
: path.resolve(ctx.cwd, candidate.filePath);
|
|
634
|
-
const candidateLine = Math.max(0, candidate.line - 1);
|
|
635
|
-
const candidateContent = candidatePath === absPath
|
|
636
|
-
? observedContent.toString("utf8")
|
|
637
|
-
: fs.readFileSync(candidatePath, "utf8");
|
|
638
|
-
const candidateLineText = candidateContent.split("\n")[candidateLine] || "";
|
|
639
|
-
const candidateColumn = Math.max(0, candidateLineText.indexOf(candidate.name));
|
|
640
|
-
const candidateClient = candidatePath === absPath
|
|
641
|
-
? client
|
|
642
|
-
: await lspMgr.getClientForFile(candidatePath, ctx.cwd);
|
|
643
|
-
if (candidateClient) {
|
|
644
|
-
const candidateHover = await candidateClient.hover(candidatePath, candidateLine, candidateColumn);
|
|
645
|
-
const candidateHoverText = formatHover(candidateHover);
|
|
646
|
-
if (candidateHover && !candidateHoverText.startsWith("No hover information")) {
|
|
647
|
-
return result(candidateHoverText, "lsp");
|
|
648
|
-
}
|
|
649
|
-
}
|
|
650
|
-
return result(
|
|
651
|
-
`[AST Hover] ${candidate.kind} ${candidate.name}\n${candidate.signature}\nDeclared in ${candidate.filePath}:${candidate.line}`,
|
|
652
|
-
"tree-sitter",
|
|
653
|
-
);
|
|
654
|
-
}
|
|
655
|
-
if (candidates.length > 1) {
|
|
656
|
-
return result(
|
|
657
|
-
`Multiple declarations found for '${requestedSymbol}':\n${candidates.slice(0, 10).map((candidate) => `- ${candidate.filePath}:${candidate.line} [${candidate.kind}] ${candidate.signature}`).join("\n")}`,
|
|
658
|
-
"tree-sitter",
|
|
659
|
-
{ count: candidates.length },
|
|
660
|
-
);
|
|
661
|
-
}
|
|
662
|
-
}
|
|
663
|
-
const h = await client.hover(absPath, line0, col0);
|
|
664
|
-
const hoverText = formatHover(h);
|
|
665
|
-
if (h && !hoverText.startsWith("No hover information")) {
|
|
666
|
-
return result(hoverText, "lsp");
|
|
667
|
-
}
|
|
668
|
-
const ext = path.extname(absPath).toLowerCase();
|
|
669
|
-
const nonCodeExts = [".md", ".markdown", ".json", ".jsonc", ".yaml", ".yml", ".toml", ".proto", ".txt"];
|
|
670
|
-
if (nonCodeExts.includes(ext)) {
|
|
671
|
-
return result(hoverText, "lsp");
|
|
672
|
-
}
|
|
673
|
-
|
|
674
|
-
// Tree-sitter local variable / parameter / symbol hover fallback
|
|
675
|
-
const sym = getSymbolUnderCursor();
|
|
676
|
-
const targetSym = sym.leaf || sym.full;
|
|
677
|
-
if (targetSym) {
|
|
678
|
-
const localHover = extractLocalSymbolHover(
|
|
679
|
-
absPath,
|
|
680
|
-
line0,
|
|
681
|
-
col0,
|
|
682
|
-
targetSym,
|
|
683
|
-
);
|
|
684
|
-
if (localHover) {
|
|
685
|
-
return result(localHover, "tree-sitter");
|
|
686
|
-
}
|
|
687
|
-
const astHits = searchAstSymbols(ctx.cwd, {
|
|
688
|
-
name: targetSym,
|
|
689
|
-
exactMatch: true,
|
|
690
|
-
});
|
|
691
|
-
if (astHits.length > 0) {
|
|
692
|
-
const hit = astHits[0];
|
|
693
|
-
return result(
|
|
694
|
-
`[Tree-sitter AST Hover - ${hit.kind} ${hit.name}]\n${hit.signature}\nDeclared in ${hit.filePath}:${hit.line}`,
|
|
695
|
-
"tree-sitter",
|
|
696
|
-
);
|
|
697
|
-
}
|
|
698
|
-
}
|
|
699
|
-
|
|
700
|
-
return result(hoverText, "lsp");
|
|
701
|
-
}
|
|
702
|
-
|
|
703
|
-
if (action === "document_symbols") {
|
|
704
|
-
const syms = await client.documentSymbol(absPath);
|
|
705
|
-
if (syms.length > 0) {
|
|
706
|
-
return result(formatDocumentSymbols(syms), "lsp", { count: syms.length });
|
|
707
|
-
}
|
|
708
|
-
const ext = path.extname(absPath).toLowerCase();
|
|
709
|
-
const nonCodeExts = [".md", ".markdown", ".json", ".jsonc", ".yaml", ".yml", ".toml", ".proto", ".txt"];
|
|
710
|
-
if (nonCodeExts.includes(ext)) {
|
|
711
|
-
return result(formatDocumentSymbols(syms), "lsp", { count: syms.length });
|
|
712
|
-
}
|
|
713
|
-
const docSyms = extractDocumentSymbols(absPath);
|
|
714
|
-
if (docSyms.length > 0) {
|
|
715
|
-
const formatted = docSyms
|
|
716
|
-
.map((s) => `• [${s.kind}] ${s.name} (line ${s.line}) - ${s.signature}`)
|
|
717
|
-
.join("\n");
|
|
718
|
-
return result(
|
|
719
|
-
`[Tree-sitter AST Document Symbols - ${docSyms.length} symbol(s)]\n${formatted}`,
|
|
720
|
-
"tree-sitter",
|
|
721
|
-
{ count: docSyms.length },
|
|
722
|
-
);
|
|
723
|
-
}
|
|
724
|
-
return result(
|
|
725
|
-
`[Tree-sitter AST] No symbols found in ${path.basename(absPath)}.`,
|
|
726
|
-
"tree-sitter",
|
|
727
|
-
{ count: 0 },
|
|
728
|
-
);
|
|
729
|
-
}
|
|
730
|
-
|
|
731
|
-
if (action === "diagnostics") {
|
|
732
|
-
const diagnosticResult = await client.getDiagnosticsResult(absPath);
|
|
733
|
-
if (diagnosticResult.diagnostics.length > 0) {
|
|
734
|
-
return result(
|
|
735
|
-
formatDiagnostics(diagnosticResult.diagnostics, absPath, ctx.cwd),
|
|
736
|
-
"lsp",
|
|
737
|
-
{ status: diagnosticResult.status, count: diagnosticResult.diagnostics.length },
|
|
738
|
-
);
|
|
739
|
-
}
|
|
740
|
-
|
|
741
|
-
const syn = checkSyntax(absPath);
|
|
742
|
-
if (!syn.valid) {
|
|
743
|
-
const status = syn.status || "failed";
|
|
744
|
-
return result(
|
|
745
|
-
`- [1:1] [${status.toUpperCase()}] Syntax validation: ${syn.error}`,
|
|
746
|
-
"syntax-check",
|
|
747
|
-
{ status },
|
|
748
|
-
);
|
|
749
|
-
}
|
|
750
|
-
|
|
751
|
-
if (diagnosticResult.status !== "clean") {
|
|
752
|
-
return result(
|
|
753
|
-
`[LSP ${diagnosticResult.status.toUpperCase()}] No definitive diagnostics result for ${path.relative(ctx.cwd, absPath)} (syntax validation passed).`,
|
|
754
|
-
"lsp",
|
|
755
|
-
{ status: diagnosticResult.status, count: 0 },
|
|
756
|
-
);
|
|
757
|
-
}
|
|
758
|
-
|
|
759
|
-
const relPath = path.relative(ctx.cwd, absPath).replace(/\\/g, "/") || absPath;
|
|
760
|
-
return result(`${relPath} clean`, "lsp", { status: "clean", count: 0 });
|
|
761
|
-
}
|
|
762
|
-
|
|
763
|
-
return result(`[LSP ERROR] Unsupported action: ${action}`, undefined, { error: "unsupported_action" }, true);
|
|
764
|
-
} catch (err: any) {
|
|
765
|
-
return result(`[LSP ERROR] ${err.message}`, undefined, { error: "query_failed" }, true);
|
|
766
|
-
}
|
|
767
|
-
},
|
|
768
|
-
renderCall(args: any, theme: any, context: any) {
|
|
769
|
-
const action = args?.action || "query";
|
|
770
|
-
const rawPath = args?.path || "";
|
|
771
|
-
const relPath = rawPath
|
|
772
|
-
? path.relative(context.cwd, rawPath) || rawPath
|
|
773
|
-
: "";
|
|
774
|
-
const pos = args?.line ? `:${args.line}:${args.character || 1}` : "";
|
|
775
|
-
return makeOutputText(
|
|
776
|
-
`${theme.fg("toolTitle", theme.bold("lsp"))} ${theme.fg("accent", `${action} ${relPath}${pos}`)}`,
|
|
777
|
-
);
|
|
778
|
-
},
|
|
779
|
-
renderResult(result: any, options: any, theme: any, context: any) {
|
|
780
|
-
if (context.isError) {
|
|
781
|
-
const errMsg =
|
|
782
|
-
result.content?.find((c: any) => c.type === "text")?.text ||
|
|
783
|
-
"LSP request failed";
|
|
784
|
-
return makeOutputText(`\n${theme.fg("error", errMsg)}`);
|
|
785
|
-
}
|
|
786
|
-
if (!options.expanded) {
|
|
787
|
-
return new Text("", 0, 0);
|
|
788
|
-
}
|
|
789
|
-
const output =
|
|
790
|
-
result.content?.find((c: any) => c.type === "text")?.text || "";
|
|
791
|
-
return makeOutputText(`\n${theme.fg("toolOutput", output)}`);
|
|
792
|
-
},
|
|
793
|
-
});
|
|
794
|
-
}
|