lsp_diagnostics.go RawHistoryFolder
1package tools
2
3import (
4 "context"
5 "errors"
6 "strings"
7 "time"
8
9 "github.com/bnema/zut/packages/agent/lsp"
10 "github.com/bnema/zut/packages/core"
11 "github.com/bnema/zut/packages/provider"
12)
13
14const writeDiagnosticsTimeout = 2 * time.Second
15
16// CloseLSPManagers closes every manager referenced by the registry. Write,
17// edit, and lsp share one manager in normal runs, so de-duplicate pointers
18// before closing them. This is used by mode owners when an agent or registry
19// is replaced; LSP processes should not outlive the session that created them.
20func CloseLSPManagers(reg core.Registry) error {
21 managers := make(map[*lsp.Manager]struct{})
22 for _, tool := range reg {
23 switch value := tool.(type) {
24 case *LSPTool:
25 if value != nil && value.Manager != nil {
26 managers[value.Manager] = struct{}{}
27 }
28 case *WriteTool:
29 if value != nil && value.LSP != nil {
30 managers[value.LSP] = struct{}{}
31 }
32 case *EditTool:
33 if value != nil && value.LSP != nil {
34 managers[value.LSP] = struct{}{}
35 }
36 }
37 }
38 var firstErr error
39 for manager := range managers {
40 if err := manager.Close(); err != nil && firstErr == nil {
41 firstErr = err
42 }
43 }
44 return firstErr
45}
46
47// attachWriteDiagnostics performs a bounded post-write diagnostics pass. A
48// failed or slow language server must never turn a successful filesystem
49// mutation into a failed tool call, so callers only attach diagnostics that
50// were actually returned before the short budget expired.
51func attachWriteDiagnostics(ctx context.Context, cwd, path string, manager *lsp.Manager, result *core.ToolResult) {
52 if manager == nil || result == nil {
53 return
54 }
55 if ctx == nil {
56 ctx = context.Background()
57 }
58 diagnosticsCtx, cancel := context.WithTimeout(ctx, writeDiagnosticsTimeout)
59 defer cancel()
60 diagnostics, err := manager.Diagnostics(diagnosticsCtx, cwd, path)
61 if err != nil {
62 if details, ok := result.Details.(map[string]any); ok {
63 status := "unavailable"
64 switch {
65 case errors.Is(err, context.DeadlineExceeded):
66 status = "timeout"
67 case errors.Is(err, context.Canceled):
68 status = "canceled"
69 }
70 details["diagnostics_status"] = status
71 details["diagnostics_error"] = err.Error()
72 }
73 return
74 }
75 diagnostics = manager.ReduceDiagnostics(cwd, path, diagnostics)
76 if len(diagnostics) == 0 {
77 return
78 }
79 summary := lsp.SummarizeDiagnostics(diagnostics, cwd, 8)
80 if strings.TrimSpace(summary) == "" || summary == "No diagnostics." {
81 return
82 }
83 for index, block := range result.Content {
84 text, ok := block.(provider.TextBlock)
85 if !ok {
86 continue
87 }
88 text.Text = strings.TrimRight(text.Text, "\n") + "\n\n" + summary + "\n"
89 result.Content[index] = text
90 break
91 }
92 if details, ok := result.Details.(map[string]any); ok {
93 details["diagnostics"] = diagnostics
94 details["diagnostics_summary"] = summary
95 }
96}