import { stat } from 'node:fs/promises'; import { isAbsolute, relative, resolve, sep } from 'node:path'; import { pathToFileURL } from 'node:url'; import { fileURLToPath } from 'node:url'; import { z } from 'zod'; import { getWorkingDir } from '../../bootstrap/workingDir.js'; import type { AgentRuntimeContext } from '../../runtime/agentRuntimeContext.js'; import type { Tool, ToolCallContext, ToolResult } from '../../types.js'; import { toToolParameters } from '../../utils/zodToJson.js'; import { DEFAULT_MAX_RESULT_SIZE_CHARS } from '../types.js'; import { discoverLspServers, lspAvailabilitySignature } from './config.js'; import { getLspManager } from './service.js'; const positionOperations = new Set([ 'goToDefinition', 'findReferences', 'hover', 'goToImplementation', 'incomingCalls', 'outgoingCalls', ]); const inputSchema = z .object({ operation: z.enum([ 'goToDefinition', 'findReferences', 'hover', 'documentSymbols', 'workspaceSymbols', 'goToImplementation', 'incomingCalls', 'outgoingCalls', 'diagnostics', ]), file_path: z.string().min(1), line: z .number() .int() .positive() .optional() .describe('1-based source line for position operations'), character: z .number() .int() .positive() .optional() .describe('1-based UTF-16 character for position operations'), query: z.string().optional().describe('Symbol query for workspaceSymbols'), limit: z .number() .int() .min(1) .max(500) .optional() .describe('Maximum formatted results, default 200'), output_format: z.enum(['compact', 'json']).default('compact').optional(), }) .superRefine((input, context) => { if ( positionOperations.has(input.operation) && (!input.line || !input.character) ) { context.addIssue({ code: z.ZodIssueCode.custom, message: `${input.operation} requires line and character`, }); } if (input.operation === 'workspaceSymbols' && !input.query?.trim()) { context.addIssue({ code: z.ZodIssueCode.custom, path: ['query'], message: 'workspaceSymbols requires a non-empty query', }); } }); type LspInput = z.infer; export function formatLspJson(value: unknown, limit: number): string { if (value == null) return 'null'; const items = Array.isArray(value) ? value.slice(0, limit) : value; const text = JSON.stringify(items, null, 2); if (text.length <= DEFAULT_MAX_RESULT_SIZE_CHARS && (!Array.isArray(value) || value.length <= limit)) return text; if (Array.isArray(items)) { // Keep complete items and report omissions; never cut serialized JSON midway. const result: unknown[] = []; let used = 100; for (const item of items) { used += JSON.stringify(item).length + 1; if (used > DEFAULT_MAX_RESULT_SIZE_CHARS) break; result.push(item); } return JSON.stringify({ truncated: true, total: (value as unknown[]).length, items: result }); } return JSON.stringify({ truncated: true, reason: 'LSP result exceeds output character limit' }); } function compactSemantic(value: unknown, cwd: string, limit: number): string { if (value == null) return 'No results.'; const rows: string[] = []; const walk = (item: any, label?: string) => { if (item == null) return; if (Array.isArray(item)) { item.forEach((v) => walk(v, label)); return; } if (typeof item !== 'object') { rows.push(String(item)); return; } const location = item.location ?? item.fromRanges?.[0] ?? item; const uri = location.uri ?? location.targetUri ?? item.uri; const range = location.range ?? location.targetSelectionRange ?? item.range ?? item.selectionRange; let where = ''; if (typeof uri === 'string') { let path = uri; try { path = uri.startsWith('file:') ? fileURLToPath(uri) : uri; } catch {} const rel = relative(resolve(cwd), path); where = (rel && !rel.startsWith('..') ? rel : path).split(sep).join('/'); } if (range?.start) where += `:${Number(range.start.line) + 1}:${Number(range.start.character) + 1}`; const message = item.message ?? item.name ?? item.detail ?? item.kind ?? label; const severity = item.severity ? `[${['', 'error', 'warning', 'info', 'hint'][item.severity] ?? item.severity}] ` : ''; const code = item.code !== undefined ? `(${String(item.code)}) ` : ''; if (where || message) rows.push( `${severity}${where || ''}${message == null ? '' : ` — ${code}${typeof message === 'string' ? message : JSON.stringify(message)}`}`, ); if (item.contents) { const contents = Array.isArray(item.contents) ? item.contents : [item.contents]; for (const c of contents) rows.push( typeof c === 'string' ? c : typeof c?.value === 'string' ? c.value : JSON.stringify(c), ); } if (item.from) walk(item.from, 'caller'); if (item.to) walk(item.to, 'callee'); if (Array.isArray(item.children)) item.children.forEach((v: any) => walk(v)); }; walk(value); const unique = [...new Set(rows)].sort(); const selected = unique.slice(0, limit); let text = selected.join('\n') || 'No results.'; if (unique.length > selected.length) text += `\n... (${unique.length - selected.length} more; total=${unique.length})`; return text.length > DEFAULT_MAX_RESULT_SIZE_CHARS ? `${text.slice(0, DEFAULT_MAX_RESULT_SIZE_CHARS)}\n... (LSP result truncated)` : text; } async function call( input: LspInput, cwd = getWorkingDir(), signal?: AbortSignal, ): Promise { if (signal?.aborted) return { ok: false, error: 'aborted' }; const filePath = resolve(cwd, input.file_path); const rel = relative(resolve(cwd), filePath); if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) { return { ok: false, error: `LSP 只处理当前工作区内的文件:${filePath}` }; } const info = await stat(filePath).catch(() => null); if (!info?.isFile()) return { ok: false, error: `LSP file does not exist: ${filePath}` }; if (info.size > 10_000_000) return { ok: false, error: 'LSP refuses files larger than 10 MB' }; const server = getLspManager(cwd).serverFor(filePath); if (!server) return { ok: false, error: `No configured LSP server handles ${filePath}` }; try { await server.openFile(filePath, signal); const request = (method: string, params: unknown) => server.request(method, params, signal); const uri = pathToFileURL(filePath).href; const position = { line: (input.line ?? 1) - 1, character: (input.character ?? 1) - 1, }; let result: unknown; switch (input.operation) { case 'goToDefinition': result = await request('textDocument/definition', { textDocument: { uri }, position, }); break; case 'findReferences': result = await request('textDocument/references', { textDocument: { uri }, position, context: { includeDeclaration: true }, }); break; case 'hover': result = await request('textDocument/hover', { textDocument: { uri }, position, }); break; case 'documentSymbols': result = await request('textDocument/documentSymbol', { textDocument: { uri }, }); break; case 'workspaceSymbols': result = await request('workspace/symbol', { query: input.query, }); break; case 'goToImplementation': result = await request('textDocument/implementation', { textDocument: { uri }, position, }); break; case 'incomingCalls': case 'outgoingCalls': { const prepared = await request( 'textDocument/prepareCallHierarchy', { textDocument: { uri }, position }, ); const item = prepared?.[0]; result = item ? await request(`callHierarchy/${input.operation}`, { item }) : []; break; } case 'diagnostics': { // Give servers a brief opportunity to publish diagnostics after didOpen. await new Promise((resolvePromise) => setTimeout(resolvePromise, 100)); if (!server.diagnostics.has(uri)) return { ok: true, content: input.output_format === 'json' ? JSON.stringify({ status: 'pending', diagnostics: null }) : '语言服务器尚未发布此文件的诊断;不能据此断言无错误。可稍后查询,或运行项目类型检查/编译。', }; result = server.diagnostics.get(uri); break; } } return { ok: true, content: input.output_format === 'json' ? formatLspJson(result, input.limit ?? 200) : compactSemantic(result, cwd, input.limit ?? 200), }; } catch (error) { return { ok: false, error: `LSP ${input.operation} failed: ${(error as Error).message}`, }; } } export const lspTool: Tool = { name: 'LSP', description: `Semantic code intelligence backed by a detected local language server. - Use LSP for definitions, references, hover/type information, symbols, implementations, call relationships, and diagnostics. - Use Grep for literal or regular-expression text search; it is not a substitute for semantic navigation. - line and character are 1-based. Results are local evidence and should be verified by reading relevant source before editing.`, inputSchema, parameters: toToolParameters(inputSchema), isReadOnly: true, isConcurrencySafe: true, maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, resolveAvailability(runtime: AgentRuntimeContext) { const servers = discoverLspServers(runtime.cwd); return { available: servers.length > 0, signature: lspAvailabilitySignature(runtime.cwd, servers), }; }, call: (input, signal) => call(input, undefined, signal), callWithContext: (input, signal, context: ToolCallContext) => call(input, context.cwd, signal), };