@@ -0,0 +1,367 @@
1+package lsp
2+
3+import (
4+ "context"
5+ "fmt"
6+ "io"
7+ "log/slog"
8+ "os"
9+ "os/exec"
10+ "path/filepath"
11+ "sync"
12+ "time"
13+
14+ powernapconfig "github.com/charmbracelet/x/powernap/pkg/config"
15+ powernap "github.com/charmbracelet/x/powernap/pkg/lsp"
16+ "github.com/charmbracelet/x/powernap/pkg/lsp/protocol"
17+ "github.com/rs/zerolog/log"
18+)
19+
20+// skipAutoStart lists generic commands that should not be auto-started.
21+// These interpreters/runners may trigger package downloads or run wrong binaries.
22+var skipAutoStart = map[string]bool{
23+ "npx": true,
24+ "node": true,
25+ "python": true,
26+ "python3": true,
27+ "java": true,
28+ "ruby": true,
29+ "perl": true,
30+ "dotnet": true,
31+ "bun": true,
32+}
33+
34+// DiagCallback is called when diagnostics change for a file.
35+// absPath is the filesystem path; lines maps 0-indexed line numbers to max severity.
36+type DiagCallback func(absPath string, lines map[int]int)
37+
38+// Manager manages LSP server lifecycles keyed by server name.
39+type Manager struct {
40+ cfgMgr *powernapconfig.Manager
41+
42+ mu sync.Mutex
43+ clients map[string]*Client // serverName -> client
44+ broken map[string]bool // servers that failed to start
45+
46+ callback DiagCallback
47+}
48+
49+// NewManager creates a manager with powernap's built-in server defaults.
50+func NewManager() *Manager {
51+ // Silence powernap's slog output — it writes to stderr which the TUI owns.
52+ slog.SetDefault(slog.New(slog.NewTextHandler(io.Discard, nil)))
53+
54+ cm := powernapconfig.NewManager()
55+ _ = cm.LoadDefaults()
56+ return &Manager{
57+ cfgMgr: cm,
58+ clients: make(map[string]*Client),
59+ broken: make(map[string]bool),
60+ }
61+}
62+
63+// SetCallback sets the function called when diagnostics change.
64+func (m *Manager) SetCallback(cb DiagCallback) {
65+ m.mu.Lock()
66+ defer m.mu.Unlock()
67+ m.callback = cb
68+}
69+
70+// TouchFile ensures the right LSP servers are running for this file and
71+// sends didOpen/didChange. Non-blocking — errors are logged, not returned.
72+func (m *Manager) TouchFile(ctx context.Context, absPath string) {
73+ clients := m.ensureClients(ctx, absPath)
74+ for _, c := range clients {
75+ if err := c.openFile(ctx, absPath); err != nil {
76+ log.Error().Err(err).Str("server", c.serverID).Msg("lsp: touchFile openFile")
77+ }
78+ }
79+}
80+
81+// NotifyAndWait notifies relevant LSP servers of a file change and waits for
82+// diagnostics. Returns aggregated diagnostics across all matching servers.
83+func (m *Manager) NotifyAndWait(ctx context.Context, absPath string, timeout time.Duration) []protocol.Diagnostic {
84+ clients := m.ensureClients(ctx, absPath)
85+ if len(clients) == 0 {
86+ return nil
87+ }
88+
89+ var all []protocol.Diagnostic
90+ for _, c := range clients {
91+ diags, err := c.notifyAndWait(ctx, absPath, timeout)
92+ if err != nil {
93+ log.Error().Err(err).Str("server", c.serverID).Msg("lsp: notifyAndWait")
94+ continue
95+ }
96+ log.Debug().Str("server", c.serverID).Int("count", len(diags)).Str("file", absPath).Msg("lsp: diagnostics received")
97+ all = append(all, diags...)
98+ }
99+
100+ log.Debug().Int("total", len(all)).Str("file", absPath).Msg("lsp: aggregated diagnostics")
101+
102+ // Fire callback once with aggregated diagnostics from all servers.
103+ m.mu.Lock()
104+ cb := m.callback
105+ m.mu.Unlock()
106+ if cb != nil {
107+ cb(absPath, diagLineSeverities(all))
108+ }
109+
110+ return all
111+}
112+
113+// StopAll gracefully shuts down all running LSP servers.
114+func (m *Manager) StopAll(ctx context.Context) {
115+ m.mu.Lock()
116+ clients := make([]*Client, 0, len(m.clients))
117+ for _, c := range m.clients {
118+ clients = append(clients, c)
119+ }
120+ m.mu.Unlock()
121+
122+ for _, c := range clients {
123+ if err := c.close(ctx); err != nil {
124+ log.Error().Err(err).Str("server", c.serverID).Msg("lsp: stopAll")
125+ }
126+ }
127+}
128+
129+// serverToStart holds info needed to start an LSP server outside the lock.
130+type serverToStart struct {
131+ name string
132+ cfg *powernapconfig.ServerConfig
133+ root string
134+ cmdPath string
135+}
136+
137+// ensureClients finds or starts LSP servers for the given file.
138+func (m *Manager) ensureClients(ctx context.Context, absPath string) []*Client {
139+ lang := string(powernap.DetectLanguage(absPath))
140+ if lang == "" {
141+ log.Debug().Str("file", absPath).Msg("lsp: unknown language, skipping")
142+ return nil
143+ }
144+
145+ log.Debug().Str("file", absPath).Str("lang", lang).Msg("lsp: ensureClients")
146+
147+ servers := m.cfgMgr.GetServers()
148+
149+ // Phase 1: under lock, collect existing clients and identify servers to start.
150+ m.mu.Lock()
151+ var result []*Client
152+ var pending []serverToStart
153+
154+ for name, cfg := range servers {
155+ if !matchesFileType(cfg, lang) {
156+ continue
157+ }
158+ if m.broken[name] {
159+ continue
160+ }
161+ if c, ok := m.clients[name]; ok {
162+ result = append(result, c)
163+ continue
164+ }
165+ if skipAutoStart[cfg.Command] {
166+ m.broken[name] = true
167+ continue
168+ }
169+ cmdPath := lookPath(cfg.Command)
170+ if cmdPath == "" {
171+ m.broken[name] = true
172+ continue
173+ }
174+ root := findRoot(absPath, cfg.RootMarkers)
175+ if root == "" {
176+ root, _ = os.Getwd()
177+ }
178+ pending = append(pending, serverToStart{name: name, cfg: cfg, root: root, cmdPath: cmdPath})
179+ }
180+ m.mu.Unlock()
181+
182+ // Phase 2: start servers without holding the lock (blocking I/O).
183+ for _, s := range pending {
184+ c, err := m.startClient(ctx, s.name, s.cfg, s.root, s.cmdPath)
185+
186+ m.mu.Lock()
187+ if err != nil {
188+ log.Error().Err(err).Str("server", s.name).Msg("lsp: start failed")
189+ m.broken[s.name] = true
190+ } else {
191+ m.clients[s.name] = c
192+ result = append(result, c)
193+ }
194+ m.mu.Unlock()
195+ }
196+
197+ return result
198+}
199+
200+// startClient spawns and initializes a single LSP server. Must be called with m.mu held.
201+func (m *Manager) startClient(ctx context.Context, name string, cfg *powernapconfig.ServerConfig, root, cmdPath string) (*Client, error) {
202+ rootURI := string(protocol.URIFromPath(root))
203+
204+ pcfg := powernap.ClientConfig{
205+ Command: cmdPath,
206+ Args: cfg.Args,
207+ RootURI: rootURI,
208+ Environment: cfg.Environment,
209+ Settings: cfg.Settings,
210+ InitOptions: cfg.InitOptions,
211+ WorkspaceFolders: []protocol.WorkspaceFolder{
212+ {URI: rootURI, Name: filepath.Base(root)},
213+ },
214+ }
215+
216+ c, err := newClient(name, pcfg)
217+ if err != nil {
218+ return nil, err
219+ }
220+
221+ initCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
222+ defer cancel()
223+
224+ if err := c.initialize(initCtx); err != nil {
225+ _ = c.close(ctx)
226+ return nil, fmt.Errorf("initialize: %w", err)
227+ }
228+
229+ log.Info().Str("server", name).Str("root", root).Str("cmd", cmdPath).Msg("lsp: server started")
230+ return c, nil
231+}
232+
233+// matchesFileType checks if a server config handles the given language ID.
234+func matchesFileType(cfg *powernapconfig.ServerConfig, lang string) bool {
235+ for _, ft := range cfg.FileTypes {
236+ if ft == lang {
237+ return true
238+ }
239+ }
240+ return false
241+}
242+
243+// findRoot walks up from the file looking for any of the root markers.
244+func findRoot(absPath string, markers []string) string {
245+ dir := filepath.Dir(absPath)
246+ for {
247+ for _, marker := range markers {
248+ matches, _ := filepath.Glob(filepath.Join(dir, marker))
249+ if len(matches) > 0 {
250+ return dir
251+ }
252+ }
253+ parent := filepath.Dir(dir)
254+ if parent == dir {
255+ return ""
256+ }
257+ dir = parent
258+ }
259+}
260+
261+// diagLineSeverities converts a diagnostic slice to a line->severity map.
262+// Only tracks errors (1) and warnings (2). Lower severity number wins.
263+func diagLineSeverities(diags []protocol.Diagnostic) map[int]int {
264+ if len(diags) == 0 {
265+ return nil
266+ }
267+ lines := make(map[int]int)
268+ for _, d := range diags {
269+ sev := int(d.Severity)
270+ if sev != SeverityError && sev != SeverityWarning {
271+ continue
272+ }
273+ line := int(d.Range.Start.Line) // 0-indexed
274+ if existing, ok := lines[line]; !ok || sev < existing {
275+ lines[line] = sev
276+ }
277+ }
278+ return lines
279+}
280+
281+// FormatDiagnostics formats diagnostics as a text block for LLM tool responses.
282+// Returns empty string if no errors or warnings.
283+func FormatDiagnostics(displayPath string, diags []protocol.Diagnostic) string {
284+ if len(diags) == 0 {
285+ return ""
286+ }
287+
288+ var buf []byte
289+ count := 0
290+ for _, d := range diags {
291+ sev := int(d.Severity)
292+ if sev != SeverityError && sev != SeverityWarning {
293+ continue
294+ }
295+ if count == 0 {
296+ buf = append(buf, fmt.Sprintf("\nLSP diagnostics:\n<diagnostics file=%q>\n", displayPath)...)
297+ }
298+ label := "WARNING"
299+ if sev == SeverityError {
300+ label = "ERROR"
301+ }
302+ buf = append(buf, fmt.Sprintf("%s [%d:%d] %s\n",
303+ label,
304+ d.Range.Start.Line+1, // display as 1-indexed
305+ d.Range.Start.Character+1,
306+ d.Message,
307+ )...)
308+ count++
309+ if count >= 20 {
310+ remaining := 0
311+ for _, dd := range diags {
312+ if int(dd.Severity) == SeverityError || int(dd.Severity) == SeverityWarning {
313+ remaining++
314+ }
315+ }
316+ remaining -= count
317+ if remaining > 0 {
318+ buf = append(buf, fmt.Sprintf("... and %d more\n", remaining)...)
319+ }
320+ break
321+ }
322+ }
323+ if count == 0 {
324+ return ""
325+ }
326+ buf = append(buf, "</diagnostics>"...)
327+ return string(buf)
328+}
329+
330+// lookPath finds a command binary, checking PATH first, then common
331+// language-specific bin directories that may not be in PATH.
332+func lookPath(command string) string {
333+ if p, err := exec.LookPath(command); err == nil {
334+ return p
335+ }
336+
337+ // Extra directories where language toolchains install binaries.
338+ home, err := os.UserHomeDir()
339+ if err != nil {
340+ return ""
341+ }
342+
343+ var extras []string
344+
345+ // Go: $GOBIN or $GOPATH/bin or ~/go/bin
346+ if gobin := os.Getenv("GOBIN"); gobin != "" {
347+ extras = append(extras, gobin)
348+ }
349+ if gopath := os.Getenv("GOPATH"); gopath != "" {
350+ extras = append(extras, filepath.Join(gopath, "bin"))
351+ }
352+ extras = append(extras, filepath.Join(home, "go", "bin"))
353+
354+ // Rust: ~/.cargo/bin
355+ extras = append(extras, filepath.Join(home, ".cargo", "bin"))
356+
357+ // Local bin
358+ extras = append(extras, filepath.Join(home, ".local", "bin"))
359+
360+ for _, dir := range extras {
361+ p := filepath.Join(dir, command)
362+ if fi, err := os.Stat(p); err == nil && !fi.IsDir() {
363+ return p
364+ }
365+ }
366+ return ""
367+}