client.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. package lsp
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "os"
  9. "os/exec"
  10. "strings"
  11. "sync"
  12. "sync/atomic"
  13. "time"
  14. "github.com/kujtimiihoxha/opencode/internal/config"
  15. "github.com/kujtimiihoxha/opencode/internal/logging"
  16. "github.com/kujtimiihoxha/opencode/internal/lsp/protocol"
  17. )
  18. type Client struct {
  19. Cmd *exec.Cmd
  20. stdin io.WriteCloser
  21. stdout *bufio.Reader
  22. stderr io.ReadCloser
  23. // Request ID counter
  24. nextID atomic.Int32
  25. // Response handlers
  26. handlers map[int32]chan *Message
  27. handlersMu sync.RWMutex
  28. // Server request handlers
  29. serverRequestHandlers map[string]ServerRequestHandler
  30. serverHandlersMu sync.RWMutex
  31. // Notification handlers
  32. notificationHandlers map[string]NotificationHandler
  33. notificationMu sync.RWMutex
  34. // Diagnostic cache
  35. diagnostics map[protocol.DocumentUri][]protocol.Diagnostic
  36. diagnosticsMu sync.RWMutex
  37. // Files are currently opened by the LSP
  38. openFiles map[string]*OpenFileInfo
  39. openFilesMu sync.RWMutex
  40. }
  41. func NewClient(ctx context.Context, command string, args ...string) (*Client, error) {
  42. cmd := exec.CommandContext(ctx, command, args...)
  43. // Copy env
  44. cmd.Env = os.Environ()
  45. stdin, err := cmd.StdinPipe()
  46. if err != nil {
  47. return nil, fmt.Errorf("failed to create stdin pipe: %w", err)
  48. }
  49. stdout, err := cmd.StdoutPipe()
  50. if err != nil {
  51. return nil, fmt.Errorf("failed to create stdout pipe: %w", err)
  52. }
  53. stderr, err := cmd.StderrPipe()
  54. if err != nil {
  55. return nil, fmt.Errorf("failed to create stderr pipe: %w", err)
  56. }
  57. client := &Client{
  58. Cmd: cmd,
  59. stdin: stdin,
  60. stdout: bufio.NewReader(stdout),
  61. stderr: stderr,
  62. handlers: make(map[int32]chan *Message),
  63. notificationHandlers: make(map[string]NotificationHandler),
  64. serverRequestHandlers: make(map[string]ServerRequestHandler),
  65. diagnostics: make(map[protocol.DocumentUri][]protocol.Diagnostic),
  66. openFiles: make(map[string]*OpenFileInfo),
  67. }
  68. // Start the LSP server process
  69. if err := cmd.Start(); err != nil {
  70. return nil, fmt.Errorf("failed to start LSP server: %w", err)
  71. }
  72. // Handle stderr in a separate goroutine
  73. go func() {
  74. scanner := bufio.NewScanner(stderr)
  75. for scanner.Scan() {
  76. fmt.Fprintf(os.Stderr, "LSP Server: %s\n", scanner.Text())
  77. }
  78. if err := scanner.Err(); err != nil {
  79. fmt.Fprintf(os.Stderr, "Error reading stderr: %v\n", err)
  80. }
  81. }()
  82. // Start message handling loop
  83. go func() {
  84. defer logging.RecoverPanic("LSP-message-handler", func() {
  85. logging.ErrorPersist("LSP message handler crashed, LSP functionality may be impaired")
  86. })
  87. client.handleMessages()
  88. }()
  89. return client, nil
  90. }
  91. func (c *Client) RegisterNotificationHandler(method string, handler NotificationHandler) {
  92. c.notificationMu.Lock()
  93. defer c.notificationMu.Unlock()
  94. c.notificationHandlers[method] = handler
  95. }
  96. func (c *Client) RegisterServerRequestHandler(method string, handler ServerRequestHandler) {
  97. c.serverHandlersMu.Lock()
  98. defer c.serverHandlersMu.Unlock()
  99. c.serverRequestHandlers[method] = handler
  100. }
  101. func (c *Client) InitializeLSPClient(ctx context.Context, workspaceDir string) (*protocol.InitializeResult, error) {
  102. initParams := &protocol.InitializeParams{
  103. WorkspaceFoldersInitializeParams: protocol.WorkspaceFoldersInitializeParams{
  104. WorkspaceFolders: []protocol.WorkspaceFolder{
  105. {
  106. URI: protocol.URI("file://" + workspaceDir),
  107. Name: workspaceDir,
  108. },
  109. },
  110. },
  111. XInitializeParams: protocol.XInitializeParams{
  112. ProcessID: int32(os.Getpid()),
  113. ClientInfo: &protocol.ClientInfo{
  114. Name: "mcp-language-server",
  115. Version: "0.1.0",
  116. },
  117. RootPath: workspaceDir,
  118. RootURI: protocol.DocumentUri("file://" + workspaceDir),
  119. Capabilities: protocol.ClientCapabilities{
  120. Workspace: protocol.WorkspaceClientCapabilities{
  121. Configuration: true,
  122. DidChangeConfiguration: protocol.DidChangeConfigurationClientCapabilities{
  123. DynamicRegistration: true,
  124. },
  125. DidChangeWatchedFiles: protocol.DidChangeWatchedFilesClientCapabilities{
  126. DynamicRegistration: true,
  127. RelativePatternSupport: true,
  128. },
  129. },
  130. TextDocument: protocol.TextDocumentClientCapabilities{
  131. Synchronization: &protocol.TextDocumentSyncClientCapabilities{
  132. DynamicRegistration: true,
  133. DidSave: true,
  134. },
  135. Completion: protocol.CompletionClientCapabilities{
  136. CompletionItem: protocol.ClientCompletionItemOptions{},
  137. },
  138. CodeLens: &protocol.CodeLensClientCapabilities{
  139. DynamicRegistration: true,
  140. },
  141. DocumentSymbol: protocol.DocumentSymbolClientCapabilities{},
  142. CodeAction: protocol.CodeActionClientCapabilities{
  143. CodeActionLiteralSupport: protocol.ClientCodeActionLiteralOptions{
  144. CodeActionKind: protocol.ClientCodeActionKindOptions{
  145. ValueSet: []protocol.CodeActionKind{},
  146. },
  147. },
  148. },
  149. PublishDiagnostics: protocol.PublishDiagnosticsClientCapabilities{
  150. VersionSupport: true,
  151. },
  152. SemanticTokens: protocol.SemanticTokensClientCapabilities{
  153. Requests: protocol.ClientSemanticTokensRequestOptions{
  154. Range: &protocol.Or_ClientSemanticTokensRequestOptions_range{},
  155. Full: &protocol.Or_ClientSemanticTokensRequestOptions_full{},
  156. },
  157. TokenTypes: []string{},
  158. TokenModifiers: []string{},
  159. Formats: []protocol.TokenFormat{},
  160. },
  161. },
  162. Window: protocol.WindowClientCapabilities{},
  163. },
  164. InitializationOptions: map[string]any{
  165. "codelenses": map[string]bool{
  166. "generate": true,
  167. "regenerate_cgo": true,
  168. "test": true,
  169. "tidy": true,
  170. "upgrade_dependency": true,
  171. "vendor": true,
  172. "vulncheck": false,
  173. },
  174. },
  175. },
  176. }
  177. var result protocol.InitializeResult
  178. if err := c.Call(ctx, "initialize", initParams, &result); err != nil {
  179. return nil, fmt.Errorf("initialize failed: %w", err)
  180. }
  181. if err := c.Notify(ctx, "initialized", struct{}{}); err != nil {
  182. return nil, fmt.Errorf("initialized notification failed: %w", err)
  183. }
  184. // Register handlers
  185. c.RegisterServerRequestHandler("workspace/applyEdit", HandleApplyEdit)
  186. c.RegisterServerRequestHandler("workspace/configuration", HandleWorkspaceConfiguration)
  187. c.RegisterServerRequestHandler("client/registerCapability", HandleRegisterCapability)
  188. c.RegisterNotificationHandler("window/showMessage", HandleServerMessage)
  189. c.RegisterNotificationHandler("textDocument/publishDiagnostics",
  190. func(params json.RawMessage) { HandleDiagnostics(c, params) })
  191. // Notify the LSP server
  192. err := c.Initialized(ctx, protocol.InitializedParams{})
  193. if err != nil {
  194. return nil, fmt.Errorf("initialization failed: %w", err)
  195. }
  196. // LSP sepecific Initialization
  197. path := strings.ToLower(c.Cmd.Path)
  198. switch {
  199. case strings.Contains(path, "typescript-language-server"):
  200. // err := initializeTypescriptLanguageServer(ctx, c, workspaceDir)
  201. // if err != nil {
  202. // return nil, err
  203. // }
  204. }
  205. return &result, nil
  206. }
  207. func (c *Client) Close() error {
  208. // Try to close all open files first
  209. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  210. defer cancel()
  211. // Attempt to close files but continue shutdown regardless
  212. c.CloseAllFiles(ctx)
  213. // Close stdin to signal the server
  214. if err := c.stdin.Close(); err != nil {
  215. return fmt.Errorf("failed to close stdin: %w", err)
  216. }
  217. // Use a channel to handle the Wait with timeout
  218. done := make(chan error, 1)
  219. go func() {
  220. done <- c.Cmd.Wait()
  221. }()
  222. // Wait for process to exit with timeout
  223. select {
  224. case err := <-done:
  225. return err
  226. case <-time.After(2 * time.Second):
  227. // If we timeout, try to kill the process
  228. if err := c.Cmd.Process.Kill(); err != nil {
  229. return fmt.Errorf("failed to kill process: %w", err)
  230. }
  231. return fmt.Errorf("process killed after timeout")
  232. }
  233. }
  234. type ServerState int
  235. const (
  236. StateStarting ServerState = iota
  237. StateReady
  238. StateError
  239. )
  240. func (c *Client) WaitForServerReady(ctx context.Context) error {
  241. // TODO: wait for specific messages or poll workspace/symbol
  242. time.Sleep(time.Second * 1)
  243. return nil
  244. }
  245. type OpenFileInfo struct {
  246. Version int32
  247. URI protocol.DocumentUri
  248. }
  249. func (c *Client) OpenFile(ctx context.Context, filepath string) error {
  250. uri := fmt.Sprintf("file://%s", filepath)
  251. c.openFilesMu.Lock()
  252. if _, exists := c.openFiles[uri]; exists {
  253. c.openFilesMu.Unlock()
  254. return nil // Already open
  255. }
  256. c.openFilesMu.Unlock()
  257. // Skip files that do not exist or cannot be read
  258. content, err := os.ReadFile(filepath)
  259. if err != nil {
  260. return fmt.Errorf("error reading file: %w", err)
  261. }
  262. params := protocol.DidOpenTextDocumentParams{
  263. TextDocument: protocol.TextDocumentItem{
  264. URI: protocol.DocumentUri(uri),
  265. LanguageID: DetectLanguageID(uri),
  266. Version: 1,
  267. Text: string(content),
  268. },
  269. }
  270. if err := c.Notify(ctx, "textDocument/didOpen", params); err != nil {
  271. return err
  272. }
  273. c.openFilesMu.Lock()
  274. c.openFiles[uri] = &OpenFileInfo{
  275. Version: 1,
  276. URI: protocol.DocumentUri(uri),
  277. }
  278. c.openFilesMu.Unlock()
  279. return nil
  280. }
  281. func (c *Client) NotifyChange(ctx context.Context, filepath string) error {
  282. uri := fmt.Sprintf("file://%s", filepath)
  283. content, err := os.ReadFile(filepath)
  284. if err != nil {
  285. return fmt.Errorf("error reading file: %w", err)
  286. }
  287. c.openFilesMu.Lock()
  288. fileInfo, isOpen := c.openFiles[uri]
  289. if !isOpen {
  290. c.openFilesMu.Unlock()
  291. return fmt.Errorf("cannot notify change for unopened file: %s", filepath)
  292. }
  293. // Increment version
  294. fileInfo.Version++
  295. version := fileInfo.Version
  296. c.openFilesMu.Unlock()
  297. params := protocol.DidChangeTextDocumentParams{
  298. TextDocument: protocol.VersionedTextDocumentIdentifier{
  299. TextDocumentIdentifier: protocol.TextDocumentIdentifier{
  300. URI: protocol.DocumentUri(uri),
  301. },
  302. Version: version,
  303. },
  304. ContentChanges: []protocol.TextDocumentContentChangeEvent{
  305. {
  306. Value: protocol.TextDocumentContentChangeWholeDocument{
  307. Text: string(content),
  308. },
  309. },
  310. },
  311. }
  312. return c.Notify(ctx, "textDocument/didChange", params)
  313. }
  314. func (c *Client) CloseFile(ctx context.Context, filepath string) error {
  315. cnf := config.Get()
  316. uri := fmt.Sprintf("file://%s", filepath)
  317. c.openFilesMu.Lock()
  318. if _, exists := c.openFiles[uri]; !exists {
  319. c.openFilesMu.Unlock()
  320. return nil // Already closed
  321. }
  322. c.openFilesMu.Unlock()
  323. params := protocol.DidCloseTextDocumentParams{
  324. TextDocument: protocol.TextDocumentIdentifier{
  325. URI: protocol.DocumentUri(uri),
  326. },
  327. }
  328. if cnf.DebugLSP {
  329. logging.Debug("Closing file", "file", filepath)
  330. }
  331. if err := c.Notify(ctx, "textDocument/didClose", params); err != nil {
  332. return err
  333. }
  334. c.openFilesMu.Lock()
  335. delete(c.openFiles, uri)
  336. c.openFilesMu.Unlock()
  337. return nil
  338. }
  339. func (c *Client) IsFileOpen(filepath string) bool {
  340. uri := fmt.Sprintf("file://%s", filepath)
  341. c.openFilesMu.RLock()
  342. defer c.openFilesMu.RUnlock()
  343. _, exists := c.openFiles[uri]
  344. return exists
  345. }
  346. // CloseAllFiles closes all currently open files
  347. func (c *Client) CloseAllFiles(ctx context.Context) {
  348. cnf := config.Get()
  349. c.openFilesMu.Lock()
  350. filesToClose := make([]string, 0, len(c.openFiles))
  351. // First collect all URIs that need to be closed
  352. for uri := range c.openFiles {
  353. // Convert URI back to file path by trimming "file://" prefix
  354. filePath := strings.TrimPrefix(uri, "file://")
  355. filesToClose = append(filesToClose, filePath)
  356. }
  357. c.openFilesMu.Unlock()
  358. // Then close them all
  359. for _, filePath := range filesToClose {
  360. err := c.CloseFile(ctx, filePath)
  361. if err != nil && cnf.DebugLSP {
  362. logging.Warn("Error closing file", "file", filePath, "error", err)
  363. }
  364. }
  365. if cnf.DebugLSP {
  366. logging.Debug("Closed all files", "files", filesToClose)
  367. }
  368. }
  369. func (c *Client) GetFileDiagnostics(uri protocol.DocumentUri) []protocol.Diagnostic {
  370. c.diagnosticsMu.RLock()
  371. defer c.diagnosticsMu.RUnlock()
  372. return c.diagnostics[uri]
  373. }
  374. func (c *Client) GetDiagnostics() map[protocol.DocumentUri][]protocol.Diagnostic {
  375. return c.diagnostics
  376. }