1package tools
2
3import (
4 "context"
5 _ "embed"
6 "fmt"
7 "log/slog"
8 "sort"
9 "strings"
10 "time"
11
12 "charm.land/fantasy"
13 "github.com/charmbracelet/crush/internal/csync"
14 "github.com/charmbracelet/crush/internal/fsext"
15 "github.com/charmbracelet/crush/internal/lsp"
16 "github.com/charmbracelet/x/powernap/pkg/lsp/protocol"
17)
18
19type DiagnosticsParams struct {
20 FilePath string `json:"file_path,omitempty" description:"The path to the file to get diagnostics for (leave w empty for project diagnostics)"`
21}
22
23const DiagnosticsToolName = "lsp_diagnostics"
24
25//go:embed diagnostics.md
26var diagnosticsDescription []byte
27
28func NewDiagnosticsTool(lspClients *csync.Map[string, *lsp.Client], workingDir string) fantasy.AgentTool {
29 return fantasy.NewAgentTool(
30 DiagnosticsToolName,
31 string(diagnosticsDescription),
32 func(ctx context.Context, params DiagnosticsParams, call fantasy.ToolCall) (fantasy.ToolResponse, error) {
33 if lspClients.Len() == 0 {
34 return fantasy.NewTextErrorResponse("no LSP clients available"), nil
35 }
36 notifyLSPs(ctx, lspClients, params.FilePath)
37 output := getDiagnostics(params.FilePath, lspClients, workingDir)
38 return fantasy.NewTextResponse(output), nil
39 })
40}
41
42func notifyLSPs(ctx context.Context, lsps *csync.Map[string, *lsp.Client], filepath string) {
43 if filepath == "" {
44 return
45 }
46 for client := range lsps.Seq() {
47 if !client.HandlesFile(filepath) {
48 continue
49 }
50 _ = client.OpenFileOnDemand(ctx, filepath)
51 _ = client.NotifyChange(ctx, filepath)
52 client.WaitForDiagnostics(ctx, 5*time.Second)
53 }
54}
55
56func getDiagnostics(filePath string, lsps *csync.Map[string, *lsp.Client], workingDir string) string {
57 fileDiagnostics := []string{}
58 projectDiagnostics := []string{}
59
60 for lspName, client := range lsps.Seq2() {
61 for location, diags := range client.GetDiagnostics() {
62 path, err := location.Path()
63 if err != nil {
64 slog.Error("Failed to convert diagnostic location URI to path", "uri", location, "error", err)
65 continue
66 }
67
68 // Skip diagnostics for files outside the working directory.
69 if !fsext.HasPrefix(path, workingDir) {
70 continue
71 }
72
73 isCurrentFile := path == filePath
74 for _, diag := range diags {
75 formattedDiag := formatDiagnostic(path, diag, lspName)
76 if isCurrentFile {
77 fileDiagnostics = append(fileDiagnostics, formattedDiag)
78 } else {
79 projectDiagnostics = append(projectDiagnostics, formattedDiag)
80 }
81 }
82 }
83 }
84
85 sortDiagnostics(fileDiagnostics)
86 sortDiagnostics(projectDiagnostics)
87
88 var output strings.Builder
89 writeDiagnostics(&output, "file_diagnostics", fileDiagnostics)
90 writeDiagnostics(&output, "project_diagnostics", projectDiagnostics)
91
92 if len(fileDiagnostics) > 0 || len(projectDiagnostics) > 0 {
93 fileErrors := countSeverity(fileDiagnostics, "Error")
94 fileWarnings := countSeverity(fileDiagnostics, "Warn")
95 projectErrors := countSeverity(projectDiagnostics, "Error")
96 projectWarnings := countSeverity(projectDiagnostics, "Warn")
97 output.WriteString("\n<diagnostic_summary>\n")
98 fmt.Fprintf(&output, "Current file: %d errors, %d warnings\n", fileErrors, fileWarnings)
99 fmt.Fprintf(&output, "Project: %d errors, %d warnings\n", projectErrors, projectWarnings)
100 output.WriteString("</diagnostic_summary>\n")
101 }
102
103 out := output.String()
104 slog.Debug("Diagnostics", "output", out)
105 return out
106}
107
108func writeDiagnostics(output *strings.Builder, tag string, in []string) {
109 if len(in) == 0 {
110 return
111 }
112 output.WriteString("\n<" + tag + ">\n")
113 if len(in) > 10 {
114 output.WriteString(strings.Join(in[:10], "\n"))
115 fmt.Fprintf(output, "\n... and %d more diagnostics", len(in)-10)
116 } else {
117 output.WriteString(strings.Join(in, "\n"))
118 }
119 output.WriteString("\n</" + tag + ">\n")
120}
121
122func sortDiagnostics(in []string) []string {
123 sort.Slice(in, func(i, j int) bool {
124 iIsError := strings.HasPrefix(in[i], "Error")
125 jIsError := strings.HasPrefix(in[j], "Error")
126 if iIsError != jIsError {
127 return iIsError // Errors come first
128 }
129 return in[i] < in[j] // Then alphabetically
130 })
131 return in
132}
133
134func formatDiagnostic(pth string, diagnostic protocol.Diagnostic, source string) string {
135 severity := "Info"
136 switch diagnostic.Severity {
137 case protocol.SeverityError:
138 severity = "Error"
139 case protocol.SeverityWarning:
140 severity = "Warn"
141 case protocol.SeverityHint:
142 severity = "Hint"
143 }
144
145 location := fmt.Sprintf("%s:%d:%d", pth, diagnostic.Range.Start.Line+1, diagnostic.Range.Start.Character+1)
146
147 sourceInfo := ""
148 if diagnostic.Source != "" {
149 sourceInfo = diagnostic.Source
150 } else if source != "" {
151 sourceInfo = source
152 }
153
154 codeInfo := ""
155 if diagnostic.Code != nil {
156 codeInfo = fmt.Sprintf("[%v]", diagnostic.Code)
157 }
158
159 tagsInfo := ""
160 if len(diagnostic.Tags) > 0 {
161 tags := []string{}
162 for _, tag := range diagnostic.Tags {
163 switch tag {
164 case protocol.Unnecessary:
165 tags = append(tags, "unnecessary")
166 case protocol.Deprecated:
167 tags = append(tags, "deprecated")
168 }
169 }
170 if len(tags) > 0 {
171 tagsInfo = fmt.Sprintf(" (%s)", strings.Join(tags, ", "))
172 }
173 }
174
175 return fmt.Sprintf("%s: %s [%s]%s%s %s",
176 severity,
177 location,
178 sourceInfo,
179 codeInfo,
180 tagsInfo,
181 diagnostic.Message)
182}
183
184func countSeverity(diagnostics []string, severity string) int {
185 count := 0
186 for _, diag := range diagnostics {
187 if strings.HasPrefix(diag, severity) {
188 count++
189 }
190 }
191 return count
192}