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,511 @@
1
+ """``braid doctor``:一条命令回答"这台机器上的 braid 能不能用,哪里不能用"。
2
+
3
+ ```text
4
+ [ok] 入口:/Users/roy/.local/bin/braid
5
+ [ok] Python:3.12.13(/Users/roy/.local/bin/python3.12)
6
+ [ok] 全局配置:/Users/roy/.braid/settings.json(版本 1)
7
+ [warn] 凭证:deepseek 未配置
8
+ 环境变量 DEEPSEEK_API_KEY 为空;运行 braid auth login deepseek 写入系统钥匙串
9
+ [ok] 沙箱:后端 seatbelt 可用(当前 mode = off,未启用)
10
+ ...
11
+ 检查完成:8 项通过,1 项建议处理,0 项必须处理
12
+ ```
13
+
14
+ ## 三档结论
15
+
16
+ - ``ok``:这项正常。
17
+ - ``warn``:不影响启动,但用户大概率想处理(缺凭证、缺沙箱后端、MCP 命令找不到)。
18
+ - ``fail``:现在就用不起来(Python 版本过低、配置读不出来、没有任何可用凭证、
19
+ 会话目录写不进去、默认模型不在目录里)。退出码为 1。
20
+
21
+ ``warn`` 不改变退出码:一台只做离线 faux 调试的机器没有 API Key 是正常的,让
22
+ ``doctor`` 因此失败会把"检查"变成"噪音"。
23
+
24
+ ## 不联网
25
+
26
+ ``doctor`` 只读本机状态:配置文件、环境变量、钥匙串、``PATH``、沙箱后端探测
27
+ (起一个最小 ``/bin/true``)。版本更新检查属于 ``braid upgrade --check``,
28
+ 启动路径与自检路径都不发模型请求、不查包索引。
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import json
34
+ import os
35
+ import shutil
36
+ import sys
37
+ from collections.abc import Mapping, Sequence
38
+ from dataclasses import dataclass, field
39
+ from pathlib import Path
40
+ from typing import Literal, TextIO
41
+ from urllib.parse import urlsplit
42
+
43
+ import braid_coding_agent
44
+ from braid_coding_agent import __version__
45
+ from braid_coding_agent.commands import CommandError, take_value
46
+ from braid_coding_agent.config import AgentConfig, ConfigError, load_config
47
+ from braid_coding_agent.config_files import CONFIG_FILE_NAME, PROJECT_CONFIG_DIR
48
+ from braid_coding_agent.credentials import Credentials, Keychain
49
+ from braid_coding_agent.mcp.config import load_mcp_config
50
+ from braid_coding_agent.sandbox.backend import SandboxUnavailableError, detect_backend
51
+ from braid_coding_agent.sandbox.policy import SandboxSettings
52
+ from braid_coding_agent.session.manager import default_session_dir
53
+
54
+ USAGE = """braid doctor [选项]
55
+ 检查本机安装:Python 版本、配置文件、凭证、沙箱后端、MCP 服务器与终端能力
56
+
57
+ 选项:
58
+ --json 以 JSON 输出全部检查项(脚本与 CI 用)
59
+ --cwd PATH 工作目录(决定项目配置与会话目录)
60
+ --config PATH 额外配置文件(可重复)
61
+ -h, --help 显示本帮助
62
+
63
+ 退出码: 0 全部必须项通过;1 有必须处理的问题"""
64
+
65
+ #: 程序声明的最低 Python 版本(与五个包的 ``requires-python`` 一致)。
66
+ REQUIRED_PYTHON: tuple[int, int] = (3, 12)
67
+
68
+ type CheckStatus = Literal["ok", "warn", "fail", "info"]
69
+
70
+ #: 输出顺序固定:先安装面,再配置面,最后运行环境。
71
+ _STATUS_LABELS: Mapping[CheckStatus, str] = {
72
+ "ok": "ok",
73
+ "warn": "warn",
74
+ "fail": "fail",
75
+ "info": "info",
76
+ }
77
+
78
+
79
+ @dataclass(slots=True, frozen=True)
80
+ class Check:
81
+ """一项检查结论。``hint`` 是用户接下来该做什么。"""
82
+
83
+ name: str
84
+ status: CheckStatus
85
+ detail: str
86
+ hint: str | None = None
87
+
88
+
89
+ @dataclass(slots=True, frozen=True)
90
+ class Environment:
91
+ """检查要用到的本机事实。测试注入一份具体取值,不替换检查逻辑。"""
92
+
93
+ agent_dir: Path
94
+ cwd: str
95
+ env: Mapping[str, str]
96
+ python_version: tuple[int, int, int]
97
+ executable: str
98
+ platform: str
99
+ isatty: bool
100
+ columns: int
101
+
102
+ @property
103
+ def python_text(self) -> str:
104
+ major, minor, patch = self.python_version
105
+ return f"{major}.{minor}.{patch}"
106
+
107
+
108
+ def current_environment(*, agent_dir: Path, cwd: str) -> Environment:
109
+ """从进程读一份事实。``doctor`` 的默认入口用它。"""
110
+ version = sys.version_info
111
+ return Environment(
112
+ agent_dir=agent_dir,
113
+ cwd=cwd,
114
+ env=dict(os.environ),
115
+ python_version=(version.major, version.minor, version.micro),
116
+ executable=sys.executable,
117
+ platform=sys.platform,
118
+ isatty=sys.stdout.isatty(),
119
+ columns=shutil.get_terminal_size((80, 24)).columns,
120
+ )
121
+
122
+
123
+ @dataclass(slots=True, frozen=True)
124
+ class Report:
125
+ """一次自检的完整结果。``failed`` 决定退出码。"""
126
+
127
+ version: str
128
+ python: str
129
+ executable: str
130
+ platform: str
131
+ checks: tuple[Check, ...]
132
+
133
+ @property
134
+ def failed(self) -> int:
135
+ return sum(1 for check in self.checks if check.status == "fail")
136
+
137
+ @property
138
+ def warned(self) -> int:
139
+ return sum(1 for check in self.checks if check.status == "warn")
140
+
141
+ @property
142
+ def passed(self) -> int:
143
+ return sum(1 for check in self.checks if check.status == "ok")
144
+
145
+
146
+ # ------------------------------------------------------------------ 检查项
147
+
148
+
149
+ def check_python(version: tuple[int, int, int], executable: str) -> Check:
150
+ """版本够不够。低于 ``REQUIRED_PYTHON`` 时进程多半根本起不来。"""
151
+ if version[:2] >= REQUIRED_PYTHON:
152
+ return Check("Python", "ok", f"{'.'.join(str(part) for part in version)}({executable})")
153
+ required = ".".join(str(part) for part in REQUIRED_PYTHON)
154
+ return Check(
155
+ "Python",
156
+ "fail",
157
+ f"{'.'.join(str(part) for part in version)} 低于要求的 {required}",
158
+ f"用 uv python install {required} 准备解释器,再重建安装环境",
159
+ )
160
+
161
+
162
+ def check_entry(environment: Environment) -> Check:
163
+ """``braid`` 在不在 ``PATH`` 上,以及它是不是当前这份安装。
164
+
165
+ 已安装包被另一份 braid 遮住时,用户敲的 ``braid`` 跑的不是升级后的代码。
166
+ 这类影子安装多半来自临时目录:安装验证把 ``UV_TOOL_BIN_DIR`` 指到临时目录,
167
+ ``uv tool update-shell`` 又把它写进了 shell 配置。只报路径不够,必须指出
168
+ 两者不是同一个文件。
169
+ """
170
+ found = shutil.which("braid", path=environment.env.get("PATH", ""))
171
+ if found is None:
172
+ return Check(
173
+ "入口",
174
+ "warn",
175
+ "当前 PATH 上找不到 braid 命令",
176
+ "安装后重开终端;仍不行就运行 uv tool update-shell,或把 ~/.local/bin 加入 PATH",
177
+ )
178
+ kind, _ = installation_kind()
179
+ expected = _installed_entry()
180
+ # 源码安装时 PATH 上的 braid 本来就可能来自别处,不做影子判断。
181
+ if kind == "installed" and expected is not None and Path(found).resolve() != expected:
182
+ return Check(
183
+ "入口",
184
+ "warn",
185
+ f"PATH 上的 braid 不是当前安装:{found}(当前安装的入口是 {expected})",
186
+ "旧安装会遮住新版本:从 shell 配置里删掉它的目录,或卸载旧安装后重开终端",
187
+ )
188
+ return Check("入口", "ok", found)
189
+
190
+
191
+ def _installed_entry() -> Path | None:
192
+ """当前解释器所在环境的 ``braid`` 启动器;不存在时返回 ``None``。"""
193
+ directory = Path(sys.executable).parent
194
+ for name in ("braid", "braid.exe"):
195
+ candidate = directory / name
196
+ if candidate.is_file():
197
+ return candidate.resolve()
198
+ return None
199
+
200
+
201
+ def installation_kind() -> tuple[str, Path]:
202
+ """这次运行的代码来自哪里:``source``(源码可编辑安装)或 ``installed``(打包产物)。
203
+
204
+ 判据是模块文件往上最近的一个 ``pyproject.toml``:可编辑安装指向包目录,wheel
205
+ 安装只会落在 ``site-packages`` 里。升级命令据此拒绝在源码树里执行。
206
+ """
207
+ package_file = Path(braid_coding_agent.__file__).resolve()
208
+ for parent in package_file.parents:
209
+ if (parent / "pyproject.toml").is_file():
210
+ return "source", parent
211
+ return "installed", package_file.parents[1]
212
+
213
+
214
+ def check_install_kind() -> Check:
215
+ kind, location = installation_kind()
216
+ if kind == "source":
217
+ return Check("安装方式", "info", f"源码可编辑安装({location})")
218
+ return Check("安装方式", "ok", f"已安装包({location})")
219
+
220
+
221
+ def _config_checks(
222
+ environment: Environment, config: AgentConfig, extra_files: Sequence[Path]
223
+ ) -> list[Check]:
224
+ """逐个配置文件:在不在、版本多少、需不需要迁移。"""
225
+ checks: list[Check] = []
226
+ global_path = environment.agent_dir / CONFIG_FILE_NAME
227
+ project_path = Path(environment.cwd) / PROJECT_CONFIG_DIR / CONFIG_FILE_NAME
228
+ for label, path in (("全局配置", global_path), ("项目配置", project_path)):
229
+ if not path.is_file():
230
+ checks.append(Check(label, "info", f"{path} 不存在(使用内置默认值)"))
231
+ continue
232
+ checks.append(Check(label, "ok", f"{path}(版本 {config.config_version})"))
233
+ for path in extra_files:
234
+ expanded = path.expanduser()
235
+ checks.append(Check("额外配置", "ok", f"{expanded}(--config)"))
236
+ return checks
237
+
238
+
239
+ def _credential_checks(
240
+ config: AgentConfig, environment: Environment, keychain: Keychain | None
241
+ ) -> list[Check]:
242
+ credentials = Credentials(config, env=environment.env, keychain=keychain)
243
+ checks: list[Check] = []
244
+ for status in credentials.statuses():
245
+ checks.append(
246
+ Check(
247
+ "凭证",
248
+ "ok" if status.available else "warn",
249
+ f"{status.provider_id}:{status.detail}",
250
+ )
251
+ )
252
+ if not any(status.available for status in credentials.statuses()):
253
+ first = config.providers[0].id if config.providers else "deepseek"
254
+ checks.append(
255
+ Check(
256
+ "凭证",
257
+ "fail",
258
+ "没有任何可用的 provider 凭证,braid 无法发起请求",
259
+ f"运行 braid auth login {first} 写入系统钥匙串,或导出对应的环境变量",
260
+ )
261
+ )
262
+ return checks
263
+
264
+
265
+ def _model_check(config: AgentConfig) -> list[Check]:
266
+ """默认模型。指向不存在的模型时 ``load_config`` 已经拒绝,这里只报告生效值。"""
267
+ if config.default_model is None:
268
+ return [Check("默认模型", "info", "未设置 default_model(按凭证推断一家可用端点)")]
269
+ return [
270
+ Check(
271
+ "默认模型",
272
+ "ok",
273
+ f"{config.default_model}(来自 {config.default_model_source})",
274
+ )
275
+ ]
276
+
277
+
278
+ def _sandbox_check(settings: SandboxSettings) -> Check:
279
+ """后端能不能用,以及当前配置是否依赖它。"""
280
+ try:
281
+ backend = detect_backend(settings.backend, executable=settings.executable)
282
+ except SandboxUnavailableError as exc:
283
+ if settings.needs_kernel_backend:
284
+ return Check("沙箱", "fail", exc.reason, exc.hint)
285
+ return Check(
286
+ "沙箱",
287
+ "info",
288
+ f"后端不可用({exc.reason});当前 mode = {settings.mode},不依赖沙箱",
289
+ exc.hint,
290
+ )
291
+ return Check("沙箱", "ok", f"后端 {backend.name} 可用(当前 mode = {settings.mode})")
292
+
293
+
294
+ def _mcp_checks(agent_dir: Path, cwd: str, environment: Environment) -> list[Check]:
295
+ loaded = load_mcp_config(agent_dir, cwd)
296
+ checks = [Check("MCP", "warn", message) for message in loaded.errors]
297
+ if not loaded.servers:
298
+ checks.append(Check("MCP", "info", "没有配置 MCP 服务器(mcp.json 不存在或为空)"))
299
+ return checks
300
+ for name, server in loaded.servers.items():
301
+ if server.transport == "http":
302
+ scheme = urlsplit(server.url or "").scheme
303
+ status: CheckStatus = "ok" if scheme in ("http", "https") else "warn"
304
+ checks.append(Check("MCP", status, f"{name}:{server.url}(http)"))
305
+ continue
306
+ command = server.command or ""
307
+ resolved = (
308
+ shutil.which(command, path=environment.env.get("PATH", ""))
309
+ if os.sep not in command
310
+ else (command if Path(command).is_file() else None)
311
+ )
312
+ if resolved is None:
313
+ checks.append(
314
+ Check(
315
+ "MCP",
316
+ "warn",
317
+ f"{name}:命令 {command} 找不到",
318
+ f"安装它,或改掉 mcp.json 里 {name} 的 command",
319
+ )
320
+ )
321
+ else:
322
+ trust = "已信任" if server.trusted else "首次连接需确认"
323
+ checks.append(Check("MCP", "ok", f"{name}:{resolved}({trust})"))
324
+ return checks
325
+
326
+
327
+ def _session_dir_check(environment: Environment) -> Check:
328
+ """会话目录必须可写:写不进去时每个回合都会丢历史。"""
329
+ try:
330
+ directory = Path(default_session_dir(environment.cwd, str(environment.agent_dir)))
331
+ probe = directory / ".doctor-probe"
332
+ probe.write_text("ok", encoding="utf-8")
333
+ probe.unlink()
334
+ except OSError as exc:
335
+ return Check(
336
+ "会话目录",
337
+ "fail",
338
+ str(exc),
339
+ "换一个可写的位置:braid --session-dir <目录>,或调整 BRAID_AGENT_DIR",
340
+ )
341
+ return Check("会话目录", "ok", str(directory))
342
+
343
+
344
+ def _terminal_check(environment: Environment) -> Check:
345
+ if environment.isatty:
346
+ return Check("终端", "ok", f"交互终端,{environment.columns} 列(TUI 可用)")
347
+ return Check(
348
+ "终端",
349
+ "info",
350
+ "不是交互终端:默认走行式 REPL,--tui 不可用",
351
+ )
352
+
353
+
354
+ def collect_checks(
355
+ environment: Environment,
356
+ *,
357
+ extra_files: Sequence[Path] = (),
358
+ keychain: Keychain | None = None,
359
+ ) -> tuple[Check, ...]:
360
+ """按固定顺序产出全部检查项。
361
+
362
+ :param extra_files: ``--config`` 给出的文件,只用于在输出里标出它们参与了合并。
363
+ :param keychain: 凭证后端;``None`` 时用系统钥匙串。
364
+ """
365
+ checks: list[Check] = [
366
+ check_install_kind(),
367
+ check_python(environment.python_version, environment.executable),
368
+ check_entry(environment),
369
+ ]
370
+ try:
371
+ config = load_config(
372
+ agent_dir=environment.agent_dir,
373
+ cwd=environment.cwd,
374
+ extra_files=tuple(extra_files),
375
+ env=environment.env,
376
+ )
377
+ except ConfigError as exc:
378
+ checks.append(Check("配置", "fail", str(exc), "按提示改配置文件;braid config path 看路径"))
379
+ checks.append(_session_dir_check(environment))
380
+ checks.append(_terminal_check(environment))
381
+ return tuple(checks)
382
+
383
+ checks.extend(_config_checks(environment, config, extra_files))
384
+ checks.extend(_credential_checks(config, environment, keychain))
385
+ checks.extend(_model_check(config))
386
+ checks.append(_sandbox_check(config.sandbox))
387
+ checks.extend(_mcp_checks(environment.agent_dir, environment.cwd, environment))
388
+ checks.append(_session_dir_check(environment))
389
+ checks.append(_terminal_check(environment))
390
+ return tuple(checks)
391
+
392
+
393
+ def build_report(environment: Environment, checks: Sequence[Check]) -> Report:
394
+ return Report(
395
+ version=__version__,
396
+ python=environment.python_text,
397
+ executable=environment.executable,
398
+ platform=environment.platform,
399
+ checks=tuple(checks),
400
+ )
401
+
402
+
403
+ # ------------------------------------------------------------------ 输出
404
+
405
+
406
+ def format_report(report: Report) -> list[str]:
407
+ """人读的行。名字后面直接接内容,不按宽度对齐:中文宽度让定宽列必然错位。"""
408
+ lines = [
409
+ f"braid {report.version}({report.platform},Python {report.python},{report.executable})",
410
+ "",
411
+ ]
412
+ for check in report.checks:
413
+ label = _STATUS_LABELS[check.status]
414
+ lines.append(f"[{label}] {check.name}:{check.detail}")
415
+ if check.hint is not None:
416
+ lines.append(f" {check.hint}")
417
+ lines.append("")
418
+ lines.append(
419
+ f"检查完成:{report.passed} 项通过,{report.warned} 项建议处理,{report.failed} 项必须处理"
420
+ )
421
+ return lines
422
+
423
+
424
+ def report_json(report: Report) -> str:
425
+ payload = {
426
+ "version": report.version,
427
+ "python": report.python,
428
+ "executable": report.executable,
429
+ "platform": report.platform,
430
+ "passed": report.passed,
431
+ "warned": report.warned,
432
+ "failed": report.failed,
433
+ "checks": [
434
+ {
435
+ "name": check.name,
436
+ "status": check.status,
437
+ "detail": check.detail,
438
+ "hint": check.hint,
439
+ }
440
+ for check in report.checks
441
+ ],
442
+ }
443
+ return json.dumps(payload, ensure_ascii=False)
444
+
445
+
446
+ # ------------------------------------------------------------------ 入口
447
+
448
+
449
+ @dataclass(slots=True)
450
+ class _Options:
451
+ as_json: bool = False
452
+ cwd: str = ""
453
+ configs: list[Path] = field(default_factory=list[Path])
454
+ help: bool = False
455
+
456
+
457
+ def _parse(argv: Sequence[str]) -> _Options:
458
+ options = _Options()
459
+ values = list(argv)
460
+ index = 0
461
+ while index < len(values):
462
+ argument = values[index]
463
+ if argument in ("-h", "--help"):
464
+ options.help = True
465
+ elif argument == "--json":
466
+ options.as_json = True
467
+ elif argument == "--cwd":
468
+ value, index = take_value(values, index, flag="--cwd")
469
+ options.cwd = value
470
+ elif argument == "--config":
471
+ value, index = take_value(values, index, flag="--config")
472
+ options.configs.append(Path(value))
473
+ else:
474
+ raise CommandError(f"未知参数: {argument}(braid doctor --help 查看用法)")
475
+ index += 1
476
+ return options
477
+
478
+
479
+ def run(argv: Sequence[str], *, agent_dir: Path, cwd: str, out: TextIO | None = None) -> int:
480
+ options = _parse(argv)
481
+ if options.help:
482
+ print(USAGE)
483
+ return 0
484
+ environment = current_environment(agent_dir=agent_dir, cwd=options.cwd or cwd)
485
+ checks = collect_checks(environment, extra_files=tuple(options.configs))
486
+ report = build_report(environment, checks)
487
+ stream = sys.stdout if out is None else out
488
+ if options.as_json:
489
+ print(report_json(report), file=stream)
490
+ else:
491
+ for line in format_report(report):
492
+ print(line, file=stream)
493
+ return 1 if report.failed else 0
494
+
495
+
496
+ __all__ = [
497
+ "REQUIRED_PYTHON",
498
+ "Check",
499
+ "Environment",
500
+ "Report",
501
+ "build_report",
502
+ "check_entry",
503
+ "check_install_kind",
504
+ "check_python",
505
+ "collect_checks",
506
+ "current_environment",
507
+ "format_report",
508
+ "installation_kind",
509
+ "report_json",
510
+ "run",
511
+ ]