braid-coding-agent 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- braid_coding_agent/__init__.py +13 -0
- braid_coding_agent/assembly.py +460 -0
- braid_coding_agent/cancellation.py +25 -0
- braid_coding_agent/checkpoint/__init__.py +106 -0
- braid_coding_agent/checkpoint/git.py +305 -0
- braid_coding_agent/checkpoint/settings.py +26 -0
- braid_coding_agent/checkpoint/store.py +1261 -0
- braid_coding_agent/checkpoint/workspace.py +220 -0
- braid_coding_agent/cli.py +2168 -0
- braid_coding_agent/commands/__init__.py +50 -0
- braid_coding_agent/commands/auth.py +161 -0
- braid_coding_agent/commands/config.py +180 -0
- braid_coding_agent/commands/doctor.py +511 -0
- braid_coding_agent/commands/mcp.py +928 -0
- braid_coding_agent/commands/models.py +95 -0
- braid_coding_agent/commands/setup.py +89 -0
- braid_coding_agent/commands/uninstall.py +277 -0
- braid_coding_agent/commands/upgrade.py +381 -0
- braid_coding_agent/compaction/__init__.py +174 -0
- braid_coding_agent/compaction/prepare.py +430 -0
- braid_coding_agent/compaction/summarize.py +542 -0
- braid_coding_agent/compaction/tokens.py +204 -0
- braid_coding_agent/compaction/tool_results.py +196 -0
- braid_coding_agent/compaction/utils.py +181 -0
- braid_coding_agent/config.py +2776 -0
- braid_coding_agent/config_files.py +191 -0
- braid_coding_agent/credentials.py +252 -0
- braid_coding_agent/discovery.py +415 -0
- braid_coding_agent/extensions/__init__.py +77 -0
- braid_coding_agent/extensions/api.py +480 -0
- braid_coding_agent/extensions/runner.py +553 -0
- braid_coding_agent/formatting/__init__.py +62 -0
- braid_coding_agent/formatting/settings.py +87 -0
- braid_coding_agent/formatting/tool.py +179 -0
- braid_coding_agent/lsp/__init__.py +105 -0
- braid_coding_agent/lsp/client.py +546 -0
- braid_coding_agent/lsp/manager.py +187 -0
- braid_coding_agent/lsp/model.py +316 -0
- braid_coding_agent/lsp/protocol.py +105 -0
- braid_coding_agent/lsp/settings.py +120 -0
- braid_coding_agent/lsp/tool.py +429 -0
- braid_coding_agent/mcp/__init__.py +101 -0
- braid_coding_agent/mcp/cache.py +230 -0
- braid_coding_agent/mcp/catalog.py +108 -0
- braid_coding_agent/mcp/config.py +664 -0
- braid_coding_agent/mcp/config_store.py +142 -0
- braid_coding_agent/mcp/inspector.py +85 -0
- braid_coding_agent/mcp/panel.py +254 -0
- braid_coding_agent/mcp/runtime.py +1060 -0
- braid_coding_agent/mcp/tools.py +579 -0
- braid_coding_agent/mcp/trust.py +150 -0
- braid_coding_agent/mcp/tui_panel.py +444 -0
- braid_coding_agent/messages.py +152 -0
- braid_coding_agent/models_view.py +105 -0
- braid_coding_agent/modes/__init__.py +64 -0
- braid_coding_agent/modes/json_mode.py +480 -0
- braid_coding_agent/modes/lifecycle.py +217 -0
- braid_coding_agent/modes/print_mode.py +257 -0
- braid_coding_agent/modes/repl.py +2687 -0
- braid_coding_agent/modes/repl_commands.py +263 -0
- braid_coding_agent/modes/rpc.py +953 -0
- braid_coding_agent/modes/skill_commands.py +88 -0
- braid_coding_agent/modes/tui.py +2226 -0
- braid_coding_agent/modes/tui_control.py +90 -0
- braid_coding_agent/modes/tui_model.py +1043 -0
- braid_coding_agent/modes/tui_render.py +327 -0
- braid_coding_agent/modes/tui_rich.py +751 -0
- braid_coding_agent/modes/tui_style.py +42 -0
- braid_coding_agent/modes/wire.py +81 -0
- braid_coding_agent/netsafe.py +82 -0
- braid_coding_agent/network/__init__.py +20 -0
- braid_coding_agent/network/cache.py +77 -0
- braid_coding_agent/network/fetch.py +311 -0
- braid_coding_agent/network/html_text.py +160 -0
- braid_coding_agent/network/search.py +347 -0
- braid_coding_agent/network/settings.py +103 -0
- braid_coding_agent/network/urls.py +89 -0
- braid_coding_agent/observability/__init__.py +101 -0
- braid_coding_agent/observability/audit.py +124 -0
- braid_coding_agent/observability/collector.py +314 -0
- braid_coding_agent/observability/exporter.py +74 -0
- braid_coding_agent/observability/logging_setup.py +149 -0
- braid_coding_agent/observability/redaction.py +96 -0
- braid_coding_agent/observability/settings.py +29 -0
- braid_coding_agent/observability/spans.py +239 -0
- braid_coding_agent/permissions/__init__.py +185 -0
- braid_coding_agent/permissions/command.py +586 -0
- braid_coding_agent/permissions/engine.py +522 -0
- braid_coding_agent/permissions/evaluate.py +309 -0
- braid_coding_agent/permissions/matching.py +233 -0
- braid_coding_agent/permissions/model.py +278 -0
- braid_coding_agent/permissions/policy.py +99 -0
- braid_coding_agent/permissions/readonly.py +236 -0
- braid_coding_agent/permissions/store.py +379 -0
- braid_coding_agent/project_init.py +313 -0
- braid_coding_agent/prompt/__init__.py +98 -0
- braid_coding_agent/prompt/context_files.py +253 -0
- braid_coding_agent/prompt/project_context.py +172 -0
- braid_coding_agent/prompt/system_prompt.py +378 -0
- braid_coding_agent/questions.py +71 -0
- braid_coding_agent/render/__init__.py +56 -0
- braid_coding_agent/render/batch.py +66 -0
- braid_coding_agent/render/history.py +143 -0
- braid_coding_agent/render/stream.py +823 -0
- braid_coding_agent/render/theme.py +243 -0
- braid_coding_agent/sandbox/__init__.py +89 -0
- braid_coding_agent/sandbox/backend.py +184 -0
- braid_coding_agent/sandbox/bubblewrap.py +96 -0
- braid_coding_agent/sandbox/operations.py +301 -0
- braid_coding_agent/sandbox/policy.py +221 -0
- braid_coding_agent/sandbox/proxy.py +320 -0
- braid_coding_agent/sandbox/seatbelt.py +222 -0
- braid_coding_agent/sdk/__init__.py +31 -0
- braid_coding_agent/sdk/async_client.py +366 -0
- braid_coding_agent/sdk/client.py +386 -0
- braid_coding_agent/sdk/errors.py +52 -0
- braid_coding_agent/sdk/events.py +162 -0
- braid_coding_agent/sdk/types.py +63 -0
- braid_coding_agent/sdk/wire.py +59 -0
- braid_coding_agent/server/__init__.py +54 -0
- braid_coding_agent/server/errors.py +52 -0
- braid_coding_agent/server/http_server.py +419 -0
- braid_coding_agent/server/hub.py +530 -0
- braid_coding_agent/server/openapi.py +157 -0
- braid_coding_agent/server/registry.py +354 -0
- braid_coding_agent/server/router.py +275 -0
- braid_coding_agent/server/run.py +148 -0
- braid_coding_agent/server/schema.py +194 -0
- braid_coding_agent/server/service.py +975 -0
- braid_coding_agent/session/__init__.py +293 -0
- braid_coding_agent/session/agent_session.py +2706 -0
- braid_coding_agent/session/context_breakdown.py +302 -0
- braid_coding_agent/session/discovery.py +212 -0
- braid_coding_agent/session/entries.py +809 -0
- braid_coding_agent/session/evidence.py +295 -0
- braid_coding_agent/session/lock.py +176 -0
- braid_coding_agent/session/manager.py +1185 -0
- braid_coding_agent/session/plan.py +243 -0
- braid_coding_agent/session/plan_mode.py +423 -0
- braid_coding_agent/session/projection.py +262 -0
- braid_coding_agent/session/rewind.py +257 -0
- braid_coding_agent/session/status.py +240 -0
- braid_coding_agent/settings.py +94 -0
- braid_coding_agent/skills/__init__.py +70 -0
- braid_coding_agent/skills/loader.py +681 -0
- braid_coding_agent/startup/__init__.py +76 -0
- braid_coding_agent/startup/cache.py +72 -0
- braid_coding_agent/startup/diagnostics.py +37 -0
- braid_coding_agent/startup/monitor.py +245 -0
- braid_coding_agent/startup/phases.py +79 -0
- braid_coding_agent/startup/project.py +165 -0
- braid_coding_agent/startup/report.py +560 -0
- braid_coding_agent/startup/scheduler.py +347 -0
- braid_coding_agent/statusline.py +163 -0
- braid_coding_agent/subagents/__init__.py +22 -0
- braid_coding_agent/subagents/contract.py +75 -0
- braid_coding_agent/subagents/definitions.py +583 -0
- braid_coding_agent/subagents/registry.py +277 -0
- braid_coding_agent/subagents/runtime.py +610 -0
- braid_coding_agent/subagents/settings.py +156 -0
- braid_coding_agent/subagents/worktree.py +63 -0
- braid_coding_agent/tools/__init__.py +327 -0
- braid_coding_agent/tools/args.py +87 -0
- braid_coding_agent/tools/bash.py +359 -0
- braid_coding_agent/tools/edit.py +298 -0
- braid_coding_agent/tools/edit_diff.py +344 -0
- braid_coding_agent/tools/find.py +158 -0
- braid_coding_agent/tools/grep.py +305 -0
- braid_coding_agent/tools/ignore.py +198 -0
- braid_coding_agent/tools/ls.py +127 -0
- braid_coding_agent/tools/mutation_queue.py +90 -0
- braid_coding_agent/tools/operations.py +274 -0
- braid_coding_agent/tools/output_accumulator.py +282 -0
- braid_coding_agent/tools/output_store.py +244 -0
- braid_coding_agent/tools/path_utils.py +91 -0
- braid_coding_agent/tools/plan.py +141 -0
- braid_coding_agent/tools/prompt_notes.py +52 -0
- braid_coding_agent/tools/question.py +180 -0
- braid_coding_agent/tools/read.py +223 -0
- braid_coding_agent/tools/submit_plan.py +102 -0
- braid_coding_agent/tools/truncate.py +423 -0
- braid_coding_agent/tools/write.py +100 -0
- braid_coding_agent/untrusted.py +50 -0
- braid_coding_agent/verify/__init__.py +78 -0
- braid_coding_agent/verify/runner.py +260 -0
- braid_coding_agent/verify/settings.py +64 -0
- braid_coding_agent/verify/tool.py +143 -0
- braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
- braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
- braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
- braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
- braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,546 @@
|
|
|
1
|
+
"""一台语言服务器的连接:spawn、握手、请求、诊断缓存、关闭。
|
|
2
|
+
|
|
3
|
+
## 为什么自己实现 JSON-RPC 客户端
|
|
4
|
+
|
|
5
|
+
``braid_mcp`` 里有一个形态相近的客户端,但两者的消息面没有交集:MCP 是
|
|
6
|
+
``tools/list`` 与 ``tools/call``,LSP 是 ``textDocument/*`` 与服务器主动推送的
|
|
7
|
+
``publishDiagnostics``。把两台协议塞进一个泛化客户端,只会得到一个两边都要
|
|
8
|
+
写条件的抽象。共用的部分(分帧、错误分类)抽在 :mod:`.protocol`。
|
|
9
|
+
|
|
10
|
+
## 文档版本与诊断的对应关系
|
|
11
|
+
|
|
12
|
+
诊断是服务器**主动推送**的:我们发 ``didOpen`` / ``didChange``,它过一会儿发
|
|
13
|
+
``publishDiagnostics``。中间没有请求-响应配对,因此需要一个匹配规则,否则会把上一次
|
|
14
|
+
的分析结果当成这一次的。
|
|
15
|
+
|
|
16
|
+
规则用两层:每次推送记一个全局递增序号,请求诊断前记下当前序号;只接受"序号更大
|
|
17
|
+
且 ``version`` 不小于自己刚发的版本"的推送。服务器不回 ``version`` 时退回"序号更大"
|
|
18
|
+
这一条。内容没变时直接读缓存,不重发 ``didChange``——否则模型连问两次诊断,第二次
|
|
19
|
+
必然等到超时。
|
|
20
|
+
|
|
21
|
+
## 全文同步
|
|
22
|
+
|
|
23
|
+
服务器通常声明增量同步(``textDocumentSync = 2``),但 LSP 规范允许 ``didChange``
|
|
24
|
+
只带 ``text`` 字段表示"整篇替换",pyright、ruff、gopls 都接受这种写法。这里一律发
|
|
25
|
+
全文:算增量 diff 需要维护一份镜像并正确处理 UTF-16 偏移,收益只是少传几 KB。
|
|
26
|
+
|
|
27
|
+
## 生命周期
|
|
28
|
+
|
|
29
|
+
第一次用到某个扩展名时才启动服务器(懒启动)。请求超时或进程退出一律**关掉整个
|
|
30
|
+
客户端**,下一次调用重新启动:一个卡在分析里的进程没法被复用,而"半死的客户端"
|
|
31
|
+
会让后续每次调用都超时。启动参数、工作区根与文档版本都随客户端丢弃,重启后从
|
|
32
|
+
``didOpen`` 重来,状态不会错位。
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import asyncio
|
|
38
|
+
import contextlib
|
|
39
|
+
import hashlib
|
|
40
|
+
import os
|
|
41
|
+
import signal
|
|
42
|
+
from collections.abc import Mapping
|
|
43
|
+
from pathlib import Path
|
|
44
|
+
from urllib.parse import quote
|
|
45
|
+
|
|
46
|
+
from braid_ai.cancel import CancelToken
|
|
47
|
+
from braid_ai.types import JsonValue
|
|
48
|
+
from braid_coding_agent.cancellation import OperationAborted
|
|
49
|
+
from braid_coding_agent.lsp.model import (
|
|
50
|
+
Diagnostic,
|
|
51
|
+
Location,
|
|
52
|
+
Symbol,
|
|
53
|
+
diagnostic_from_wire,
|
|
54
|
+
locations_from_wire,
|
|
55
|
+
path_from_uri,
|
|
56
|
+
symbols_from_document_wire,
|
|
57
|
+
symbols_from_workspace_wire,
|
|
58
|
+
)
|
|
59
|
+
from braid_coding_agent.lsp.protocol import (
|
|
60
|
+
MAX_HEADER_LINE_BYTES,
|
|
61
|
+
MAX_MESSAGE_BYTES,
|
|
62
|
+
LspError,
|
|
63
|
+
LspProtocolError,
|
|
64
|
+
LspResponseError,
|
|
65
|
+
LspServerGone,
|
|
66
|
+
LspTimeout,
|
|
67
|
+
decode_message,
|
|
68
|
+
encode_message,
|
|
69
|
+
)
|
|
70
|
+
from braid_coding_agent.lsp.settings import SHUTDOWN_TIMEOUT_SECONDS, LspServerSettings
|
|
71
|
+
|
|
72
|
+
#: 轮询间隔(秒)。取消令牌与诊断推送都靠它检查,50ms 的粒度对交互无感。
|
|
73
|
+
_POLL_SECONDS = 0.05
|
|
74
|
+
#: 保留的 stderr 行数。服务器崩溃时这几行通常就是全部线索。
|
|
75
|
+
_STDERR_TAIL_LINES = 20
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class LspClient:
|
|
79
|
+
"""一台语言服务器的进程内代理。非线程安全:只在事件循环里用。"""
|
|
80
|
+
|
|
81
|
+
def __init__(self, settings: LspServerSettings, *, root: str) -> None:
|
|
82
|
+
self._settings = settings
|
|
83
|
+
self._root = root
|
|
84
|
+
self._process: asyncio.subprocess.Process | None = None
|
|
85
|
+
self._reader_task: asyncio.Task[None] | None = None
|
|
86
|
+
self._stderr_task: asyncio.Task[None] | None = None
|
|
87
|
+
#: 回复服务器请求的后台任务。持引用,避免被 GC 提前回收。
|
|
88
|
+
self._replies: set[asyncio.Task[None]] = set()
|
|
89
|
+
self._pending: dict[int, asyncio.Future[dict[str, JsonValue]]] = {}
|
|
90
|
+
self._next_id = 1
|
|
91
|
+
self._gone_reason: str | None = None
|
|
92
|
+
self._stderr: list[str] = []
|
|
93
|
+
#: URI → 已发送的文档版本。
|
|
94
|
+
self._versions: dict[str, int] = {}
|
|
95
|
+
#: URI → 已发送内容的摘要。内容没变就不重发。
|
|
96
|
+
self._digests: dict[str, str] = {}
|
|
97
|
+
#: URI → (推送序号, 服务器回的版本, 诊断)。
|
|
98
|
+
self._published: dict[str, tuple[int, int | None, tuple[Diagnostic, ...]]] = {}
|
|
99
|
+
self._seq = 0
|
|
100
|
+
|
|
101
|
+
# ------------------------------------------------------------- 只读状态
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def settings(self) -> LspServerSettings:
|
|
105
|
+
return self._settings
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def root(self) -> str:
|
|
109
|
+
return self._root
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def alive(self) -> bool:
|
|
113
|
+
return self._process is not None and self._process.returncode is None
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def stderr_tail(self) -> str:
|
|
117
|
+
return "\n".join(self._stderr[-_STDERR_TAIL_LINES:])
|
|
118
|
+
|
|
119
|
+
# --------------------------------------------------------------- 生命周期
|
|
120
|
+
|
|
121
|
+
async def start(self) -> None:
|
|
122
|
+
"""spawn 服务器并完成 ``initialize`` 握手。失败时进程已被清理。"""
|
|
123
|
+
if self._process is not None:
|
|
124
|
+
raise RuntimeError(f"语言服务器 {self._settings.name} 已经启动")
|
|
125
|
+
try:
|
|
126
|
+
self._process = await asyncio.create_subprocess_exec(
|
|
127
|
+
*self._settings.command,
|
|
128
|
+
cwd=self._root,
|
|
129
|
+
env={**os.environ, **self._settings.env},
|
|
130
|
+
stdin=asyncio.subprocess.PIPE,
|
|
131
|
+
stdout=asyncio.subprocess.PIPE,
|
|
132
|
+
stderr=asyncio.subprocess.PIPE,
|
|
133
|
+
start_new_session=True,
|
|
134
|
+
)
|
|
135
|
+
except FileNotFoundError as exc:
|
|
136
|
+
raise LspServerGone(
|
|
137
|
+
f"无法启动语言服务器 {self._settings.name}:找不到可执行文件 "
|
|
138
|
+
f"{self._settings.command[0]}(检查 lsp.{self._settings.name}.command)"
|
|
139
|
+
) from exc
|
|
140
|
+
except OSError as exc:
|
|
141
|
+
raise LspServerGone(f"无法启动语言服务器 {self._settings.name}:{exc}") from exc
|
|
142
|
+
|
|
143
|
+
self._reader_task = asyncio.create_task(self._read_loop())
|
|
144
|
+
self._stderr_task = asyncio.create_task(self._stderr_loop())
|
|
145
|
+
try:
|
|
146
|
+
await self._request("initialize", self._initialize_params())
|
|
147
|
+
except LspError:
|
|
148
|
+
await self.close()
|
|
149
|
+
raise
|
|
150
|
+
await self._notify("initialized", {})
|
|
151
|
+
|
|
152
|
+
def _initialize_params(self) -> dict[str, JsonValue]:
|
|
153
|
+
root_uri = _file_uri(self._root)
|
|
154
|
+
return {
|
|
155
|
+
"processId": os.getpid(),
|
|
156
|
+
"clientInfo": {"name": "braid"},
|
|
157
|
+
"rootUri": root_uri,
|
|
158
|
+
# 只给 rootUri 时,部分服务器(包括 pyright)会把工作区根落到自己的安装
|
|
159
|
+
# 目录上,项目配置与解释器全部按错的根解析。workspaceFolders 是权威写法。
|
|
160
|
+
"workspaceFolders": [{"uri": root_uri, "name": Path(self._root).name or "root"}],
|
|
161
|
+
"initializationOptions": dict(self._settings.initialization_options),
|
|
162
|
+
"capabilities": _client_capabilities(),
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async def close(self) -> None:
|
|
166
|
+
"""尽力优雅关闭,然后确保进程组被清理。可以重复调用。"""
|
|
167
|
+
if self._process is None:
|
|
168
|
+
return
|
|
169
|
+
# 两条退出消息都可能失败(进程已经退出、管道已关),这里不关心原因:
|
|
170
|
+
# 紧接着的 _terminate 才是收尾的保证。
|
|
171
|
+
try:
|
|
172
|
+
await self._request("shutdown", None, timeout=SHUTDOWN_TIMEOUT_SECONDS)
|
|
173
|
+
await self._notify("exit", None)
|
|
174
|
+
except LspError:
|
|
175
|
+
pass
|
|
176
|
+
await self._terminate()
|
|
177
|
+
|
|
178
|
+
async def _terminate(self) -> None:
|
|
179
|
+
process = self._process
|
|
180
|
+
self._process = None
|
|
181
|
+
self._fail_pending("语言服务器已关闭")
|
|
182
|
+
for task in (self._reader_task, self._stderr_task):
|
|
183
|
+
if task is not None:
|
|
184
|
+
task.cancel()
|
|
185
|
+
self._reader_task = None
|
|
186
|
+
self._stderr_task = None
|
|
187
|
+
if process is None:
|
|
188
|
+
return
|
|
189
|
+
if process.returncode is None:
|
|
190
|
+
with contextlib.suppress(ProcessLookupError):
|
|
191
|
+
process.kill()
|
|
192
|
+
try:
|
|
193
|
+
await asyncio.wait_for(process.wait(), timeout=SHUTDOWN_TIMEOUT_SECONDS)
|
|
194
|
+
except TimeoutError:
|
|
195
|
+
_kill_process_group(process.pid)
|
|
196
|
+
await process.wait()
|
|
197
|
+
|
|
198
|
+
# ------------------------------------------------------------------ 请求
|
|
199
|
+
|
|
200
|
+
async def _request(
|
|
201
|
+
self,
|
|
202
|
+
method: str,
|
|
203
|
+
params: JsonValue,
|
|
204
|
+
*,
|
|
205
|
+
timeout: float | None = None,
|
|
206
|
+
signal: CancelToken | None = None,
|
|
207
|
+
) -> JsonValue:
|
|
208
|
+
"""发一条请求并等结果。取消与超时都会抛出,调用方负责关掉客户端。"""
|
|
209
|
+
process = self._process
|
|
210
|
+
if process is None or process.returncode is not None:
|
|
211
|
+
raise LspServerGone(self._gone_message("语言服务器没有运行"))
|
|
212
|
+
|
|
213
|
+
request_id = self._next_id
|
|
214
|
+
self._next_id += 1
|
|
215
|
+
future: asyncio.Future[dict[str, JsonValue]] = asyncio.get_running_loop().create_future()
|
|
216
|
+
self._pending[request_id] = future
|
|
217
|
+
try:
|
|
218
|
+
await self._send(
|
|
219
|
+
{"jsonrpc": "2.0", "id": request_id, "method": method, "params": params}
|
|
220
|
+
)
|
|
221
|
+
message = await self._wait(future, method, timeout, signal=signal)
|
|
222
|
+
finally:
|
|
223
|
+
self._pending.pop(request_id, None)
|
|
224
|
+
|
|
225
|
+
if "error" in message:
|
|
226
|
+
raise _response_error(method, message["error"])
|
|
227
|
+
return message.get("result")
|
|
228
|
+
|
|
229
|
+
async def _notify(self, method: str, params: JsonValue) -> None:
|
|
230
|
+
await self._send({"jsonrpc": "2.0", "method": method, "params": params})
|
|
231
|
+
|
|
232
|
+
async def _send(self, payload: dict[str, JsonValue]) -> None:
|
|
233
|
+
process = self._process
|
|
234
|
+
if process is None or process.stdin is None:
|
|
235
|
+
raise LspServerGone(self._gone_message("语言服务器没有运行"))
|
|
236
|
+
try:
|
|
237
|
+
process.stdin.write(encode_message(payload))
|
|
238
|
+
await process.stdin.drain()
|
|
239
|
+
except (BrokenPipeError, ConnectionResetError) as exc:
|
|
240
|
+
self._gone_reason = f"写入语言服务器失败:{exc}"
|
|
241
|
+
raise LspServerGone(self._gone_message("写入失败")) from exc
|
|
242
|
+
|
|
243
|
+
async def _wait(
|
|
244
|
+
self,
|
|
245
|
+
future: asyncio.Future[dict[str, JsonValue]],
|
|
246
|
+
method: str,
|
|
247
|
+
timeout: float | None,
|
|
248
|
+
*,
|
|
249
|
+
signal: CancelToken | None,
|
|
250
|
+
) -> dict[str, JsonValue]:
|
|
251
|
+
"""等一个 future,同时响应取消与超时。"""
|
|
252
|
+
limit = self._settings.timeout_seconds if timeout is None else timeout
|
|
253
|
+
loop = asyncio.get_running_loop()
|
|
254
|
+
deadline = loop.time() + limit
|
|
255
|
+
while True:
|
|
256
|
+
if future.done():
|
|
257
|
+
return future.result()
|
|
258
|
+
if signal is not None and signal.cancelled:
|
|
259
|
+
future.cancel()
|
|
260
|
+
raise OperationAborted(f"{method} aborted")
|
|
261
|
+
if loop.time() >= deadline:
|
|
262
|
+
future.cancel()
|
|
263
|
+
raise LspTimeout(method, limit)
|
|
264
|
+
await asyncio.sleep(_POLL_SECONDS)
|
|
265
|
+
|
|
266
|
+
# --------------------------------------------------------------- 文档同步
|
|
267
|
+
|
|
268
|
+
async def sync(self, path: str, text: str) -> int:
|
|
269
|
+
"""把磁盘上的内容推给服务器。返回这次使用的文档版本。
|
|
270
|
+
|
|
271
|
+
内容没变时什么都不发,直接返回当前版本——重复的 ``didChange`` 会让服务器
|
|
272
|
+
重新分析一遍,而结果与上一次相同。
|
|
273
|
+
"""
|
|
274
|
+
uri = _file_uri(path)
|
|
275
|
+
digest = _digest(text)
|
|
276
|
+
current = self._versions.get(uri)
|
|
277
|
+
if current is None:
|
|
278
|
+
await self._notify(
|
|
279
|
+
"textDocument/didOpen",
|
|
280
|
+
{
|
|
281
|
+
"textDocument": {
|
|
282
|
+
"uri": uri,
|
|
283
|
+
"languageId": self._settings.language_id,
|
|
284
|
+
"version": 1,
|
|
285
|
+
"text": text,
|
|
286
|
+
}
|
|
287
|
+
},
|
|
288
|
+
)
|
|
289
|
+
self._versions[uri] = 1
|
|
290
|
+
self._digests[uri] = digest
|
|
291
|
+
return 1
|
|
292
|
+
if self._digests.get(uri) == digest:
|
|
293
|
+
return current
|
|
294
|
+
version = current + 1
|
|
295
|
+
await self._notify(
|
|
296
|
+
"textDocument/didChange",
|
|
297
|
+
{
|
|
298
|
+
"textDocument": {"uri": uri, "version": version},
|
|
299
|
+
# 全文替换:range 省略即表示整篇更新。
|
|
300
|
+
"contentChanges": [{"text": text}],
|
|
301
|
+
},
|
|
302
|
+
)
|
|
303
|
+
self._versions[uri] = version
|
|
304
|
+
self._digests[uri] = digest
|
|
305
|
+
return version
|
|
306
|
+
|
|
307
|
+
async def diagnostics(
|
|
308
|
+
self, path: str, text: str, *, signal: CancelToken | None = None
|
|
309
|
+
) -> tuple[Diagnostic, ...]:
|
|
310
|
+
"""确保服务器看过这份内容,返回它推送的诊断。"""
|
|
311
|
+
uri = _file_uri(path)
|
|
312
|
+
baseline = self._seq
|
|
313
|
+
unchanged = self._digests.get(uri) == _digest(text)
|
|
314
|
+
version = await self.sync(path, text)
|
|
315
|
+
if unchanged:
|
|
316
|
+
cached = self._published.get(uri)
|
|
317
|
+
if cached is not None and (cached[1] is None or cached[1] >= version):
|
|
318
|
+
return cached[2]
|
|
319
|
+
return await self._await_publish(uri, version, baseline, signal)
|
|
320
|
+
|
|
321
|
+
async def _await_publish(
|
|
322
|
+
self, uri: str, version: int, baseline: int, signal: CancelToken | None
|
|
323
|
+
) -> tuple[Diagnostic, ...]:
|
|
324
|
+
loop = asyncio.get_running_loop()
|
|
325
|
+
deadline = loop.time() + self._settings.timeout_seconds
|
|
326
|
+
while True:
|
|
327
|
+
published = self._published.get(uri)
|
|
328
|
+
if published is not None:
|
|
329
|
+
seq, published_version, items = published
|
|
330
|
+
if seq > baseline and (published_version is None or published_version >= version):
|
|
331
|
+
return items
|
|
332
|
+
if not self.alive:
|
|
333
|
+
# 进程已经退出:再等到超时只会把一个明确原因拖成"超时"。
|
|
334
|
+
raise LspServerGone(self._gone_message("语言服务器在分析期间退出"))
|
|
335
|
+
if signal is not None and signal.cancelled:
|
|
336
|
+
raise OperationAborted("diagnostics aborted")
|
|
337
|
+
if loop.time() >= deadline:
|
|
338
|
+
raise LspTimeout("textDocument/publishDiagnostics", self._settings.timeout_seconds)
|
|
339
|
+
await asyncio.sleep(_POLL_SECONDS)
|
|
340
|
+
|
|
341
|
+
# --------------------------------------------------------------- 查询动作
|
|
342
|
+
|
|
343
|
+
async def definition(
|
|
344
|
+
self, path: str, line: int, column: int, *, signal: CancelToken | None = None
|
|
345
|
+
) -> list[Location]:
|
|
346
|
+
result = await self._request(
|
|
347
|
+
"textDocument/definition",
|
|
348
|
+
_position_params(path, line, column),
|
|
349
|
+
signal=signal,
|
|
350
|
+
)
|
|
351
|
+
return locations_from_wire(result)
|
|
352
|
+
|
|
353
|
+
async def references(
|
|
354
|
+
self, path: str, line: int, column: int, *, signal: CancelToken | None = None
|
|
355
|
+
) -> list[Location]:
|
|
356
|
+
params = _position_params(path, line, column)
|
|
357
|
+
params["context"] = {"includeDeclaration": True}
|
|
358
|
+
result = await self._request("textDocument/references", params, signal=signal)
|
|
359
|
+
return locations_from_wire(result)
|
|
360
|
+
|
|
361
|
+
async def document_symbols(
|
|
362
|
+
self, path: str, *, signal: CancelToken | None = None
|
|
363
|
+
) -> list[Symbol]:
|
|
364
|
+
result = await self._request(
|
|
365
|
+
"textDocument/documentSymbol",
|
|
366
|
+
{"textDocument": {"uri": _file_uri(path)}},
|
|
367
|
+
signal=signal,
|
|
368
|
+
)
|
|
369
|
+
return symbols_from_document_wire(result)
|
|
370
|
+
|
|
371
|
+
async def workspace_symbols(
|
|
372
|
+
self, query: str, *, signal: CancelToken | None = None
|
|
373
|
+
) -> list[Symbol]:
|
|
374
|
+
result = await self._request("workspace/symbol", {"query": query}, signal=signal)
|
|
375
|
+
return symbols_from_workspace_wire(result)
|
|
376
|
+
|
|
377
|
+
# ------------------------------------------------------------- 读与分发
|
|
378
|
+
|
|
379
|
+
async def _read_loop(self) -> None:
|
|
380
|
+
process = self._process
|
|
381
|
+
if process is None or process.stdout is None:
|
|
382
|
+
return
|
|
383
|
+
stream = process.stdout
|
|
384
|
+
try:
|
|
385
|
+
while True:
|
|
386
|
+
self._dispatch(await _read_message(stream))
|
|
387
|
+
except asyncio.CancelledError:
|
|
388
|
+
raise
|
|
389
|
+
except (LspError, asyncio.IncompleteReadError, ConnectionResetError, OSError) as exc:
|
|
390
|
+
self._gone_reason = str(exc) or type(exc).__name__
|
|
391
|
+
self._fail_pending(self._gone_message("语言服务器连接中断"))
|
|
392
|
+
|
|
393
|
+
def _dispatch(self, message: dict[str, JsonValue]) -> None:
|
|
394
|
+
method = message.get("method")
|
|
395
|
+
request_id = message.get("id")
|
|
396
|
+
if isinstance(method, str):
|
|
397
|
+
if request_id is not None:
|
|
398
|
+
# 服务器发来的请求(注册能力、创建工作进度、读配置)。规范允许回 null,
|
|
399
|
+
# 回得越少越不容易踩到各家的私有约定;主要作用是别让它等在那里。
|
|
400
|
+
self._schedule_reply(request_id)
|
|
401
|
+
return
|
|
402
|
+
self._handle_notification(method, message.get("params"))
|
|
403
|
+
return
|
|
404
|
+
if isinstance(request_id, int):
|
|
405
|
+
future = self._pending.get(request_id)
|
|
406
|
+
if future is not None and not future.done():
|
|
407
|
+
future.set_result(message)
|
|
408
|
+
|
|
409
|
+
def _schedule_reply(self, request_id: JsonValue) -> None:
|
|
410
|
+
task = asyncio.create_task(self._send({"jsonrpc": "2.0", "id": request_id, "result": None}))
|
|
411
|
+
self._replies.add(task)
|
|
412
|
+
task.add_done_callback(self._replies.discard)
|
|
413
|
+
|
|
414
|
+
def _handle_notification(self, method: str, params: JsonValue) -> None:
|
|
415
|
+
if method != "textDocument/publishDiagnostics" or not isinstance(params, dict):
|
|
416
|
+
return
|
|
417
|
+
uri = params.get("uri")
|
|
418
|
+
if not isinstance(uri, str):
|
|
419
|
+
return
|
|
420
|
+
self._seq += 1
|
|
421
|
+
path = path_from_uri(uri)
|
|
422
|
+
raw_items = params.get("diagnostics")
|
|
423
|
+
items = (
|
|
424
|
+
tuple(diagnostic_from_wire(path, item) for item in raw_items)
|
|
425
|
+
if isinstance(raw_items, list)
|
|
426
|
+
else ()
|
|
427
|
+
)
|
|
428
|
+
version_value = params.get("version")
|
|
429
|
+
version = version_value if isinstance(version_value, int) else None
|
|
430
|
+
self._published[uri] = (self._seq, version, items)
|
|
431
|
+
|
|
432
|
+
def _fail_pending(self, reason: str) -> None:
|
|
433
|
+
pending = list(self._pending.values())
|
|
434
|
+
self._pending.clear()
|
|
435
|
+
for future in pending:
|
|
436
|
+
if not future.done():
|
|
437
|
+
future.set_exception(LspServerGone(reason))
|
|
438
|
+
|
|
439
|
+
async def _stderr_loop(self) -> None:
|
|
440
|
+
process = self._process
|
|
441
|
+
if process is None or process.stderr is None:
|
|
442
|
+
return
|
|
443
|
+
while True:
|
|
444
|
+
line = await process.stderr.readline()
|
|
445
|
+
if not line:
|
|
446
|
+
return
|
|
447
|
+
self._stderr.append(line.decode("utf-8", errors="replace").rstrip())
|
|
448
|
+
|
|
449
|
+
def _gone_message(self, prefix: str) -> str:
|
|
450
|
+
pieces = [f"{prefix}({self._settings.name})"]
|
|
451
|
+
if self._gone_reason:
|
|
452
|
+
pieces.append(self._gone_reason)
|
|
453
|
+
tail = self.stderr_tail
|
|
454
|
+
if tail:
|
|
455
|
+
pieces.append(f"stderr: {tail}")
|
|
456
|
+
return ";".join(pieces)
|
|
457
|
+
|
|
458
|
+
def __repr__(self) -> str:
|
|
459
|
+
state = "alive" if self.alive else "dead"
|
|
460
|
+
return f"LspClient({self._settings.name!r}, root={self._root!r}, {state})"
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
async def _read_message(stream: asyncio.StreamReader) -> dict[str, JsonValue]:
|
|
464
|
+
"""读一条 LSP 帧。头部按规范逐行解析,只认 ``Content-Length``。"""
|
|
465
|
+
length: int | None = None
|
|
466
|
+
while True:
|
|
467
|
+
try:
|
|
468
|
+
line = await stream.readline()
|
|
469
|
+
except ValueError as exc:
|
|
470
|
+
raise LspProtocolError(f"消息头部超长:{exc}") from exc
|
|
471
|
+
if not line:
|
|
472
|
+
raise LspServerGone("语言服务器关闭了输出")
|
|
473
|
+
if len(line) > MAX_HEADER_LINE_BYTES:
|
|
474
|
+
raise LspProtocolError(f"消息头部单行超过 {MAX_HEADER_LINE_BYTES} 字节")
|
|
475
|
+
stripped = line.strip()
|
|
476
|
+
if not stripped:
|
|
477
|
+
break
|
|
478
|
+
name, _, value = stripped.partition(b":")
|
|
479
|
+
if name.strip().lower() == b"content-length":
|
|
480
|
+
try:
|
|
481
|
+
length = int(value.strip())
|
|
482
|
+
except ValueError as exc:
|
|
483
|
+
raise LspProtocolError(f"非法的 Content-Length:{value!r}") from exc
|
|
484
|
+
if length is None:
|
|
485
|
+
raise LspProtocolError("消息缺少 Content-Length 头部")
|
|
486
|
+
if length <= 0 or length > MAX_MESSAGE_BYTES:
|
|
487
|
+
raise LspProtocolError(f"消息长度 {length} 超出允许范围")
|
|
488
|
+
return decode_message(await stream.readexactly(length))
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def _client_capabilities() -> dict[str, JsonValue]:
|
|
492
|
+
"""只声明我们真的会用的能力。
|
|
493
|
+
|
|
494
|
+
不声明 ``textDocument.diagnostic``(拉取诊断):一旦声明,部分服务器就不再推送
|
|
495
|
+
``publishDiagnostics``,而推送是兼容面最广的那条路。
|
|
496
|
+
"""
|
|
497
|
+
return {
|
|
498
|
+
"workspace": {"workspaceFolders": True, "symbol": {}},
|
|
499
|
+
"textDocument": {
|
|
500
|
+
"publishDiagnostics": {"relatedInformation": True, "versionSupport": True},
|
|
501
|
+
"definition": {"linkSupport": True},
|
|
502
|
+
"references": {},
|
|
503
|
+
"documentSymbol": {"hierarchicalDocumentSymbolSupport": True},
|
|
504
|
+
},
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def _position_params(path: str, line: int, column: int) -> dict[str, JsonValue]:
|
|
509
|
+
"""工具层用 1 基行列,LSP 用 0 基;减一集中在这里做一次。"""
|
|
510
|
+
return {
|
|
511
|
+
"textDocument": {"uri": _file_uri(path)},
|
|
512
|
+
"position": {"line": line - 1, "character": column - 1},
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _response_error(method: str, error: JsonValue) -> LspResponseError:
|
|
517
|
+
details: Mapping[str, JsonValue] = error if isinstance(error, dict) else {}
|
|
518
|
+
code = details.get("code")
|
|
519
|
+
text = details.get("message")
|
|
520
|
+
return LspResponseError(
|
|
521
|
+
method,
|
|
522
|
+
code if isinstance(code, int) else 0,
|
|
523
|
+
text if isinstance(text, str) else str(error),
|
|
524
|
+
)
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def _file_uri(path: str) -> str:
|
|
528
|
+
"""绝对路径 → ``file://`` URI,转义空格与中文。"""
|
|
529
|
+
normalized = path.replace(os.sep, "/")
|
|
530
|
+
if not normalized.startswith("/"):
|
|
531
|
+
normalized = f"/{normalized}"
|
|
532
|
+
return f"file://{quote(normalized, safe='/:@')}"
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def _digest(text: str) -> str:
|
|
536
|
+
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def _kill_process_group(pid: int) -> None:
|
|
540
|
+
try:
|
|
541
|
+
os.killpg(os.getpgid(pid), signal.SIGKILL)
|
|
542
|
+
except ProcessLookupError:
|
|
543
|
+
return
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
__all__ = ["LspClient"]
|