summaryrefslogtreecommitdiff
path: root/internal/lsp/server.go
blob: 7675d34174a32b2e04b08fbab6d0ade138522d96 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
// Package lsp provides a minimal LSP server over stdio; manages documents, dispatches requests, and tracks stats.
package lsp

import (
	"bufio"
	"context"
	"encoding/json"
	"errors"
	"io"
	"log"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"codeberg.org/snonux/hexai/internal/appconfig"
	"codeberg.org/snonux/hexai/internal/ignore"
	"codeberg.org/snonux/hexai/internal/llm"
	"codeberg.org/snonux/hexai/internal/llmutils"
	"codeberg.org/snonux/hexai/internal/logging"
	"codeberg.org/snonux/hexai/internal/runtimeconfig"
)

// Server implements a minimal LSP over stdio.
type Server struct {
	in           *bufio.Reader
	out          io.Writer
	outMu        sync.Mutex
	logger       *log.Logger
	serverCtx    context.Context
	serverCancel context.CancelFunc
	statusSink   StatusSink
	exited       atomic.Bool
	inflight     sync.WaitGroup // tracks background goroutines (inline prompt, chat, etc.)
	// mu protects docs, cfg, logContext, configLoadOpts, nextID, and chatSubsystem.lastInput.
	// It is never held while completionState.stateMu is held, and vice versa,
	// so there is no lock ordering concern between them.
	mu          sync.RWMutex
	docs        map[string]*document
	logContext  bool
	configStore *runtimeconfig.Store
	cfg         appconfig.App
	codeActionSubsystem
	chatSubsystem
	llmStatsSubsystem
	completionSubsystem
	configLoadOpts appconfig.LoadOptions
	// Outgoing JSON-RPC id counter for server-initiated requests
	nextID int64

	// Gitignore-aware file checker (nil when disabled)
	ignoreChecker *ignore.Checker

	// Dispatch table for JSON-RPC methods → handler functions
	handlers map[string]func(Request)
}

type completionSubsystem struct {
	completionState
}

type chatSubsystem struct {
	lastInput time.Time
}

type codeActionSubsystem struct {
	llmClientRegistry
}

// llmStatsSubsystem holds atomic LLM request counters. All fields are
// lock-free (atomic.Int64), so no mutex is needed.
type llmStatsSubsystem struct {
	llmReqTotal       atomic.Int64
	llmSentBytesTotal atomic.Int64
	llmRespTotal      atomic.Int64
	llmRespBytesTotal atomic.Int64
	startTime         time.Time
}

// GlobalStatus bundles the fields for a global status update,
// replacing a long parameter list.
type GlobalStatus struct {
	Reqs      int64
	RPM       float64
	Sent      int64
	Recv      int64
	Provider  string
	Model     string
	ScopeRPM  float64
	ScopeReqs int64
	Window    time.Duration
}

// StatusSink receives status updates from the LSP server.
type StatusSink interface {
	SetLLMStart(provider, model string) error
	SetGlobal(gs GlobalStatus) error
}

// ServerOptions collects configuration for NewServer to avoid long parameter lists.
type ServerOptions struct {
	LogContext        bool
	ConfigStore       *runtimeconfig.Store
	Config            *appconfig.App
	ConfigLoadOptions appconfig.LoadOptions

	Client llm.Client
	// Gitignore-aware file checker (optional)
	IgnoreChecker *ignore.Checker
	StatusSink    StatusSink
}

// NewServer creates a new LSP server that reads from r and writes to w.
func NewServer(r io.Reader, w io.Writer, logger *log.Logger, opts ServerOptions) *Server {
	ctx, cancel := context.WithCancel(context.Background())
	s := &Server{
		in:           bufio.NewReader(r),
		out:          w,
		logger:       logger,
		docs:         make(map[string]*document),
		logContext:   opts.LogContext,
		configStore:  opts.ConfigStore,
		serverCtx:    ctx,
		serverCancel: cancel,
		codeActionSubsystem: codeActionSubsystem{
			llmClientRegistry: llmClientRegistry{},
		},
		completionSubsystem: completionSubsystem{
			completionState: completionState{},
		},
	}
	s.startTime = time.Now()
	s.applyOptions(opts)
	// Initialize dispatch table
	s.handlers = map[string]func(Request){
		"initialize":               s.handleInitialize,
		"initialized":              func(_ Request) { s.handleInitialized() },
		"shutdown":                 s.handleShutdown,
		"exit":                     func(_ Request) { s.handleExit() },
		"textDocument/didOpen":     s.handleDidOpen,
		"textDocument/didChange":   s.handleDidChange,
		"textDocument/didClose":    s.handleDidClose,
		"textDocument/completion":  s.handleCompletion,
		"textDocument/codeAction":  s.handleCodeAction,
		"codeAction/resolve":       s.handleCodeActionResolve,
		"workspace/executeCommand": s.handleExecuteCommand,
	}
	return s
}

func (s *Server) applyOptions(opts ServerOptions) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.logContext = opts.LogContext
	s.configLoadOpts = opts.ConfigLoadOptions
	if opts.ConfigStore != nil {
		s.configStore = opts.ConfigStore
	}
	if opts.Config != nil {
		s.cfg = *opts.Config
	} else if opts.ConfigStore != nil {
		s.cfg = opts.ConfigStore.Snapshot()
	} else {
		s.cfg = appconfig.App{}
	}
	if opts.IgnoreChecker != nil {
		s.ignoreChecker = opts.IgnoreChecker
	}
	if opts.StatusSink != nil {
		s.statusSink = opts.StatusSink
	}
	s.llmClientRegistry.applyOptions(opts.Client, s.cfg.Provider)
}

// ApplyOptions updates the server's configuration at runtime.
func (s *Server) ApplyOptions(opts ServerOptions) {
	s.applyOptions(opts)
}

func (s *Server) currentLLMClient() llm.Client {
	return s.llmClientRegistry.current()
}

func newClientForProvider(cfg appconfig.App, provider, modelOverride string) (llm.Client, error) {
	return llmutils.NewClientFromAppForProvider(cfg, provider, modelOverride)
}

func (s *Server) clientFor(spec requestSpec) llm.Client {
	return s.llmClientRegistry.clientFor(spec, s.currentConfig(), newClientForProvider)
}

func (s *Server) currentConfig() appconfig.App {
	s.mu.RLock()
	store := s.configStore
	cfg := s.cfg
	s.mu.RUnlock()
	if store != nil {
		return store.Snapshot()
	}
	return cfg
}

func (s *Server) maxTokens() int {
	cfg := s.currentConfig()
	if cfg.MaxTokens <= 0 {
		return 500
	}
	return cfg.MaxTokens
}

func (s *Server) contextMode() string {
	mode := strings.TrimSpace(s.currentConfig().ContextMode)
	if mode == "" {
		return "file-on-new-func"
	}
	return mode
}

func (s *Server) windowLines() int {
	cfg := s.currentConfig()
	if cfg.ContextWindowLines <= 0 {
		return 120
	}
	return cfg.ContextWindowLines
}

func (s *Server) maxContextTokens() int {
	cfg := s.currentConfig()
	if cfg.MaxContextTokens <= 0 {
		return 2000
	}
	return cfg.MaxContextTokens
}

func (s *Server) triggerCharacters() []string {
	cfg := s.currentConfig()
	if len(cfg.TriggerCharacters) == 0 {
		return []string{".", ":", "/", "_", ")", "{"}
	}
	return append([]string{}, cfg.TriggerCharacters...)
}

func (s *Server) codingTemperature() *float64 {
	cfg := s.currentConfig()
	return cfg.CodingTemperature
}

func (s *Server) manualInvokeMinPrefix() int {
	return s.currentConfig().ManualInvokeMinPrefix
}

func (s *Server) completionDebounce() time.Duration {
	cfg := s.currentConfig()
	if cfg.CompletionDebounceMs <= 0 {
		return 0
	}
	return time.Duration(cfg.CompletionDebounceMs) * time.Millisecond
}

func (s *Server) completionThrottle() time.Duration {
	cfg := s.currentConfig()
	if cfg.CompletionThrottleMs <= 0 {
		return 0
	}
	return time.Duration(cfg.CompletionThrottleMs) * time.Millisecond
}

func (s *Server) completionWaitAll() bool {
	cfg := s.currentConfig()
	if cfg.CompletionWaitAll == nil {
		return true // default: wait for all backends
	}
	return *cfg.CompletionWaitAll
}

func (s *Server) inlineMarkers() (open string, close string, openChar byte, closeChar byte) {
	cfg := s.currentConfig()
	open = strings.TrimSpace(cfg.InlineOpen)
	if open == "" {
		open = ">!"
	}
	close = strings.TrimSpace(cfg.InlineClose)
	if close == "" {
		close = ">"
	}
	openChar = '>'
	if len(open) > 0 {
		openChar = open[0]
	}
	closeChar = '>'
	if len(close) > 0 {
		closeChar = close[0]
	}
	return open, close, openChar, closeChar
}

func (s *Server) chatConfig() (suffix string, prefixes []string, suffixChar byte) {
	cfg := s.currentConfig()
	suffix = cfg.ChatSuffix
	if suffix != "" {
		suffix = strings.TrimSpace(suffix)
		if suffix == "" {
			suffix = ">"
		}
	} else {
		suffix = ""
	}
	if len(cfg.ChatPrefixes) == 0 {
		prefixes = []string{"?", "!", ":", ";"}
	} else {
		prefixes = append([]string{}, cfg.ChatPrefixes...)
	}
	suffixChar = '>'
	if len(suffix) > 0 {
		suffixChar = suffix[0]
	}
	return suffix, prefixes, suffixChar
}

func (s *Server) promptSet() appconfig.App {
	return s.currentConfig()
}

func (s *Server) customActions() []appconfig.CustomAction {
	cfg := s.currentConfig()
	if len(cfg.CustomActions) == 0 {
		return nil
	}
	return append([]appconfig.CustomAction{}, cfg.CustomActions...)
}

func (s *Server) requestTimeoutContext(timeout time.Duration) (context.Context, context.CancelFunc) {
	if s.serverCtx == nil {
		return context.WithTimeout(context.Background(), timeout)
	}
	return context.WithTimeout(s.serverCtx, timeout)
}

func (s *Server) cancelRequests() {
	if s.serverCancel != nil {
		s.serverCancel()
	}
}

func (s *Server) emitLLMStartStatus(provider, model string) {
	if s.statusSink != nil {
		if err := s.statusSink.SetLLMStart(provider, model); err != nil {
			logging.Logf("lsp ", "status sink SetLLMStart error: %v", err)
		}
	}
}

func (s *Server) emitGlobalStatus(gs GlobalStatus) {
	if s.statusSink != nil {
		if err := s.statusSink.SetGlobal(gs); err != nil {
			logging.Logf("lsp ", "status sink SetGlobal error: %v", err)
		}
	}
}

// Run starts the server's main loop, reading and dispatching LSP messages until EOF or exit.
// On shutdown it cancels the server context and waits for in-flight goroutines.
func (s *Server) Run() error {
	defer func() {
		s.cancelRequests()
		s.inflight.Wait()
	}()
	for {
		body, err := s.readMessage()
		if errors.Is(err, io.EOF) {
			return nil
		}
		if err != nil {
			return err
		}
		var req Request
		if err := json.Unmarshal(body, &req); err != nil {
			logging.Logf("lsp ", "invalid JSON: %v", err)
			continue
		}
		if req.Method == "" {
			// A response from client; ignore
			continue
		}
		// Track every request goroutine so Run's deferred inflight.Wait()
		// catches them all and prevents use-after-close writes to s.out.
		s.inflight.Add(1)
		go func(r Request) {
			defer s.inflight.Done()
			s.handle(r)
		}(req)
		if s.exited.Load() {
			return nil
		}
	}
}