import path from "node:path"; import {defineTool} from "@earendil-works/pi-coding-agent"; import {Type} from "typebox"; import {commandExists, commandPathValue} from "../command.js"; import { COMMON_SKIP_DIRECTORIES, loadRuntime, normalizeExtension, } from "../config.js"; import {collectFiles, resolveRoot} from "../files.js"; import {lspAutoInstallEnabled} from "../lsp-install.js"; import { DEFAULT_FILE_LIMIT, DEFAULT_MAX_DIAGNOSTICS, MAX_PARALLEL_LSP_LANES, runDiagnostics, textFromResult, textResult, withConcurrencyLimit, } from "../lsp-runner.js"; import {filterAdapters} from "../routes.js"; import {dispatchRunnerRoutes, filterRunners,} from "../runners/registry.js"; import type {RunnerResult} from "../types.js"; import {ServerParameter} from "./lsp-diagnostics.js"; const STATUS_KEY = "lsp-checks"; /** 状态栏 key。LSP 与 CLI 两条通道共用 lsp-checks 前缀,但服务器和工具会重名 * (biome / ruff / ty 三处两边都配了),CLI 一路加 `cli:` 段区分——否则同一路 * key 被两条 lane 同时用,先收尾的那条会把另一条还在跑的状态清掉。 */ export function checksLaneStatusKey(lane: "lsp" | "cli", name: string): string { return `${STATUS_KEY}:${lane === "cli" ? "cli:" : ""}${name}`; } // Unified check entry point: one tool, both lanes. // - LSP lane: configured default language servers (pull/push diagnostics, spawn-per-call). // - Runner lane: builtin CLI runners (ruff, biome, shellcheck) selected by file // extension, executed in parallel through the runner registry. export const lspChecksTool = defineTool({ name: "lsp_checks", label: "Checks: Run", description: "Run all matching checks (LSP servers and builtin CLI runners such as ruff/biome/shellcheck) over files or directories, aggregated into one report. " + "Superset of lsp_diagnostics (LSP-only lane) plus the CLI runner lane.", promptSnippet: "Run all matching LSP and CLI checks over files", promptGuidelines: [ "Use lsp_checks for one-call aggregated feedback before finishing an edit.", "Pass explicit paths when the workspace is large: the file walk defaults to the workspace root and is capped at limit (default 50) files.", "Use the runners parameter to restrict CLI runners, or the server parameter to restrict the LSP lane.", ], parameters: Type.Object({ paths: Type.Optional( Type.Array(Type.String(), { description: "Files or directories to check. Defaults to the workspace root.", }), ), root: Type.Optional( Type.String({description: "Workspace root. Defaults to cwd."}), ), limit: Type.Optional( Type.Number({ description: "Maximum files to collect per LSP server / runner. Defaults to 50.", }), ), server: ServerParameter, runners: Type.Optional( Type.Union([Type.String(), Type.Array(Type.String())], { description: "Optional CLI runner name(s) (e.g. ruff, biome, shellcheck) to restrict the runner lane. Defaults to all builtin runners.", }), ), autoInstall: Type.Optional( Type.Boolean({ description: "Set false to skip best-effort auto-install of missing LSP servers and CLI tools. Defaults to true.", }), ), maxDiagnostics: Type.Optional( Type.Number({ description: "Maximum diagnostics rendered per lane/tool. Extra diagnostics are truncated with a count. Defaults to 200.", }), ), }), async execute(_toolCallId, params, signal, _onUpdate, ctx) { const root = resolveRoot(params.root); const {adapters, runners, timeoutMs} = loadRuntime(); const limit = params.limit ?? DEFAULT_FILE_LIMIT; const maxDiagnostics = params.maxDiagnostics ?? DEFAULT_MAX_DIAGNOSTICS; // Validate + normalize up front: unknown or blank server names must fail // loudly (same contract as the runners lane), never degrade to "no LSP ran". const requestedServers = params.server === undefined ? undefined : filterAdapters(adapters, params.server).map( (adapter) => adapter.name, ); // De-duplication with the runner lane: ruff/biome exist both as LSP // servers and as CLI runners, and running both reports every finding // twice. When the CLI runner for a server is actually runnable, the // LSP lane defers to it — unless the caller explicitly asked for that // server. A runners restriction that excludes the runner leaves the // LSP lane in charge. autoInstall-only runners do not count as active // here: a first call that triggers an install must not simultaneously // hide the LSP lane, or a failed install would silently drop the check. const selectedRunners = filterRunners(runners, params.runners); const activeRunnerIds = new Set( selectedRunners .filter( (runner) => runner.command !== undefined && commandExists(runner.command, root, commandPathValue(undefined)), ) .map((runner) => runner.id), ); // Per-lane file collection: every server/runner gets its own limit // (matching lsp_diagnostics), instead of one shared union budget that // lets a directory full of .ts files starve the .py checks. Lanes with // identical file policies share one walk through the cache. const collectCache = new Map(); const unionFiles = new Set(); let anyLaneHitLimit = false; const collectFor = ( extensions: string[], skipDirectories: Set, ): string[] => { const key = JSON.stringify([ extensions, [...skipDirectories].sort((left, right) => left.localeCompare(right), ), ]); let files = collectCache.get(key); if (!files) { // Normalize like adapter.isSupportedFile does, so a // non-dotted extension in config matches here too. const extensionSet = new Set(extensions.map(normalizeExtension)); files = collectFiles( (filePath) => extensionSet.has(path.extname(filePath)), skipDirectories, root, params.paths, limit, ); collectCache.set(key, files); if (files.length >= limit) anyLaneHitLimit = true; } for (const file of files) unionFiles.add(file); return files; }; // LSP lane tasks: default servers that are runnable, deduplicated // against the runner lane, and capped at MAX_PARALLEL_LSP_LANES. const delegatedToRunners: string[] = []; const lspTasks = adapters .filter((adapter) => { if (requestedServers && !requestedServers.includes(adapter.name)) return false; if (!adapter.isDefault) return false; if ( !requestedServers && activeRunnerIds.has(adapter.name) && selectedRunners.some((runner) => runner.id === adapter.name) ) { delegatedToRunners.push(adapter.name); return false; } if (lspAutoInstallEnabled(adapter, params.autoInstall)) return true; const command = adapter.defaultCommand; return commandExists( command.command, root, commandPathValue(adapter.env), ); }) .map( (adapter) => { // Collected eagerly, before the empty-union check below: the // check must see every lane's files, not an unexecuted lazy // task list. const matchedFiles = collectFor( adapter.extensions, adapter.skipDirectories, ); return async (): Promise<{ name: string; section: string; failed: boolean; } | null> => { if (matchedFiles.length === 0) return null; try { const result = await runDiagnostics( adapter, { root, files: matchedFiles, limit, autoInstall: params.autoInstall, maxDiagnostics, }, timeoutMs, signal, ctx, checksLaneStatusKey("lsp", adapter.name), ); return { name: adapter.name, section: `${adapter.name} LSP\n\n${textFromResult(result)}`, failed: false, }; } catch (error: unknown) { return { name: adapter.name, section: `${adapter.name} LSP failed: ${error instanceof Error ? error.message : String(error)}`, failed: true, }; } }; }, ); // Runner lane files are collected eagerly for the same reason. const routes = selectedRunners .map((runner) => ({ runner, files: collectFor(runner.extensions, COMMON_SKIP_DIRECTORIES), })) .filter((route) => route.files.length > 0); // Union of every lane's files, for the header and the empty check. const files = [...unionFiles].sort((left, right) => left.localeCompare(right), ); if (files.length === 0) { return textResult("No supported files found to check.", { root, files: [], results: [], }); } const limitNotice = anyLaneHitLimit ? ` File collection stopped at the limit of ${limit} per lane; pass explicit paths or raise limit to cover more files.` : ""; const lspLanes = ( await withConcurrencyLimit(lspTasks, MAX_PARALLEL_LSP_LANES) ).filter((lane): lane is NonNullable => lane !== null); const lspSections = lspLanes.map((lane) => lane.section); const lspServersRun = lspLanes.map((lane) => lane.name); const lspFailures = lspLanes.filter((lane) => lane.failed); const runnerResults = await dispatchRunnerRoutes(routes, { root, signal, defaultTimeoutMs: timeoutMs, // CLI 通道与 LSP 通道用同一套状态栏:一路一个 key,安装与运行两段 // 文案由 runner 自己拼,清理归派发层(抛错/取消也不留残影)。 reportStatus: (runnerId, text) => { try { ctx.ui.setStatus(checksLaneStatusKey("cli", runnerId), text); } catch { // 状态栏不可用不该拖垮检查本身 } }, }); const sections = [ ...lspSections, ...runnerResults.map((result) => formatRunnerResult(result, maxDiagnostics), ), ].join("\n\n---\n\n"); const summary = summarize(runnerResults); // Failed lanes stay visible in the header, not only in the body sections. const lspSummary = lspLanes .map((lane) => (lane.failed ? `${lane.name} (failed)` : lane.name)) .join(", "); const header = `lsp_checks: ${files.length} file(s); CLI runners: ${summary.succeeded} succeeded, ${summary.failed} failed, ${summary.skipped} skipped, ${summary.diagnostics} diagnostic(s); LSP servers: ${lspSummary || "none"}.${limitNotice}`; return textResult(`${header}\n\n${sections}`, { root, files, runners: runnerResults.map((result) => ({ tool: result.tool, status: result.status, files: result.files.length, diagnostics: result.diagnostics.length, durationMs: result.durationMs, failureKind: result.failureKind, failureMessage: result.failureMessage, skipReason: result.skipReason, })), lspServers: lspServersRun, lspFailures: lspFailures.map((lane) => lane.name), lspServersCoveredByRunners: delegatedToRunners, }); }, }); export function formatRunnerResult( result: RunnerResult, maxDiagnostics: number = DEFAULT_MAX_DIAGNOSTICS, ) { const lines = [ `${result.tool}: ${result.status} (${result.diagnostics.length} diagnostic(s), ${result.durationMs}ms)${result.autoInstalled ? " [auto-installed]" : ""}`, ]; if (result.status === "skipped") { const reason = result.skipReason === "unavailable" ? "command not found on PATH" : "no files matched"; const installNote = result.installDetail ? ` Auto-install attempts: ${result.installDetail}.` : ""; return [...lines, ` skipped: ${reason}.${installNote}`].join("\n"); } if (result.failureKind) { return [ ...lines, ` failure (${result.failureKind}): ${result.failureMessage ?? "unknown"}`, ].join("\n"); } if (result.diagnostics.length === 0) return [...lines, " no diagnostics."].join("\n"); const cap = Math.max(1, Math.floor(maxDiagnostics)); const truncated = result.diagnostics.length - Math.min(result.diagnostics.length, cap); for (const diagnostic of result.diagnostics.slice(0, cap)) { const rule = diagnostic.rule ? `(${diagnostic.rule})` : ""; const fixable = diagnostic.fixable ? " [fixable]" : ""; lines.push( `${diagnostic.filePath}:${diagnostic.line}:${diagnostic.column}: ${diagnostic.severity} ${diagnostic.tool}${rule}: ${diagnostic.message}${fixable}`, ); } if (truncated > 0) lines.push( `… ${truncated} more diagnostics truncated (maxDiagnostics=${cap}).`, ); return lines.join("\n"); } function summarize(results: RunnerResult[]) { return { succeeded: results.filter((result) => result.status === "succeeded").length, failed: results.filter((result) => result.status === "failed").length, skipped: results.filter((result) => result.status === "skipped").length, diagnostics: results.reduce( (total, result) => total + result.diagnostics.length, 0, ), }; }