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,95 @@
1
+ """``braid models``:把配置里的模型目录打出来。
2
+
3
+ 输出与 REPL 的 ``/models`` 来自同一个 :func:`~braid_coding_agent.models_view.catalog_lines`,
4
+ 所以两处永远不会给出不同的模型集合。区别只有一处:``/models`` 列的是运行时注册表,
5
+ ``--script`` 现场注册的 ``faux`` 也在里面;``braid models`` 列的是配置对象里的目录。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+ from collections.abc import Sequence
12
+ from dataclasses import dataclass, field
13
+ from pathlib import Path
14
+
15
+ from braid_ai.types import Model
16
+ from braid_coding_agent.commands import CommandError, load_base_config, take_value
17
+ from braid_coding_agent.config import AgentConfig
18
+ from braid_coding_agent.credentials import Credentials
19
+ from braid_coding_agent.discovery import refresh_catalog
20
+ from braid_coding_agent.models_view import catalog_lines
21
+
22
+ USAGE = """braid models [选项]
23
+ 列出 provider、模型、上下文窗口、输入能力、价格与当前默认项
24
+
25
+ 选项:
26
+ --refresh 重新读配置并访问 discover 端点,刷新模型清单缓存
27
+ --config PATH 额外配置文件(可重复,按给出顺序后者覆盖前者)
28
+ --cwd PATH 工作目录(决定读哪个项目配置)
29
+ -h, --help 显示本帮助"""
30
+
31
+
32
+ @dataclass(slots=True)
33
+ class _Options:
34
+ refresh: bool = False
35
+ cwd: str = ""
36
+ configs: list[Path] = field(default_factory=list[Path])
37
+ help: bool = False
38
+
39
+
40
+ def _parse(argv: Sequence[str]) -> _Options:
41
+ options = _Options()
42
+ values = list(argv)
43
+ index = 0
44
+ while index < len(values):
45
+ argument = values[index]
46
+ if argument in ("-h", "--help"):
47
+ options.help = True
48
+ elif argument == "--refresh":
49
+ options.refresh = True
50
+ elif argument == "--config":
51
+ value, index = take_value(values, index, flag="--config")
52
+ options.configs.append(Path(value))
53
+ elif argument == "--cwd":
54
+ value, index = take_value(values, index, flag="--cwd")
55
+ options.cwd = value
56
+ else:
57
+ raise CommandError(f"未知参数: {argument}(braid models --help 查看用法)")
58
+ index += 1
59
+ return options
60
+
61
+
62
+ def _default_model(config: AgentConfig) -> Model | None:
63
+ """默认模型对应的对象,用来标 ``*``。没声明默认模型时返回 ``None``。"""
64
+ if config.default_model is None:
65
+ return None
66
+ provider_id, _, model_id = config.default_model.partition("/")
67
+ return config.find(provider_id, model_id)
68
+
69
+
70
+ async def run(argv: Sequence[str], *, agent_dir: Path, cwd: str) -> int:
71
+ options = _parse(argv)
72
+ if options.help:
73
+ print(USAGE)
74
+ return 0
75
+ config = load_base_config(
76
+ agent_dir=agent_dir,
77
+ cwd=options.cwd or cwd,
78
+ extra_files=tuple(options.configs),
79
+ )
80
+ credentials = Credentials(config)
81
+ if options.refresh:
82
+ config, report = await refresh_catalog(config, agent_dir=agent_dir, credentials=credentials)
83
+ for line in report.lines():
84
+ print(line, file=sys.stderr)
85
+ for line in catalog_lines(
86
+ config.models(),
87
+ current=_default_model(config),
88
+ config=config,
89
+ credentials=credentials,
90
+ ):
91
+ print(line)
92
+ return 0
93
+
94
+
95
+ __all__ = ["run"]
@@ -0,0 +1,89 @@
1
+ """``braid setup``:首次安装后准备全局目录,并给出下一步操作。
2
+
3
+ 初始化只补齐缺失的文件与目录,不读取网络,也不修改已有配置。安装脚本在普通安装
4
+ 完成后调用它;用户之后也可以随时重复运行,用来修复被删除的目录。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import sys
10
+ from collections.abc import Sequence
11
+ from pathlib import Path
12
+ from typing import TextIO
13
+
14
+ from braid_coding_agent.commands import CommandError
15
+ from braid_coding_agent.config_files import CONFIG_FILE_NAME, template_text
16
+
17
+ USAGE = """braid setup [选项]
18
+ 创建全局目录、settings.json 与会话/技能/子代理目录
19
+
20
+ 选项:
21
+ -h, --help 显示本帮助
22
+
23
+ 退出码: 0 初始化完成或已经是最新状态;1 失败
24
+
25
+ 初始化是幂等的:已有 settings.json 时保留原内容,已有目录不移动也不清空。"""
26
+
27
+ #: 首次使用需要的目录。会话按工作目录在 sessions/ 下继续创建子目录。
28
+ LAYOUT_DIRECTORIES: tuple[str, ...] = ("agents", "sessions", "skills")
29
+
30
+
31
+ def _status_line(label: str, path: Path, *, created: bool, kind: str = "目录") -> str:
32
+ if created:
33
+ return f" [已创建] {label}:{path}"
34
+ suffix = "已存在,保留原内容" if kind == "文件" else "已就绪"
35
+ return f" [已存在] {label}:{path}({suffix})"
36
+
37
+
38
+ def run(argv: Sequence[str], *, agent_dir: Path, cwd: str, out: TextIO | None = None) -> int:
39
+ """准备 ``agent_dir``,返回进程退出码。``cwd`` 保留给统一的子命令接口。"""
40
+ del cwd
41
+ stream = sys.stdout if out is None else out
42
+ if argv and argv[0] in ("-h", "--help"):
43
+ print(USAGE, file=stream)
44
+ return 0
45
+ if argv:
46
+ raise CommandError(f"未知参数: {argv[0]}(braid setup --help 查看用法)")
47
+
48
+ legacy = agent_dir / "config.toml"
49
+ if legacy.is_file():
50
+ raise CommandError(
51
+ f"{legacy}: 旧版 TOML 配置不再读取;把需要的字段迁移到 "
52
+ f"{agent_dir / CONFIG_FILE_NAME},再删除这份文件"
53
+ )
54
+
55
+ changes: list[str] = []
56
+
57
+ agent_dir_created = not agent_dir.exists()
58
+ agent_dir.mkdir(parents=True, exist_ok=True)
59
+ if agent_dir_created:
60
+ changes.append(f" [已创建] 全局目录:{agent_dir}")
61
+
62
+ config_path = agent_dir / CONFIG_FILE_NAME
63
+ config_created = not config_path.exists()
64
+ if config_created:
65
+ config_path.write_text(template_text(), encoding="utf-8")
66
+ changes.append(_status_line("settings.json", config_path, created=True, kind="文件"))
67
+ else:
68
+ changes.append(_status_line("settings.json", config_path, created=False, kind="文件"))
69
+
70
+ for name in LAYOUT_DIRECTORIES:
71
+ path = agent_dir / name
72
+ created = not path.exists()
73
+ path.mkdir(parents=True, exist_ok=True)
74
+ changes.append(_status_line(f"{name}/", path, created=created))
75
+
76
+ state = "初始化完成" if agent_dir_created or config_created else "已经初始化"
77
+ print(f"Braid 全局目录:{agent_dir}({state})", file=stream)
78
+ for line in changes:
79
+ print(line, file=stream)
80
+ print("", file=stream)
81
+ print("下一步:", file=stream)
82
+ print(" 1. braid auth login deepseek 将 API Key 写入系统钥匙串", file=stream)
83
+ print(" 也可以改用环境变量 DEEPSEEK_API_KEY 或 OPENAI_API_KEY", file=stream)
84
+ print(" 2. braid doctor 检查安装、配置与终端能力", file=stream)
85
+ print(" 3. braid 进入交互会话", file=stream)
86
+ return 0
87
+
88
+
89
+ __all__ = ["LAYOUT_DIRECTORIES", "run"]
@@ -0,0 +1,277 @@
1
+ """``braid uninstall``:卸载 uv tool 安装与全局数据目录。
2
+
3
+ ```text
4
+ braid uninstall 显示将要删除的路径,确认后执行
5
+ braid uninstall --yes 不询问(脚本与 CI 用)
6
+ braid uninstall --keep-data 只卸载工具,保留 ~/.braid/
7
+ ```
8
+
9
+ 卸载顺序固定为工具在前、数据目录在后。uv 卸载失败时直接停止,数据目录保持原样,
10
+ 避免出现"命令没了但会话与配置也一起丢了"的半完成状态。
11
+
12
+ 统一安装入口使用 ``uv tool install``,因此工具卸载调用
13
+ ``uv tool uninstall braid-coding-agent``。源码可编辑安装不会执行这一步:当前代码位于
14
+ 源码树中,uv tool 里即使存在另一份安装也属于独立安装,删掉它不会移除当前源码。
15
+ 这类运行只清理全局数据目录,并在输出中说明源码目录未被改动。
16
+
17
+ 全局目录来自 ``BRAID_AGENT_DIR`` 或 ``~/.braid``。删除前会拒绝文件系统根目录、
18
+ 用户主目录、当前工作目录,以及包含当前工作目录或用户主目录的路径。符号链接目录
19
+ 同样拒绝,避免把链接目标误当成数据目录删除。
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import shutil
25
+ import subprocess
26
+ import sys
27
+ from collections.abc import Sequence
28
+ from dataclasses import dataclass
29
+ from pathlib import Path
30
+ from typing import Final, TextIO
31
+
32
+ from braid_coding_agent.commands import CommandError
33
+ from braid_coding_agent.commands.doctor import installation_kind
34
+
35
+ USAGE = """braid uninstall [选项]
36
+ 卸载 uv tool 安装的 braid-coding-agent,并删除全局数据目录
37
+
38
+ 选项:
39
+ --yes 不询问,直接卸载(脚本用)
40
+ --keep-data 保留全局数据目录,只卸载工具
41
+ -h, --help 显示本帮助
42
+
43
+ 默认删除的全局目录由 BRAID_AGENT_DIR 指定,未设置时是 ~/.braid/。
44
+ 系统钥匙串中的凭证不会随数据目录删除;需要时先运行 braid auth logout <provider>。
45
+
46
+ 退出码: 0 卸载完成或已经不存在;10 非交互环境没有 --yes,未执行;1 卸载失败"""
47
+
48
+ #: 发布到包索引的包名,也是 uv tool 记录的包名。
49
+ PACKAGE_NAME: Final[str] = "braid-coding-agent"
50
+
51
+ #: 检测到可执行动作但没有执行时使用,与 ``braid upgrade`` 保持一致。
52
+ UNINSTALL_PENDING: Final[int] = 10
53
+
54
+
55
+ @dataclass(slots=True, frozen=True)
56
+ class Plan:
57
+ """一次卸载要处理的路径与安装方式。"""
58
+
59
+ agent_dir: Path
60
+ cwd: Path
61
+ home: Path
62
+ source_root: Path | None
63
+ keep_data: bool
64
+ uv: str = "uv"
65
+
66
+
67
+ @dataclass(slots=True)
68
+ class _Options:
69
+ yes: bool = False
70
+ keep_data: bool = False
71
+ help: bool = False
72
+
73
+
74
+ def _parse(argv: Sequence[str]) -> _Options:
75
+ options = _Options()
76
+ for argument in argv:
77
+ if argument in ("-h", "--help"):
78
+ options.help = True
79
+ elif argument == "--yes":
80
+ options.yes = True
81
+ elif argument == "--keep-data":
82
+ options.keep_data = True
83
+ else:
84
+ raise CommandError(f"未知参数: {argument}(braid uninstall --help 查看用法)")
85
+ return options
86
+
87
+
88
+ def build_plan(
89
+ *,
90
+ agent_dir: Path,
91
+ cwd: Path,
92
+ source_root: Path | None,
93
+ keep_data: bool,
94
+ home: Path | None = None,
95
+ uv: str = "uv",
96
+ ) -> Plan:
97
+ """组合出要删除的路径。``source_root`` 非空表示当前运行来自源码树。"""
98
+ return Plan(
99
+ agent_dir=agent_dir,
100
+ cwd=cwd,
101
+ home=Path.home() if home is None else home,
102
+ source_root=source_root,
103
+ keep_data=keep_data,
104
+ uv=uv,
105
+ )
106
+
107
+
108
+ def validate_agent_dir(agent_dir: Path, *, cwd: Path, home: Path) -> Path:
109
+ """删除前的安全检查,返回解析后的绝对路径。
110
+
111
+ 数据目录必须是普通目录,或者尚不存在。根目录、主目录、当前工作目录与它们的
112
+ 上级目录都拒绝,避免一个写错的 ``BRAID_AGENT_DIR`` 把用户目录整个删掉。
113
+ """
114
+ raw = agent_dir.expanduser()
115
+ if raw.is_symlink():
116
+ raise CommandError(f"拒绝删除符号链接目录:{raw};指向真实目录后再执行")
117
+ try:
118
+ resolved = raw.resolve()
119
+ cwd_resolved = cwd.expanduser().resolve()
120
+ home_resolved = home.expanduser().resolve()
121
+ except OSError as exc:
122
+ raise CommandError(f"无法解析卸载路径:{raw}:{exc}") from exc
123
+ if resolved.parent == resolved:
124
+ raise CommandError(f"拒绝删除文件系统根目录:{resolved}")
125
+ if home_resolved.is_relative_to(resolved):
126
+ raise CommandError(f"拒绝删除用户主目录或它的上级目录:{resolved}")
127
+ if cwd_resolved.is_relative_to(resolved):
128
+ raise CommandError(f"拒绝删除包含当前工作目录的路径:{resolved}")
129
+ if not resolved.exists():
130
+ return resolved
131
+ if not resolved.is_dir():
132
+ raise CommandError(f"全局数据路径不是目录:{resolved}")
133
+ return resolved
134
+
135
+
136
+ def _process_detail(completed: subprocess.CompletedProcess[str]) -> str:
137
+ text = (completed.stderr or completed.stdout).strip()
138
+ return f":{text}" if text else ""
139
+
140
+
141
+ def tool_is_installed(uv: str) -> bool:
142
+ """``uv tool list`` 里有没有本包。列表失败直接报错,不猜。"""
143
+ try:
144
+ completed = subprocess.run(
145
+ [uv, "tool", "list"], capture_output=True, text=True, check=False
146
+ )
147
+ except OSError as exc:
148
+ raise CommandError(f"无法执行 {uv}:{exc}") from exc
149
+ if completed.returncode != 0:
150
+ raise CommandError(
151
+ f"读取 uv tool 安装列表失败(退出码 {completed.returncode})"
152
+ f"{_process_detail(completed)}"
153
+ )
154
+ for line in completed.stdout.splitlines():
155
+ fields = line.split()
156
+ if fields and fields[0] == PACKAGE_NAME:
157
+ return True
158
+ return False
159
+
160
+
161
+ def uninstall_tool(uv: str) -> None:
162
+ """调用 ``uv tool uninstall``,失败时保留调用方的后续步骤。"""
163
+ try:
164
+ completed = subprocess.run(
165
+ [uv, "tool", "uninstall", PACKAGE_NAME],
166
+ capture_output=True,
167
+ text=True,
168
+ check=False,
169
+ )
170
+ except OSError as exc:
171
+ raise CommandError(f"无法执行 {uv}:{exc}") from exc
172
+ if completed.returncode != 0:
173
+ raise CommandError(
174
+ f"卸载 {PACKAGE_NAME} 失败(退出码 {completed.returncode}){_process_detail(completed)}"
175
+ )
176
+
177
+
178
+ def remove_data_dir(path: Path) -> None:
179
+ """删除已经通过安全检查的数据目录。"""
180
+ try:
181
+ shutil.rmtree(path)
182
+ except OSError as exc:
183
+ raise CommandError(f"删除全局数据目录失败:{path}:{exc}") from exc
184
+
185
+
186
+ def execute(plan: Plan, *, assume_yes: bool, out: TextIO) -> int:
187
+ """按计划执行卸载。返回进程退出码。"""
188
+ if plan.keep_data:
189
+ try:
190
+ agent_dir = plan.agent_dir.expanduser().resolve()
191
+ except OSError as exc:
192
+ raise CommandError(f"无法解析全局数据路径:{plan.agent_dir}:{exc}") from exc
193
+ else:
194
+ agent_dir = validate_agent_dir(plan.agent_dir, cwd=plan.cwd, home=plan.home)
195
+ print("将要卸载 Braid:", file=out)
196
+ if plan.source_root is None:
197
+ print(f" 工具:uv tool 安装的 {PACKAGE_NAME}", file=out)
198
+ else:
199
+ print(f" 工具:源码安装({plan.source_root},不会删除源码目录)", file=out)
200
+ if plan.keep_data:
201
+ print(f" 数据:保留 {agent_dir}", file=out)
202
+ elif agent_dir.exists():
203
+ print(f" 数据:{agent_dir}(配置、会话、技能与子代理)", file=out)
204
+ else:
205
+ print(f" 数据:{agent_dir} 不存在,跳过", file=out)
206
+
207
+ if not assume_yes:
208
+ if not sys.stdin.isatty():
209
+ print("\n没有终端可以确认。要现在卸载,请加 --yes:", file=out)
210
+ print(" braid uninstall --yes", file=out)
211
+ return UNINSTALL_PENDING
212
+ print("\n继续?[y/N] ", end="", file=out, flush=True)
213
+ answer = sys.stdin.readline().strip().lower()
214
+ if answer not in ("y", "yes"):
215
+ print("已取消,没有改动任何东西", file=out)
216
+ return 0
217
+
218
+ if plan.source_root is None:
219
+ uv = shutil.which(plan.uv)
220
+ if uv is None:
221
+ raise CommandError(
222
+ f"找不到 {plan.uv}:先安装 uv,再运行 braid uninstall;"
223
+ "也可以手动执行 uv tool uninstall braid-coding-agent"
224
+ )
225
+ if tool_is_installed(uv):
226
+ uninstall_tool(uv)
227
+ print(f"已卸载 uv tool:{PACKAGE_NAME}", file=out)
228
+ else:
229
+ print(f"uv tool 中没有 {PACKAGE_NAME},跳过工具卸载", file=out)
230
+ else:
231
+ print("当前是源码安装,跳过 uv tool 卸载;源码目录保持不变", file=out)
232
+
233
+ if plan.keep_data:
234
+ print(f"按 --keep-data 保留全局数据目录:{agent_dir}", file=out)
235
+ elif agent_dir.exists():
236
+ remove_data_dir(agent_dir)
237
+ print(f"已删除全局数据目录:{agent_dir}", file=out)
238
+ else:
239
+ print(f"全局数据目录已经不存在:{agent_dir}", file=out)
240
+
241
+ print("卸载完成。", file=out)
242
+ print(
243
+ "系统钥匙串中的凭证没有改动;清理凭证应在卸载前运行 braid auth logout <provider>。",
244
+ file=out,
245
+ )
246
+ return 0
247
+
248
+
249
+ def run(argv: Sequence[str], *, agent_dir: Path, cwd: str, out: TextIO | None = None) -> int:
250
+ options = _parse(argv)
251
+ stream = sys.stdout if out is None else out
252
+ if options.help:
253
+ print(USAGE, file=stream)
254
+ return 0
255
+
256
+ kind, source_root = installation_kind()
257
+ plan = build_plan(
258
+ agent_dir=agent_dir,
259
+ cwd=Path(cwd),
260
+ source_root=source_root if kind == "source" else None,
261
+ keep_data=options.keep_data,
262
+ )
263
+ return execute(plan, assume_yes=options.yes, out=stream)
264
+
265
+
266
+ __all__ = [
267
+ "PACKAGE_NAME",
268
+ "UNINSTALL_PENDING",
269
+ "Plan",
270
+ "build_plan",
271
+ "execute",
272
+ "remove_data_dir",
273
+ "run",
274
+ "tool_is_installed",
275
+ "uninstall_tool",
276
+ "validate_agent_dir",
277
+ ]