LSP 原始碼解讀

深入理解 OpenCode LSP 模組:Effect Service 架構、智慧客戶端管理、30+ Language Server 自動偵測與啟動、診斷收集機制。

本頁內文若連結到尚未提供繁體版本的頁面(例如 /ecosystem/plugins/、/news/),會開啟英文原頁;導覽與頁尾標有 EN 的項目即為這類頁面。

模組概述

LSP(Language Server Protocol)模組讓 OpenCode 獲得了 IDE 級別的程式碼理解能力。透過標準化的 LSP 協定,OpenCode 可以取得精確的診斷資訊(編譯錯誤、型別錯誤、lint 警告)、跳轉到定義、尋找引用、取得懸浮資訊、瀏覽符號階層。這讓 AI 助手能基於精確的程式碼語意做出決策,而非單純的文字比對。

模組位於 packages/opencode/src/lsp/,由 5 個檔案組成,總共約 2900 行程式碼。核心入口 LSP 命名空間採用 Effect Service 架構,透過 Instance.state() 管理全域單例狀態。模組內建 30+ 種 Language Server 的定義(TypeScript、Gopls、Rust Analyzer、Pyright、Clangd、Lua LS 等),每種伺服器都有自己的專案根目錄偵測邏輯與 spawn 實作。

核心設計選擇:

  • Effect Service 模式:LSP 命名空間透過 ServiceMap.Service 註冊為全域服務,Instance.state() 管理生命週期
  • 智慧客戶端複用:getClients(file) 依 (root, serverID) 去重,同一專案只啟動一個伺服器實例
  • 去抖診斷收集:waitForDiagnostics() 使用 150ms 去抖 + 3 秒逾時,避免 Agent 阻塞
  • 自動下載與隔離:Language Server 二進位檔自動下載到 Global.Path.bin,透過 Flag.OPENCODE_DISABLE_LSP_DOWNLOAD 控制

關鍵檔案

檔案路徑行數職責
src/lsp/index.ts~559模組主入口:Effect Service 定義、InstanceState 狀態管理、getClients 智慧配對、所有公開 API
src/lsp/client.ts~253LSP 客戶端實作:vscode-jsonrpc 連線管理、診斷收集、檔案版本追蹤、連線關閉
src/lsp/server.ts~196830+ 種 Language Server 定義:LSPServer.Info 介面、NearestRoot 高階函式、spawn 實作與自動下載
src/lsp/launch.ts~22spawn 輔助函式:包裝 Process.spawn,簡化伺服器啟動程式碼
src/lsp/language.ts~120LANGUAGE_EXTENSIONS 對應表:檔案副檔名(如 .tsx)→ LSP languageId(如 typescriptreact)

型別體系

Range 與 Diagnostic — 位置與診斷

// 文字範圍(行號 + 字元位移)
export const Range = z.object({
  start: z.object({ line: z.number(), character: z.number() }),
  end: z.object({ line: z.number(), character: z.number() }),
})

// 符號資訊(用於 documentSymbol / workspaceSymbol)
export const Symbol = z.object({
  name: z.string(),
  kind: z.number(),       // LSP SymbolKind 列舉值
  location: z.object({
    uri: z.string(),
    range: Range,
  }),
})

// 伺服器連線狀態
export const Status = z.object({
  id: z.string(),         // 伺服器唯一識別碼
  name: z.string(),       // 人類可讀名稱
  root: z.string(),       // 專案根目錄
  status: z.union([
    z.literal("connected"),
    z.literal("error"),
  ]),
})

InstanceState — 全域狀態

// LSP 模組的全域狀態結構
{
  clients: LSPClient.Info[],                 // 所有活躍的客戶端連線
  servers: Record<string, LSPServer.Info>,   // 已註冊的伺服器定義(key = serverID)
  broken: Set<string>,                       // 已知失敗的伺服器 ID,避免重複嘗試
  spawning: Map<string, Promise<LSPClient.Info | undefined>>,  // 正在啟動的客戶端(去重)
}

關鍵欄位說明:

  • clients:所有活躍的 LSP 客戶端連線。每個客戶端綁定到一個 (root, serverID) 組合
  • servers:從內建定義 + 使用者設定合併後的伺服器註冊表。key 是伺服器 ID(如 "typescript"、"gopls")
  • broken:啟動失敗的伺服器 ID 集合。一旦進入此集合,後續 getClients() 直接略過,不再重試
  • spawning:正在啟動中的客戶端 Promise。同一 (root, serverID) 的並行請求會共用同一個 Promise,避免重複啟動

LSPServer.Info — 伺服器定義

// server.ts 中每種 Language Server 的定義介面
interface Info {
  id: string              // 唯一識別碼,如 "typescript"、"gopls"、"rust-analyzer"
  extensions: string[]    // 關聯的檔案副檔名,如 [".ts", ".tsx"]
  root: RootFunction      // 判定專案根目錄的函式
  spawn(root: string): Promise<Handle | undefined>  // 啟動伺服器行程
}

LSPClient.Info — 客戶端實例

// client.ts 中客戶端的核心結構
{
  serverID: string                           // 對應的伺服器 ID
  root: string                               // 專案根目錄
  connection: MessageConnection              // vscode-jsonrpc 訊息連線
  diagnostics: Map<string, Diagnostic[]>     // 檔案路徑 → 診斷清單
  files: Record<string, number>              // 檔案路徑 → 版本編號(遞增計數器)
  process: ChildProcess                      // 伺服器子行程
}

核心流程

getClients — 智慧檔案-客戶端配對

getClients(file) 是 LSP 模組最核心的函式,負責為指定檔案找到或建立合適的 LSP 客戶端。完整邏輯分為 8 個步驟:

// index.ts — 簡化後的核心邏輯
async function getClients(file: string): Promise<LSPClient.Info[]> {
  const state = await instanceState()
  const results: LSPClient.Info[] = []

  // 步驟 1:檢查檔案是否在 Instance 目錄內
  // 不在專案目錄內的檔案不處理
  if (!file.startsWith(instance.directory)) return results

  // 步驟 2:取出檔案副檔名
  const ext = path.extname(file)  // 例如 ".ts"、".go"

  // 步驟 3:走訪所有已註冊伺服器,檢查副檔名是否相符
  for (const [serverID, server] of Object.entries(state.servers)) {
    if (!server.extensions.includes(ext)) continue

    // 步驟 4:呼叫 server.root(file) 判定專案根目錄
    const root = server.root(file)
    if (!root) continue  // 該檔案不屬於任何專案

    // 步驟 5:檢查 broken 集合,略過已知失敗的伺服器
    if (state.broken.has(serverID)) continue

    // 步驟 6:尋找既有客戶端(root + serverID 相符)
    const existing = state.clients.find(
      c => c.root === root && c.serverID === serverID
    )
    if (existing) {
      results.push(existing)
      continue
    }

    // 步驟 7:檢查 spawning Map 處理並行請求
    const spawnKey = `${root}:${serverID}`
    const spawning = state.spawning.get(spawnKey)
    if (spawning) {
      const client = await spawning
      if (client) results.push(client)
      continue
    }

    // 步驟 8:建立新客戶端並存入快取
    const promise = LSPClient.create({ serverID, server: server.handle, root })
      .catch(() => {
        state.broken.add(serverID)  // 啟動失敗 → 加入 broken 集合
        return undefined
      })
    state.spawning.set(spawnKey, promise)
    const client = await promise
    state.spawning.delete(spawnKey)
    if (client) {
      state.clients.push(client)
      results.push(client)
    }
  }

  return results
}

這段邏輯實作了完整的客戶端複用與去重:

  • 同一專案下不會啟動兩個相同類型的 Language Server
  • 並行的 getClients 呼叫共用同一個 spawn Promise
  • 失敗的伺服器被記入 broken 集合,不再重試

LSPClient.create — JSON-RPC 連線建立

LSPClient.create() 是客戶端建立的核心函式,建立與 Language Server 的通訊通道:

// client.ts — 核心流程(簡化)
async function create(input: {
  serverID: string
  server: LSPServer.Handle
  root: string
}): Promise<Info> {
  // 1. 啟動伺服器子行程
  const handle = await input.server.spawn(input.root)
  if (!handle) throw new Error("spawn failed")

  // 2. 建立 JSON-RPC 訊息連線
  const connection = createMessageConnection(
    new StreamMessageReader(handle.process.stdout),
    new StreamMessageWriter(handle.process.stdin),
  )

  // 3. 啟動訊息監聽
  connection.listen()

  // 4. 送出 initialize 請求(逾時 45 秒)
  const initResult = await withTimeout(
    connection.sendRequest("initialize", {
      rootUri: pathToUri(input.root),
      capabilities: {
        textDocument: {
          synchronization: { didOpen: true, didChange: true, didClose: true },
          publishDiagnostics: { relatedInformation: true },
        },
        workspace: { configuration: true },
      },
    }),
    45_000,
  )

  // 5. 送出 initialized 通知
  connection.sendNotification("initialized", {})

  // 6. 建立客戶端實例
  return {
    serverID: input.serverID,
    root: input.root,
    connection,
    process: handle.process,
    diagnostics: new Map(),
    files: {},
  }
}

連線建立後,客戶端監聽 textDocument/publishDiagnostics 通知並自動更新診斷對應表。

診斷收集流程

診斷收集是 LSP 模組最核心的輸出,直接影響 Agent 的程式碼修復能力。完整流程:

1. Agent 編輯檔案
   └─ LSP.touchFile(filePath, content, true)

2. getClients(file) 配對合適的客戶端
   └─ 依副檔名 → 伺服器 → root → 複用/建立客戶端

3. 客戶端送出檔案變更通知
   ├─ 首次開啟? → textDocument/didOpen
   └─ 已開啟?   → textDocument/didChange (帶版本編號)

4. Language Server 分析程式碼後推送診斷
   └─ textDocument/publishDiagnostics 通知

5. 客戶端更新 diagnostics Map
   └─ TypeScript 伺服器特殊處理:首次診斷不發布事件(!exists 檢查)

6. 透過 Bus 廣播給上層
   └─ Bus.publish(Event.Diagnostics, { ... })

waitForDiagnostics 去抖機制:

// client.ts — 診斷等待(簡化)
async function waitForDiagnostics(
  client: LSPClient.Info,
  uri: string,
): Promise<Diagnostic[]> {
  const DIAGNOSTICS_DEBOUNCE_MS = 150   // 去抖間隔
  const DIAGNOSTICS_TIMEOUT_MS = 3000   // 總逾時

  return new Promise((resolve) => {
    let timer: ReturnType<typeof setTimeout>

    // 訂閱診斷事件
    const unsub = Bus.subscribe(Event.Diagnostics, (event) => {
      // 只關注目前檔案
      if (event.uri !== uri) return

      // 收到診斷後重設計時器(去抖)
      clearTimeout(timer)
      timer = setTimeout(() => {
        unsub()
        resolve(client.diagnostics.get(uri) ?? [])
      }, DIAGNOSTICS_DEBOUNCE_MS)
    })

    // 總逾時保護:3 秒後強制回傳
    setTimeout(() => {
      unsub()
      clearTimeout(timer)
      resolve(client.diagnostics.get(uri) ?? [])
    }, DIAGNOSTICS_TIMEOUT_MS)
  })
}

150ms 去抖的原因:Language Server 通常先送出語法診斷,稍後送出語意診斷。去抖確保 Agent 取得的是完整的診斷結果,而非中間狀態。3 秒總逾時避免 Agent 無限等待。

伺服器定義與 NearestRoot

server.ts 是模組中最大的檔案(~1968 行),定義了 30+ 種 Language Server。每種伺服器的核心是兩個函式:root() 和 spawn()。

NearestRoot 高階函式:

// server.ts — 專案根目錄偵測(簡化)
function NearestRoot(
  files: string[],      // 目標檔名清單,如 ["package.json", "tsconfig.json"]
  exclude?: string[],   // 排除模式,如 ["deno.json"]
): (file: string) => string | undefined {
  return (file: string) => {
    // 從檔案所在目錄往上搜尋直到 Instance.directory
    let dir = path.dirname(file)
    while (dir.startsWith(instance.directory)) {
      // 檢查目標檔案是否存在
      for (const name of files) {
        const target = path.join(dir, name)
        if (fs.existsSync(target)) {
          // 檢查排除模式
          if (exclude?.some(ex => fs.existsSync(path.join(dir, ex)))) {
            continue  // 符合排除規則,略過此目錄
          }
          return dir
        }
      }
      dir = path.dirname(dir)
    }
    return undefined
  }
}

這個高階函式支援 monorepo 情境:不同子目錄下的檔案可以配對到不同的專案根目錄,從而啟動獨立的 Language Server 實例。排除模式用於處理特殊情況(如 TypeScript 伺服器排除 deno.json,避免在 Deno 專案中啟動錯誤的 TS 伺服器)。

內建伺服器概覽(30+ 種):

類別伺服器根目錄偵測策略
前端TypeScript, Deno, Vue, Astro, SvelteNearestRoot(["package.json", "tsconfig.json"], ["deno.json"])
系統語言Gopls, Rust Analyzer, Clangd, SourceKit (Swift)NearestRoot(["go.mod"]) / Cargo.toml / compile_commands.json / Package.swift
指令碼語言Pyright, JDTLS (Java), KotlinLS, Rubocop (Ruby), JuliaLSNearestRoot(["pyproject.toml", "setup.py"]) / pom.xml / build.gradle 等
函式式語言LuaLS, Zls (Zig), Gleam, Ocaml, HLS (Haskell)NearestRoot([".luarc.json"]) / build.zig / gleam.toml / dune / hie.yaml
基礎設施TerraformLS, DockerfileLS, YamlLS, NixdNearestRoot(["*.tf"]) / Dockerfile / *.yml / flake.nix
資料/查詢Prisma, TexLab (LaTeX), SQLSNearestRoot(["*.prisma"]) / *.tex / *.sql
其他Biome, ESLint, Dart, Clojure, PHPIntelephense, CSharp, FSharp各自的設定檔偵測
排版Tinymist (Typst)NearestRoot(["*.typ"])

自動下載邏輯

部分 Language Server(如 Biome、Deno、Ty)支援自動下載,流程如下:

// server.ts — 自動下載(簡化)
async function spawnWithDownload(input: {
  command: string
  args: string[]
  url: string    // 下載網址範本
}): Promise<Handle | undefined> {
  // 檢查旗標
  if (Flag.OPENCODE_DISABLE_LSP_DOWNLOAD) {
    // 只嘗試本機尋找,不下載
    return Process.spawn(input.command, input.args)
  }

  // 嘗試本機啟動
  const local = await Process.spawn(input.command, input.args)
  if (local) return local

  // 本機不存在 → 自動下載到 Global.Path.bin
  const binPath = path.join(Global.Path.bin, input.command)
  if (!fs.existsSync(binPath)) {
    await download(input.url, binPath)
  }

  return Process.spawn(binPath, input.args)
}

程式碼導覽 API

LSP 模組提供完整的程式碼導覽能力,所有 API 透過 run() 輔助函式路由到配對的客戶端:

// index.ts — run 輔助函式(簡化)
async function run<T>(
  file: string,
  fn: (client: LSPClient.Info, uri: string) => Promise<T>,
): Promise<T[]> {
  const clients = await getClients(file)
  const uri = pathToUri(file)
  return Promise.all(clients.map(c => fn(c, uri)))
}
APILSP Method說明
definition(file, position)textDocument/definition從引用跳轉到定義,回傳 Location[]
references(file, position)textDocument/references尋找符號的所有引用位置
hover(file, position)textDocument/hover取得符號的型別資訊與文件
workspaceSymbol(query)workspace/symbol全域符號搜尋,過濾 kind 5/6/11/12 等,最多 10 筆
documentSymbol(uri)textDocument/documentSymbol文件內符號清單,回傳 DocumentSymbol 或 Symbol
incomingCalls(file, position)兩步請求prepareCallHierarchy → callHierarchy/incomingCalls
outgoingCalls(file, position)兩步請求prepareCallHierarchy → callHierarchy/outgoingCalls

workspaceSymbol 的過濾邏輯:

// index.ts — workspaceSymbol(簡化)
async function workspaceSymbol(query: string): Promise<Symbol[]> {
  const allClients = await allClients()
  const results: Symbol[] = []

  for (const client of allClients) {
    const symbols = await client.connection.sendRequest(
      "workspace/symbol",
      { query },
    )
    for (const sym of symbols) {
      // 過濾到關鍵類型:Class(5), Function(6/12), Method(6), Enum(10)
      if ([5, 6, 11, 12].includes(sym.kind)) {
        results.push(sym)
      }
    }
  }

  // 最多回傳 10 筆,避免上下文膨脹
  return results.slice(0, 10)
}

呼叫鏈範例

鏈路 1:Agent 編輯檔案 → 診斷收集 → Agent 修復

1. Agent 執行 EditTool 修改檔案
   └─ SessionProcessor 處理 tool-result 事件

2. Agent 呼叫 LSP.touchFile(filePath, newContent, true)
   ├─ getClients(file)
   │  ├─ 取出副檔名: ".ts"
   │  ├─ 配對伺服器: Typescript (extensions 包含 ".ts")
   │  ├─ root(file) → NearestRoot(["package.json"]) → "/project/root"
   │  ├─ 尋找既有客戶端: root="/project/root", serverID="typescript" → 命中
   │  └─ 回傳 [existingClient]
   └─ client.notify.didChange({ uri, version: 3, content: newContent })

3. Language Server 分析變更後的檔案
   └─ 推送 textDocument/publishDiagnostics 通知

4. 客戶端更新 diagnostics Map
   └─ Bus.publish(Event.Diagnostics, { uri, diagnostics: [...] })

5. Agent 呼叫 LSP.waitForDiagnostics(file)
   ├─ 訂閱 Diagnostics 事件
   ├─ 收到通知 → 啟動 150ms 去抖計時器
   ├─ 150ms 內無新診斷 → resolve
   └─ 回傳 [{ message: "Type 'string' is not assignable to 'number'", range: {...} }]

6. Agent 依診斷結果決定是否繼續修復
   └─ SessionPrompt.loop() 下一次迭代中,Agent 看到診斷結果並決定修復策略

鏈路 2:首次開啟檔案 → 伺服器啟動 → 診斷就緒

1. Agent 首次讀取 "main.go"
   └─ LSP.touchFile("main.go", content, true)

2. getClients("main.go")
   ├─ 副檔名: ".go"
   ├─ 配對伺服器: Gopls (extensions 包含 ".go")
   ├─ root("main.go") → NearestRoot(["go.mod"]) → "/project/root"
   ├─ 尋找既有客戶端: 無相符(首次開啟)
   ├─ 檢查 spawning Map: 無(首次)
   └─ 建立新客戶端:
      ├─ LSPClient.create({ serverID: "gopls", root: "/project/root" })
      │  ├─ server.spawn(root) → Process.spawn("gopls", ["serve"])
      │  ├─ createMessageConnection(stdout, stdin)
      │  ├─ connection.sendRequest("initialize", { rootUri, capabilities })
      │  ├─ connection.sendNotification("initialized", {})
      │  └─ 回傳新客戶端
      ├─ state.clients.push(newClient)
      └─ 回傳 [newClient]

3. 新客戶端送出 textDocument/didOpen
   └─ connection.sendNotification("textDocument/didOpen", { textDocument: { uri, languageId: "go", version: 1, text: content } })

4. Gopls 分析後推送診斷
   └─ publishDiagnostics → diagnostics Map 更新 → Bus 廣播

5. waitForDiagnostics("main.go")
   ├─ 150ms 去抖等待
   └─ 回傳診斷結果

鏈路 3:Monorepo 中多個專案共存

專案結構:
/project
├── frontend/
│   ├── package.json
│   └── app.tsx       ← TypeScript 檔案
├── backend/
│   ├── go.mod
│   └── main.go       ← Go 檔案
└── shared/
    └── utils.ts      ← TypeScript 檔案

1. Agent 開啟 "frontend/app.tsx"
   ├─ getClients → Typescript 伺服器
   ├─ root("frontend/app.tsx") → NearestRoot → "/project/frontend"
   └─ 啟動 TS Client A (root="/project/frontend")

2. Agent 開啟 "shared/utils.ts"
   ├─ getClients → Typescript 伺服器
   ├─ root("shared/utils.ts") → NearestRoot → "/project"(往上搜尋到專案根目錄的 package.json)
   └─ 啟動 TS Client B (root="/project") — 不同 root,不同實例

3. Agent 開啟 "backend/main.go"
   ├─ getClients → Gopls 伺服器
   ├─ root("backend/main.go") → NearestRoot → "/project/backend"
   └─ 啟動 Go Client C (root="/project/backend")

結果:3 個獨立的 LSP 客戶端並存,互不干擾

鏈路 4:伺服器啟動失敗 → broken 標記 → 後續略過

1. Agent 開啟 "broken.rs"
   └─ getClients → Rust Analyzer 伺服器

2. LSPClient.create() → server.spawn() 失敗
   ├─ catch 區塊捕捉錯誤
   ├─ state.broken.add("rust-analyzer")
   └─ 回傳 undefined

3. Agent 再次開啟 "other.rs"
   └─ getClients("other.rs")
      ├─ 配對伺服器: Rust Analyzer
      ├─ 檢查 broken 集合: "rust-analyzer" ∈ broken
      └─ 略過,不重試 → 回傳空清單

4. Agent 看到沒有診斷結果,繼續正常運作

設計取捨

決策理由
Effect Service 而非一般模組LSP 狀態需要跟隨 Instance 生命週期(專案開啟時初始化,關閉時清理)。Instance.state() + Effect.addFinalizer 確保客戶端連線與子行程在專案關閉時被正確清理
broken 集合而非重試Language Server 啟動失敗通常是因為二進位檔不存在、連接埠衝突等環境問題。重複嘗試只會浪費時間與資源,不如直接標記略過
spawning Map 去重並行的 getClients 呼叫(如 Agent 同時編輯多個 .ts 檔案)必須共用同一個 spawn Promise,否則會啟動多個相同的 Language Server 行程
150ms 去抖診斷Language Server 通常先推送語法診斷(基於 AST),再推送語意診斷(基於型別檢查)。去抖確保 Agent 看到完整的診斷集合
3 秒總逾時Agent 不能因為 LSP 回應慢而無限等待。3 秒是「診斷通常足夠完整」與「Agent 不能等太久」的平衡點
NearestRoot 高階函式不同伺服器需要偵測不同的設定檔,高階函式抽象了這個模式。排除模式(如 TypeScript 排除 deno.json)處理語言伺服器之間的衝突
30+ 內建伺服器主流開發語言開箱即用是 OpenCode 的核心賣點。使用者也可以透過 Config.lsp 新增自訂伺服器或停用內建伺服器
自動下載而非報錯缺少 Language Server 二進位檔時自動下載(如 Biome、Deno)優於報錯結束。Flag.OPENCODE_DISABLE_LSP_DOWNLOAD 允許使用者在受限環境中停用此行為
workspaceSymbol 過濾到 10 筆Agent 的上下文視窗有限,過多符號會稀釋有效資訊。過濾到 Class/Function/Method/Enum 等關鍵類型並限制 10 筆,是資訊密度與完整性的平衡

狀態管理與生命週期

InstanceState 初始化

LSP 狀態透過 Instance.state() 建立惰性載入單例:

// index.ts — 狀態初始化(簡化)
const instanceState = Instance.state(async () => {
  const cfg = await Config.get()

  // 1. 收集內建伺服器定義
  const servers: Record<string, LSPServer.Info> = {}
  for (const server of builtInServers) {
    servers[server.id] = server
  }

  // 2. 合併使用者自訂伺服器設定
  if (cfg.lsp) {
    for (const [id, custom] of Object.entries(cfg.lsp)) {
      if (custom.disabled) {
        delete servers[id]  // 停用內建伺服器
        continue
      }
      // 覆寫內建伺服器的 command、extensions、env、initialization 等
      if (servers[id]) {
        servers[id] = mergeServerConfig(servers[id], custom)
      } else {
        servers[id] = createCustomServer(id, custom)
      }
    }
  }

  // 3. 全域停用檢查
  if (cfg.lsp === false) {
    return { clients: [], servers: {}, broken: new Set(), spawning: new Map() }
  }

  return { clients: [], servers, broken: new Set(), spawning: new Map() }
})

Effect.addFinalizer 清理

// index.ts — 生命週期清理(簡化)
Effect.addFinalizer(async () => {
  const state = await instanceState()
  for (const client of state.clients) {
    await LSPClient.shutdown(client)
  }
  state.clients = []
  state.broken.clear()
  state.spawning.clear()
})

當 Instance(專案)關閉時,所有 LSP 客戶端連線被中斷,子行程被終止。

LSPClient.shutdown — 連線關閉

// client.ts — 關閉流程(簡化)
async function shutdown(client: LSPClient.Info): Promise<void> {
  try {
    // 1. 送出 shutdown 請求(優雅關閉)
    await withTimeout(
      client.connection.sendRequest("shutdown"),
      5000,
    )
    // 2. 送出 exit 通知
    client.connection.sendNotification("exit")
  } catch {
    // 逾時或錯誤 → 強制終止行程
  } finally {
    // 3. 關閉連線
    client.connection.dispose()
    // 4. 終止子行程
    client.process.kill()
  }
}

與其他模組的關係

  • Agent:Agent 在編輯檔案後呼叫 LSP.touchFile() 並透過 LSP.diagnostics() 取得最新診斷,協助判斷是否需要修復程式碼。hover() 和 definition() 幫助 Agent 理解符號的語意
  • Session / SessionPrompt:SessionPrompt 在建構使用者訊息時呼叫 LSP.documentSymbol() 和 LSP.workspaceSymbol() 為 LLM 提供程式碼結構概覽
  • Bus:LSP 透過 Bus.publish(Event.Diagnostics) 和 BusEvent.define("lsp.client.diagnostics") 通知診斷狀態變更,上層模組(Agent、UI)訂閱這些事件
  • Config:Config.lsp 定義啟用的伺服器、自訂命令與環境變數;cfg.lsp === false 可全域停用整個 LSP 模組
  • Instance:LSP 狀態透過 Instance.state() 管理,跟隨專案實例的生命週期。Instance.directory 是 NearestRoot 搜尋的邊界
  • Global/Flag:Global.Path.bin 存放自動下載的 Language Server 二進位檔;Flag.OPENCODE_DISABLE_LSP_DOWNLOAD 控制是否允許自動下載
  • Process:launch.ts 中的 spawn() 函式封裝 Process.spawn(),統一處理子行程啟動的錯誤處理與環境變數注入