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.
Files changed (192) hide show
  1. braid_coding_agent/__init__.py +13 -0
  2. braid_coding_agent/assembly.py +460 -0
  3. braid_coding_agent/cancellation.py +25 -0
  4. braid_coding_agent/checkpoint/__init__.py +106 -0
  5. braid_coding_agent/checkpoint/git.py +305 -0
  6. braid_coding_agent/checkpoint/settings.py +26 -0
  7. braid_coding_agent/checkpoint/store.py +1261 -0
  8. braid_coding_agent/checkpoint/workspace.py +220 -0
  9. braid_coding_agent/cli.py +2168 -0
  10. braid_coding_agent/commands/__init__.py +50 -0
  11. braid_coding_agent/commands/auth.py +161 -0
  12. braid_coding_agent/commands/config.py +180 -0
  13. braid_coding_agent/commands/doctor.py +511 -0
  14. braid_coding_agent/commands/mcp.py +928 -0
  15. braid_coding_agent/commands/models.py +95 -0
  16. braid_coding_agent/commands/setup.py +89 -0
  17. braid_coding_agent/commands/uninstall.py +277 -0
  18. braid_coding_agent/commands/upgrade.py +381 -0
  19. braid_coding_agent/compaction/__init__.py +174 -0
  20. braid_coding_agent/compaction/prepare.py +430 -0
  21. braid_coding_agent/compaction/summarize.py +542 -0
  22. braid_coding_agent/compaction/tokens.py +204 -0
  23. braid_coding_agent/compaction/tool_results.py +196 -0
  24. braid_coding_agent/compaction/utils.py +181 -0
  25. braid_coding_agent/config.py +2776 -0
  26. braid_coding_agent/config_files.py +191 -0
  27. braid_coding_agent/credentials.py +252 -0
  28. braid_coding_agent/discovery.py +415 -0
  29. braid_coding_agent/extensions/__init__.py +77 -0
  30. braid_coding_agent/extensions/api.py +480 -0
  31. braid_coding_agent/extensions/runner.py +553 -0
  32. braid_coding_agent/formatting/__init__.py +62 -0
  33. braid_coding_agent/formatting/settings.py +87 -0
  34. braid_coding_agent/formatting/tool.py +179 -0
  35. braid_coding_agent/lsp/__init__.py +105 -0
  36. braid_coding_agent/lsp/client.py +546 -0
  37. braid_coding_agent/lsp/manager.py +187 -0
  38. braid_coding_agent/lsp/model.py +316 -0
  39. braid_coding_agent/lsp/protocol.py +105 -0
  40. braid_coding_agent/lsp/settings.py +120 -0
  41. braid_coding_agent/lsp/tool.py +429 -0
  42. braid_coding_agent/mcp/__init__.py +101 -0
  43. braid_coding_agent/mcp/cache.py +230 -0
  44. braid_coding_agent/mcp/catalog.py +108 -0
  45. braid_coding_agent/mcp/config.py +664 -0
  46. braid_coding_agent/mcp/config_store.py +142 -0
  47. braid_coding_agent/mcp/inspector.py +85 -0
  48. braid_coding_agent/mcp/panel.py +254 -0
  49. braid_coding_agent/mcp/runtime.py +1060 -0
  50. braid_coding_agent/mcp/tools.py +579 -0
  51. braid_coding_agent/mcp/trust.py +150 -0
  52. braid_coding_agent/mcp/tui_panel.py +444 -0
  53. braid_coding_agent/messages.py +152 -0
  54. braid_coding_agent/models_view.py +105 -0
  55. braid_coding_agent/modes/__init__.py +64 -0
  56. braid_coding_agent/modes/json_mode.py +480 -0
  57. braid_coding_agent/modes/lifecycle.py +217 -0
  58. braid_coding_agent/modes/print_mode.py +257 -0
  59. braid_coding_agent/modes/repl.py +2687 -0
  60. braid_coding_agent/modes/repl_commands.py +263 -0
  61. braid_coding_agent/modes/rpc.py +953 -0
  62. braid_coding_agent/modes/skill_commands.py +88 -0
  63. braid_coding_agent/modes/tui.py +2226 -0
  64. braid_coding_agent/modes/tui_control.py +90 -0
  65. braid_coding_agent/modes/tui_model.py +1043 -0
  66. braid_coding_agent/modes/tui_render.py +327 -0
  67. braid_coding_agent/modes/tui_rich.py +751 -0
  68. braid_coding_agent/modes/tui_style.py +42 -0
  69. braid_coding_agent/modes/wire.py +81 -0
  70. braid_coding_agent/netsafe.py +82 -0
  71. braid_coding_agent/network/__init__.py +20 -0
  72. braid_coding_agent/network/cache.py +77 -0
  73. braid_coding_agent/network/fetch.py +311 -0
  74. braid_coding_agent/network/html_text.py +160 -0
  75. braid_coding_agent/network/search.py +347 -0
  76. braid_coding_agent/network/settings.py +103 -0
  77. braid_coding_agent/network/urls.py +89 -0
  78. braid_coding_agent/observability/__init__.py +101 -0
  79. braid_coding_agent/observability/audit.py +124 -0
  80. braid_coding_agent/observability/collector.py +314 -0
  81. braid_coding_agent/observability/exporter.py +74 -0
  82. braid_coding_agent/observability/logging_setup.py +149 -0
  83. braid_coding_agent/observability/redaction.py +96 -0
  84. braid_coding_agent/observability/settings.py +29 -0
  85. braid_coding_agent/observability/spans.py +239 -0
  86. braid_coding_agent/permissions/__init__.py +185 -0
  87. braid_coding_agent/permissions/command.py +586 -0
  88. braid_coding_agent/permissions/engine.py +522 -0
  89. braid_coding_agent/permissions/evaluate.py +309 -0
  90. braid_coding_agent/permissions/matching.py +233 -0
  91. braid_coding_agent/permissions/model.py +278 -0
  92. braid_coding_agent/permissions/policy.py +99 -0
  93. braid_coding_agent/permissions/readonly.py +236 -0
  94. braid_coding_agent/permissions/store.py +379 -0
  95. braid_coding_agent/project_init.py +313 -0
  96. braid_coding_agent/prompt/__init__.py +98 -0
  97. braid_coding_agent/prompt/context_files.py +253 -0
  98. braid_coding_agent/prompt/project_context.py +172 -0
  99. braid_coding_agent/prompt/system_prompt.py +378 -0
  100. braid_coding_agent/questions.py +71 -0
  101. braid_coding_agent/render/__init__.py +56 -0
  102. braid_coding_agent/render/batch.py +66 -0
  103. braid_coding_agent/render/history.py +143 -0
  104. braid_coding_agent/render/stream.py +823 -0
  105. braid_coding_agent/render/theme.py +243 -0
  106. braid_coding_agent/sandbox/__init__.py +89 -0
  107. braid_coding_agent/sandbox/backend.py +184 -0
  108. braid_coding_agent/sandbox/bubblewrap.py +96 -0
  109. braid_coding_agent/sandbox/operations.py +301 -0
  110. braid_coding_agent/sandbox/policy.py +221 -0
  111. braid_coding_agent/sandbox/proxy.py +320 -0
  112. braid_coding_agent/sandbox/seatbelt.py +222 -0
  113. braid_coding_agent/sdk/__init__.py +31 -0
  114. braid_coding_agent/sdk/async_client.py +366 -0
  115. braid_coding_agent/sdk/client.py +386 -0
  116. braid_coding_agent/sdk/errors.py +52 -0
  117. braid_coding_agent/sdk/events.py +162 -0
  118. braid_coding_agent/sdk/types.py +63 -0
  119. braid_coding_agent/sdk/wire.py +59 -0
  120. braid_coding_agent/server/__init__.py +54 -0
  121. braid_coding_agent/server/errors.py +52 -0
  122. braid_coding_agent/server/http_server.py +419 -0
  123. braid_coding_agent/server/hub.py +530 -0
  124. braid_coding_agent/server/openapi.py +157 -0
  125. braid_coding_agent/server/registry.py +354 -0
  126. braid_coding_agent/server/router.py +275 -0
  127. braid_coding_agent/server/run.py +148 -0
  128. braid_coding_agent/server/schema.py +194 -0
  129. braid_coding_agent/server/service.py +975 -0
  130. braid_coding_agent/session/__init__.py +293 -0
  131. braid_coding_agent/session/agent_session.py +2706 -0
  132. braid_coding_agent/session/context_breakdown.py +302 -0
  133. braid_coding_agent/session/discovery.py +212 -0
  134. braid_coding_agent/session/entries.py +809 -0
  135. braid_coding_agent/session/evidence.py +295 -0
  136. braid_coding_agent/session/lock.py +176 -0
  137. braid_coding_agent/session/manager.py +1185 -0
  138. braid_coding_agent/session/plan.py +243 -0
  139. braid_coding_agent/session/plan_mode.py +423 -0
  140. braid_coding_agent/session/projection.py +262 -0
  141. braid_coding_agent/session/rewind.py +257 -0
  142. braid_coding_agent/session/status.py +240 -0
  143. braid_coding_agent/settings.py +94 -0
  144. braid_coding_agent/skills/__init__.py +70 -0
  145. braid_coding_agent/skills/loader.py +681 -0
  146. braid_coding_agent/startup/__init__.py +76 -0
  147. braid_coding_agent/startup/cache.py +72 -0
  148. braid_coding_agent/startup/diagnostics.py +37 -0
  149. braid_coding_agent/startup/monitor.py +245 -0
  150. braid_coding_agent/startup/phases.py +79 -0
  151. braid_coding_agent/startup/project.py +165 -0
  152. braid_coding_agent/startup/report.py +560 -0
  153. braid_coding_agent/startup/scheduler.py +347 -0
  154. braid_coding_agent/statusline.py +163 -0
  155. braid_coding_agent/subagents/__init__.py +22 -0
  156. braid_coding_agent/subagents/contract.py +75 -0
  157. braid_coding_agent/subagents/definitions.py +583 -0
  158. braid_coding_agent/subagents/registry.py +277 -0
  159. braid_coding_agent/subagents/runtime.py +610 -0
  160. braid_coding_agent/subagents/settings.py +156 -0
  161. braid_coding_agent/subagents/worktree.py +63 -0
  162. braid_coding_agent/tools/__init__.py +327 -0
  163. braid_coding_agent/tools/args.py +87 -0
  164. braid_coding_agent/tools/bash.py +359 -0
  165. braid_coding_agent/tools/edit.py +298 -0
  166. braid_coding_agent/tools/edit_diff.py +344 -0
  167. braid_coding_agent/tools/find.py +158 -0
  168. braid_coding_agent/tools/grep.py +305 -0
  169. braid_coding_agent/tools/ignore.py +198 -0
  170. braid_coding_agent/tools/ls.py +127 -0
  171. braid_coding_agent/tools/mutation_queue.py +90 -0
  172. braid_coding_agent/tools/operations.py +274 -0
  173. braid_coding_agent/tools/output_accumulator.py +282 -0
  174. braid_coding_agent/tools/output_store.py +244 -0
  175. braid_coding_agent/tools/path_utils.py +91 -0
  176. braid_coding_agent/tools/plan.py +141 -0
  177. braid_coding_agent/tools/prompt_notes.py +52 -0
  178. braid_coding_agent/tools/question.py +180 -0
  179. braid_coding_agent/tools/read.py +223 -0
  180. braid_coding_agent/tools/submit_plan.py +102 -0
  181. braid_coding_agent/tools/truncate.py +423 -0
  182. braid_coding_agent/tools/write.py +100 -0
  183. braid_coding_agent/untrusted.py +50 -0
  184. braid_coding_agent/verify/__init__.py +78 -0
  185. braid_coding_agent/verify/runner.py +260 -0
  186. braid_coding_agent/verify/settings.py +64 -0
  187. braid_coding_agent/verify/tool.py +143 -0
  188. braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
  189. braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
  190. braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
  191. braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
  192. braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,187 @@
1
+ """语言服务器的路由与复用:一个文件该交给谁、服务器什么时候启动、失败后怎么办。
2
+
3
+ 路由只看扩展名:按配置顺序取第一台 ``enabled`` 且声明了这个扩展名的服务器。多台服务器
4
+ 抢同一个扩展名时先声明的赢——"只想用 ruff 的服务器"靠 ``enabled = false`` 表达,
5
+ 不靠调整顺序碰运气。
6
+
7
+ 工作区根按 ``root_markers`` 从文件所在目录向上找。找到的根决定服务器的项目配置与
8
+ 解释器:根定在仓库根,``pyproject.toml`` 里的 ``[tool.pyright]`` 与虚拟环境才会生效。
9
+ 没有任何标记时用会话的工作目录。``workspace/symbol`` 没有具体文件,按工作目录找根。
10
+
11
+ 客户端按 ``(服务器名, 根)`` 缓存并复用。同一个根上的十次诊断调用共享一个进程——
12
+ 每次调用重启服务器会让每次等待都变成冷启动。操作失败时(超时、进程退出、协议错乱)
13
+ **丢弃**那个客户端:卡在分析里的进程留着重用只会让后续调用连着超时,下一次调用
14
+ 重新 spawn,状态从 ``didOpen`` 重来。
15
+
16
+ 文件内容由本层读取(线程池里读,不阻塞事件循环),读完之后先 ``sync`` 再查询。
17
+ 理由:语言服务器的所有 ``textDocument/*`` 请求都假设文件"已经打开",没打开的文件
18
+ 在部分服务器上会返回空结果;而磁盘上的内容可能刚被 ``edit`` 改过,服务器手上的
19
+ 版本已经过期。
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import asyncio
25
+ import os
26
+ from collections.abc import Coroutine, Sequence
27
+ from typing import TypeVar
28
+
29
+ from braid_ai.cancel import CancelToken
30
+ from braid_coding_agent.lsp.client import LspClient
31
+ from braid_coding_agent.lsp.model import Diagnostic, Location, Symbol
32
+ from braid_coding_agent.lsp.protocol import (
33
+ LspProtocolError,
34
+ LspServerGone,
35
+ LspTimeout,
36
+ )
37
+ from braid_coding_agent.lsp.settings import LspServerSettings, LspSettings
38
+
39
+ T = TypeVar("T")
40
+
41
+ #: 需要重启客户端的失败:超时(可能卡在分析里)、进程没了、对面说的不是 LSP。
42
+ _RESTART_ERRORS = (LspTimeout, LspServerGone, LspProtocolError)
43
+
44
+
45
+ class LspManager:
46
+ """一次进程运行内的全部语言服务器。惰性启动,按根复用。"""
47
+
48
+ def __init__(self, settings: LspSettings, *, cwd: str) -> None:
49
+ self._settings = settings
50
+ self._cwd = cwd
51
+ self._clients: dict[tuple[str, str], LspClient] = {}
52
+
53
+ @property
54
+ def settings(self) -> LspSettings:
55
+ return self._settings
56
+
57
+ @property
58
+ def cwd(self) -> str:
59
+ """会话工作目录:没有 ``root_markers`` 命中时用它当工作区根。"""
60
+ return self._cwd
61
+
62
+ def server_for(self, path: str) -> LspServerSettings | None:
63
+ return self._settings.server_for(path)
64
+
65
+ def describe(self) -> str:
66
+ """给错误消息与 ``/status`` 用的一行摘要。"""
67
+ return self._settings.describe()
68
+
69
+ # -------------------------------------------------------------------- 查询
70
+
71
+ async def diagnostics(
72
+ self, path: str, *, signal: CancelToken | None = None
73
+ ) -> tuple[Diagnostic, ...]:
74
+ client = await self._client_for_path(path)
75
+ text = await _read_text(path)
76
+ return await self._guard(client, client.diagnostics(path, text, signal=signal))
77
+
78
+ async def definition(
79
+ self, path: str, line: int, column: int, *, signal: CancelToken | None = None
80
+ ) -> list[Location]:
81
+ client = await self._client_for_path(path)
82
+ text = await _read_text(path)
83
+ await self._guard(client, client.sync(path, text))
84
+ return await self._guard(client, client.definition(path, line, column, signal=signal))
85
+
86
+ async def references(
87
+ self, path: str, line: int, column: int, *, signal: CancelToken | None = None
88
+ ) -> list[Location]:
89
+ client = await self._client_for_path(path)
90
+ text = await _read_text(path)
91
+ await self._guard(client, client.sync(path, text))
92
+ return await self._guard(client, client.references(path, line, column, signal=signal))
93
+
94
+ async def document_symbols(
95
+ self, path: str, *, signal: CancelToken | None = None
96
+ ) -> list[Symbol]:
97
+ client = await self._client_for_path(path)
98
+ text = await _read_text(path)
99
+ await self._guard(client, client.sync(path, text))
100
+ return await self._guard(client, client.document_symbols(path, signal=signal))
101
+
102
+ async def workspace_symbols(
103
+ self, query: str, *, signal: CancelToken | None = None
104
+ ) -> list[Symbol]:
105
+ """工作区符号搜索。没有具体文件可依,用第一台启用的服务器与工作目录的根。"""
106
+ servers = self._settings.enabled_servers
107
+ if not servers:
108
+ raise LspServerGone(f"没有启用的语言服务器({self._settings.describe()})")
109
+ server = servers[0]
110
+ root = _find_root(
111
+ os.path.join(self._cwd, f"workspace{server.extensions[0]}"),
112
+ server.root_markers,
113
+ fallback=self._cwd,
114
+ )
115
+ client = await self._client_for(server, root)
116
+ return await self._guard(client, client.workspace_symbols(query, signal=signal))
117
+
118
+ # ---------------------------------------------------------------- 生命周期
119
+
120
+ async def close(self) -> None:
121
+ """关闭全部客户端。进程退出前调用。"""
122
+ clients = list(self._clients.values())
123
+ self._clients.clear()
124
+ for client in clients:
125
+ await client.close()
126
+
127
+ # ------------------------------------------------------------------ 内部
128
+
129
+ async def _client_for_path(self, path: str) -> LspClient:
130
+ server = self._settings.server_for(path)
131
+ if server is None:
132
+ raise LspServerGone(
133
+ f"没有语言服务器处理 {os.path.splitext(path)[1] or '无扩展名文件'}"
134
+ f"(已配置:{self._settings.describe()})"
135
+ )
136
+ root = _find_root(path, server.root_markers, fallback=self._cwd)
137
+ return await self._client_for(server, root)
138
+
139
+ async def _client_for(self, server: LspServerSettings, root: str) -> LspClient:
140
+ key = (server.name, root)
141
+ client = self._clients.get(key)
142
+ if client is not None and not client.alive:
143
+ await client.close()
144
+ self._clients.pop(key, None)
145
+ client = None
146
+ if client is None:
147
+ client = LspClient(server, root=root)
148
+ await client.start()
149
+ self._clients[key] = client
150
+ return client
151
+
152
+ async def _guard(self, client: LspClient, awaitable: Coroutine[object, object, T]) -> T:
153
+ """执行一个客户端操作;可恢复的失败丢掉客户端后原样抛出。"""
154
+ try:
155
+ return await awaitable
156
+ except _RESTART_ERRORS:
157
+ for key, cached in list(self._clients.items()):
158
+ if cached is client:
159
+ self._clients.pop(key, None)
160
+ await client.close()
161
+ raise
162
+
163
+
164
+ async def _read_text(path: str) -> str:
165
+ return await asyncio.to_thread(_read_file, path)
166
+
167
+
168
+ def _read_file(path: str) -> str:
169
+ with open(path, encoding="utf-8", errors="replace") as handle:
170
+ return handle.read()
171
+
172
+
173
+ def _find_root(path: str, markers: Sequence[str], *, fallback: str) -> str:
174
+ """从文件所在目录向上找第一个含标记文件的目录。找不到用 ``fallback``。"""
175
+ if not markers:
176
+ return fallback
177
+ current = os.path.dirname(os.path.abspath(path)) or fallback
178
+ while True:
179
+ if any(os.path.exists(os.path.join(current, marker)) for marker in markers):
180
+ return current
181
+ parent = os.path.dirname(current)
182
+ if parent == current:
183
+ return fallback
184
+ current = parent
185
+
186
+
187
+ __all__ = ["LspManager"]
@@ -0,0 +1,316 @@
1
+ """把 LSP 的线上对象收窄成四种模型:诊断、位置、符号、文档。
2
+
3
+ 线上格式有几个"同一概念多种形状"的地方,工具层不该各自处理:
4
+
5
+ - ``textDocument/definition`` 可以回 ``Location``、``Location[]`` 或 ``LocationLink[]``
6
+ (后者带 ``targetUri`` / ``targetSelectionRange``);
7
+ - ``textDocument/documentSymbol`` 可以回嵌套的 ``DocumentSymbol[]``(带 ``children``),
8
+ 也可以回平铺的 ``SymbolInformation[]``(带 ``location`` 与 ``containerName``);
9
+ - 位置是 **0 基**(``line`` 与 ``character`` 都从 0 开始),而人读的 ``file:line:col``
10
+ 是 1 基。转换只在这里做一次:两处各转一次,总有一处会多减一。
11
+ - 诊断的 ``severity`` 是 1–4 的整数,缺省表示 ``error``(规范原话)。
12
+
13
+ 字符串一律转成 posix 路径;``file://`` URI 的百分号转义要解掉,否则中文目录会变成
14
+ 一串 ``%E4%B8%AD`` 摆在模型面前。
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from dataclasses import dataclass
20
+ from typing import Final, Literal
21
+ from urllib.parse import unquote, urlparse
22
+
23
+ from braid_ai.types import JsonValue
24
+ from braid_coding_agent.lsp.protocol import LspProtocolError
25
+
26
+ #: 诊断级别,按严重程度从高到低。工具按它过滤与排序。
27
+ type Severity = Literal["error", "warning", "info", "hint"]
28
+
29
+ SEVERITIES: tuple[Severity, ...] = ("error", "warning", "info", "hint")
30
+
31
+ _SEVERITY_BY_CODE: Final[dict[int, Severity]] = {
32
+ 1: "error",
33
+ 2: "warning",
34
+ 3: "info",
35
+ 4: "hint",
36
+ }
37
+ _SEVERITY_RANK: Final[dict[Severity, int]] = {
38
+ severity: index for index, severity in enumerate(SEVERITIES)
39
+ }
40
+
41
+ #: LSP 的 SymbolKind。只用于把数字翻译成模型读得懂的一行标签。
42
+ _SYMBOL_KINDS: Final[dict[int, str]] = {
43
+ 1: "file",
44
+ 2: "module",
45
+ 3: "namespace",
46
+ 4: "package",
47
+ 5: "class",
48
+ 6: "method",
49
+ 7: "property",
50
+ 8: "field",
51
+ 9: "constructor",
52
+ 10: "enum",
53
+ 11: "interface",
54
+ 12: "function",
55
+ 13: "variable",
56
+ 14: "constant",
57
+ 15: "string",
58
+ 16: "number",
59
+ 17: "boolean",
60
+ 18: "array",
61
+ 19: "object",
62
+ 20: "key",
63
+ 21: "null",
64
+ 22: "enum member",
65
+ 23: "struct",
66
+ 24: "event",
67
+ 25: "operator",
68
+ 26: "type parameter",
69
+ }
70
+
71
+
72
+ @dataclass(slots=True, frozen=True)
73
+ class Diagnostic:
74
+ """一条诊断。``line`` 与 ``column`` 都是 1 基。"""
75
+
76
+ path: str
77
+ line: int
78
+ column: int
79
+ severity: Severity
80
+ message: str
81
+ code: str | None = None
82
+ source: str | None = None
83
+
84
+ @property
85
+ def rank(self) -> int:
86
+ return _SEVERITY_RANK[self.severity]
87
+
88
+
89
+ @dataclass(slots=True, frozen=True)
90
+ class Location:
91
+ """一个可跳转的位置。``line`` 与 ``column`` 都是 1 基。"""
92
+
93
+ path: str
94
+ line: int
95
+ column: int
96
+
97
+
98
+ @dataclass(slots=True, frozen=True)
99
+ class Symbol:
100
+ """文档或工作区里的一个符号。``children`` 只在分层返回时非空。
101
+
102
+ ``path`` 只有工作区搜索会填:文档符号的路径就是请求时给的那个文件,再写一遍
103
+ 只是重复。
104
+ """
105
+
106
+ name: str
107
+ kind: str
108
+ line: int
109
+ detail: str = ""
110
+ path: str = ""
111
+ children: tuple[Symbol, ...] = ()
112
+
113
+
114
+ def severity_from_code(code: int | None) -> Severity:
115
+ """规范说 ``severity`` 缺省时按 error 处理。"""
116
+ if code is None:
117
+ return "error"
118
+ return _SEVERITY_BY_CODE.get(code, "error")
119
+
120
+
121
+ def severity_at_least(severity: Severity, minimum: Severity) -> bool:
122
+ """``severity`` 是否达到 ``minimum`` 的严重程度(error 最严重)。"""
123
+ return _SEVERITY_RANK[severity] <= _SEVERITY_RANK[minimum]
124
+
125
+
126
+ def path_from_uri(uri: str) -> str:
127
+ """``file://`` URI → posix 路径,解百分号转义。
128
+
129
+ 非 ``file`` 协议(``untitled:``、``jdt:``)原样返回:工具层没法读它们,
130
+ 但把原始 URI 摆在结果里比抛异常有用。
131
+ """
132
+ parsed = urlparse(uri)
133
+ if parsed.scheme != "file":
134
+ return uri
135
+ path = unquote(parsed.path)
136
+ # Windows 的 ``file:///C:/x`` 会多一个前导斜杠。
137
+ if len(path) > 2 and path[0] == "/" and path[2] == ":":
138
+ return path[1:]
139
+ return path
140
+
141
+
142
+ def diagnostic_from_wire(path: str, item: JsonValue) -> Diagnostic:
143
+ """一条 ``PublishDiagnosticsParams.diagnostics`` 元素。"""
144
+ obj = _object(item, what="diagnostic")
145
+ start = _object(_object(obj.get("range"), what="diagnostic.range").get("start"), what="start")
146
+ code_value = obj.get("code")
147
+ code = str(code_value) if isinstance(code_value, str | int) else None
148
+ source_value = obj.get("source")
149
+ return Diagnostic(
150
+ path=path,
151
+ line=_integer(start.get("line"), what="start.line") + 1,
152
+ column=_integer(start.get("character"), what="start.character") + 1,
153
+ severity=severity_from_code(_optional_integer(obj.get("severity"), what="severity")),
154
+ message=_text(obj.get("message"), what="diagnostic.message"),
155
+ code=code,
156
+ source=source_value if isinstance(source_value, str) else None,
157
+ )
158
+
159
+
160
+ def locations_from_wire(item: JsonValue) -> list[Location]:
161
+ """``definition`` 的三种返回形状统一成位置列表。"""
162
+ if item is None:
163
+ return []
164
+ items = item if isinstance(item, list) else [item]
165
+ locations: list[Location] = []
166
+ for entry in items:
167
+ obj = _object(entry, what="location")
168
+ # LocationLink:目标在 ``targetUri`` + ``targetSelectionRange``。
169
+ if "targetUri" in obj:
170
+ uri = _text(obj.get("targetUri"), what="targetUri")
171
+ range_obj = _object(
172
+ obj.get("targetSelectionRange", obj.get("targetRange")),
173
+ what="targetSelectionRange",
174
+ )
175
+ else:
176
+ uri = _text(obj.get("uri"), what="location.uri")
177
+ range_obj = _object(obj.get("range"), what="location.range")
178
+ start = _object(range_obj.get("start"), what="range.start")
179
+ locations.append(
180
+ Location(
181
+ path=path_from_uri(uri),
182
+ line=_integer(start.get("line"), what="start.line") + 1,
183
+ column=_integer(start.get("character"), what="start.character") + 1,
184
+ )
185
+ )
186
+ return locations
187
+
188
+
189
+ def symbols_from_document_wire(item: JsonValue) -> list[Symbol]:
190
+ """``documentSymbol`` 的两种返回形状(嵌套 DocumentSymbol / 平铺 SymbolInformation)。"""
191
+ if item is None:
192
+ return []
193
+ symbols: list[Symbol] = []
194
+ for entry in _array(item, what="documentSymbol"):
195
+ symbols.append(_document_symbol(entry))
196
+ return symbols
197
+
198
+
199
+ def symbols_from_workspace_wire(item: JsonValue) -> list[Symbol]:
200
+ """``workspace/symbol`` 的元素。新版规范允许顶层直接给 ``location`` 或 ``uri``。"""
201
+ if item is None:
202
+ return []
203
+ symbols: list[Symbol] = []
204
+ for entry in _array(item, what="workspaceSymbol"):
205
+ obj = _object(entry, what="workspaceSymbol")
206
+ location = obj.get("location")
207
+ if isinstance(location, dict):
208
+ start = _object(
209
+ _object(location.get("range"), what="location.range").get("start"),
210
+ what="location.range.start",
211
+ )
212
+ path = path_from_uri(_text(location.get("uri"), what="location.uri"))
213
+ else:
214
+ # 只有 uri(没有位置)的条目:行号记 0,表示"位置未知"。
215
+ path = path_from_uri(_text(obj.get("uri"), what="uri")) if "uri" in obj else ""
216
+ start = {}
217
+ container = obj.get("containerName")
218
+ symbols.append(
219
+ Symbol(
220
+ name=_text(obj.get("name"), what="symbol.name"),
221
+ kind=_kind_name(obj.get("kind")),
222
+ line=_integer(start.get("line"), what="start.line") + 1 if start else 0,
223
+ detail=container if isinstance(container, str) else "",
224
+ path=path,
225
+ )
226
+ )
227
+ return symbols
228
+
229
+
230
+ def _document_symbol(item: JsonValue) -> Symbol:
231
+ obj = _object(item, what="documentSymbol")
232
+ # DocumentSymbol 用 range/selectionRange;SymbolInformation 用 location。
233
+ if "location" in obj:
234
+ location = _object(obj.get("location"), what="location")
235
+ start = _object(
236
+ _object(location.get("range"), what="location.range").get("start"),
237
+ what="location.range.start",
238
+ )
239
+ line = _integer(start.get("line"), what="start.line") + 1
240
+ container = obj.get("containerName")
241
+ detail = container if isinstance(container, str) else ""
242
+ return Symbol(
243
+ name=_text(obj.get("name"), what="symbol.name"),
244
+ kind=_kind_name(obj.get("kind")),
245
+ line=line,
246
+ detail=detail,
247
+ )
248
+ selection = _object(obj.get("selectionRange"), what="selectionRange")
249
+ start = _object(selection.get("start"), what="selectionRange.start")
250
+ detail_value = obj.get("detail")
251
+ children_value = obj.get("children")
252
+ children = (
253
+ tuple(_document_symbol(child) for child in _array(children_value, what="children"))
254
+ if children_value is not None
255
+ else ()
256
+ )
257
+ return Symbol(
258
+ name=_text(obj.get("name"), what="symbol.name"),
259
+ kind=_kind_name(obj.get("kind")),
260
+ line=_integer(start.get("line"), what="start.line") + 1,
261
+ detail=detail_value if isinstance(detail_value, str) else "",
262
+ children=children,
263
+ )
264
+
265
+
266
+ def _kind_name(value: JsonValue) -> str:
267
+ code = _optional_integer(value, what="symbol.kind")
268
+ if code is None:
269
+ return "symbol"
270
+ return _SYMBOL_KINDS.get(code, f"kind-{code}")
271
+
272
+
273
+ def _object(value: JsonValue, *, what: str) -> dict[str, JsonValue]:
274
+ if not isinstance(value, dict):
275
+ raise LspProtocolError(f"{what} 应为对象,收到 {type(value).__name__}")
276
+ return value
277
+
278
+
279
+ def _array(value: JsonValue, *, what: str) -> list[JsonValue]:
280
+ if not isinstance(value, list):
281
+ raise LspProtocolError(f"{what} 应为数组,收到 {type(value).__name__}")
282
+ return value
283
+
284
+
285
+ def _integer(value: JsonValue, *, what: str) -> int:
286
+ if isinstance(value, bool) or not isinstance(value, int):
287
+ raise LspProtocolError(f"{what} 应为整数,收到 {value!r}")
288
+ return value
289
+
290
+
291
+ def _optional_integer(value: JsonValue, *, what: str) -> int | None:
292
+ if value is None:
293
+ return None
294
+ return _integer(value, what=what)
295
+
296
+
297
+ def _text(value: JsonValue, *, what: str) -> str:
298
+ if not isinstance(value, str):
299
+ raise LspProtocolError(f"{what} 应为字符串,收到 {value!r}")
300
+ return value
301
+
302
+
303
+ __all__ = [
304
+ "SEVERITIES",
305
+ "Diagnostic",
306
+ "Location",
307
+ "Severity",
308
+ "Symbol",
309
+ "diagnostic_from_wire",
310
+ "locations_from_wire",
311
+ "path_from_uri",
312
+ "severity_at_least",
313
+ "severity_from_code",
314
+ "symbols_from_document_wire",
315
+ "symbols_from_workspace_wire",
316
+ ]
@@ -0,0 +1,105 @@
1
+ """LSP 的线上格式:``Content-Length`` 分帧与四类失败。
2
+
3
+ LSP 复用 JSON-RPC 2.0,但它把消息贴在一条字节流上,因此需要一个分帧层:
4
+
5
+ ```text
6
+ Content-Length: 137\r\n
7
+ \r\n
8
+ {"jsonrpc":"2.0","id":1,"result":{...}}
9
+ ```
10
+
11
+ 只认 ``Content-Length``。规范还允许 ``Content-Type``,但没有任何一个主流语言服务器
12
+ 会发它;写一个"能容忍未知头部"的解析器不增加兼容性,只增加一条没被测试过的分支。
13
+ 未知头部按规范跳过,缺失长度、长度非法、正文不是 JSON、正文不是对象,一律
14
+ :class:`LspProtocolError`——这些说明对面不是一个可用的语言服务器,继续读下去只会
15
+ 拿到半截消息。
16
+
17
+ 四类失败分开,是因为调用方对它们的处置不同:
18
+
19
+ | 异常 | 含义 | 调用方的动作 |
20
+ |---|---|---|
21
+ | :class:`LspServerGone` | 进程退出或管道关闭 | 丢弃客户端,下次调用重启 |
22
+ | :class:`LspProtocolError` | 对面说的不是 LSP | 同上,并把原因写进工具结果 |
23
+ | :class:`LspResponseError` | 服务器明确回了 ``error`` | 原样把方法与错误码给模型,通常重试无用 |
24
+ | :class:`LspTimeout` | 在预算内没等到响应 | 关掉客户端(可能卡在分析里),下次重启 |
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import json
30
+ from typing import Final
31
+
32
+ from braid_ai.types import JsonValue
33
+
34
+ #: 一条消息的长度上限(字节)。语言服务器不会发超过这个量的单条消息;真发了,说明
35
+ #: 流已经错位,继续读会把后续消息当成正文。
36
+ MAX_MESSAGE_BYTES: Final[int] = 32 * 1024 * 1024
37
+
38
+ #: 单行头部的长度上限。``StreamReader.readline`` 超过它直接抛 ``ValueError``。
39
+ MAX_HEADER_LINE_BYTES: Final[int] = 8 * 1024
40
+
41
+
42
+ class LspError(Exception):
43
+ """LSP 层失败的基类。工具把它翻成 ``is_error`` 结果。"""
44
+
45
+
46
+ class LspServerGone(LspError):
47
+ """语言服务器进程已经退出或关闭了输出管道。"""
48
+
49
+
50
+ class LspProtocolError(LspError):
51
+ """对面发来的字节不符合 LSP 分帧或 JSON-RPC 形状。"""
52
+
53
+
54
+ class LspResponseError(LspError):
55
+ """服务器对某个请求回了 ``error``。"""
56
+
57
+ def __init__(self, method: str, code: int, message: str) -> None:
58
+ super().__init__(f"{method} failed ({code}): {message}")
59
+ self.method = method
60
+ self.code = code
61
+ self.message = message
62
+
63
+
64
+ class LspTimeout(LspError):
65
+ """在预算内没有等到响应。"""
66
+
67
+ def __init__(self, method: str, seconds: float) -> None:
68
+ super().__init__(f"{method} timed out after {seconds:g}s")
69
+ self.method = method
70
+ self.seconds = seconds
71
+
72
+
73
+ def encode_message(payload: dict[str, JsonValue]) -> bytes:
74
+ """把一条 JSON-RPC 消息封成 LSP 帧。
75
+
76
+ ``ensure_ascii=False`` 让中文路径按 UTF-8 发出,字节数按编码后的长度算——
77
+ 长度写错会让对面永远等下去。
78
+ """
79
+ body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
80
+ return f"Content-Length: {len(body)}\r\n\r\n".encode("ascii") + body
81
+
82
+
83
+ def decode_message(body: bytes) -> dict[str, JsonValue]:
84
+ """把正文解析成 JSON 对象。数组或标量一律视为协议错误。"""
85
+ try:
86
+ parsed: JsonValue = json.loads(body)
87
+ except json.JSONDecodeError as exc:
88
+ preview = body[:200].decode("utf-8", errors="replace")
89
+ raise LspProtocolError(f"消息不是合法 JSON:{exc};开头是 {preview!r}") from exc
90
+ if not isinstance(parsed, dict):
91
+ raise LspProtocolError(f"消息必须是 JSON 对象,收到 {type(parsed).__name__}")
92
+ return parsed
93
+
94
+
95
+ __all__ = [
96
+ "MAX_HEADER_LINE_BYTES",
97
+ "MAX_MESSAGE_BYTES",
98
+ "LspError",
99
+ "LspProtocolError",
100
+ "LspResponseError",
101
+ "LspServerGone",
102
+ "LspTimeout",
103
+ "decode_message",
104
+ "encode_message",
105
+ ]