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,244 @@
1
+ """工具完整输出的落盘目录与保留策略。
2
+
3
+ ``bash`` 超过展示上限时把原始字节写进文件,路径进工具结果。这些文件必须有一个
4
+ 确定的归属与生命周期,否则长会话每跑一条大命令就留下一个孤儿。
5
+
6
+ 三条规则:
7
+
8
+ 1. **按会话归属**。落盘文件放在 ``<会话目录>/<会话 id>/outputs/``;内存会话用
9
+ ``<系统临时目录>/braid-session-outputs/<会话 id>/outputs/``,进程结束时整体删除。
10
+ 2. **按数量收敛**。同一会话只保留最近 :data:`DEFAULT_KEPT_OUTPUT_FILES` 个文件,
11
+ 新建时删掉最旧的。恢复会话时先按修改时间接管目录里已有的文件,否则数量上限
12
+ 会在每次重启后重新计算。
13
+ 3. **按时间清扫**。会话开始前扫一遍同级会话目录,删除超过
14
+ :data:`DEFAULT_OUTPUT_RETENTION_DAYS` 天的输出,并顺手移除空掉的会话目录。
15
+
16
+ ``keep=True`` 同时关掉后两条:不裁剪、不清扫、不删除。它是留给"这份输出我要留着
17
+ 排查问题"的出口。
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import os
23
+ import shutil
24
+ import tempfile
25
+ import time
26
+ from pathlib import Path
27
+ from typing import Final, Protocol
28
+
29
+ #: 一个会话最多保留多少个完整输出文件。超出时删最旧的。
30
+ DEFAULT_KEPT_OUTPUT_FILES: Final[int] = 20
31
+
32
+ #: 会话结束后输出文件还能留多久(天)。
33
+ DEFAULT_OUTPUT_RETENTION_DAYS: Final[float] = 7.0
34
+
35
+ _OUTPUT_DIR_NAME: Final[str] = "outputs"
36
+ _TEMP_ROOT_NAME: Final[str] = "braid-session-outputs"
37
+ _SECONDS_PER_DAY: Final[float] = 86_400.0
38
+
39
+
40
+ class SessionLike(Protocol):
41
+ """本模块需要的会话能力。只取三个只读方法,避免让工具层依赖会话实现。"""
42
+
43
+ def is_persisted(self) -> bool: ...
44
+
45
+ def get_session_dir(self) -> str: ...
46
+
47
+ def get_session_id(self) -> str: ...
48
+
49
+
50
+ class ToolOutputStore:
51
+ """一个会话的输出文件目录。只在事件循环线程里用。
52
+
53
+ :param directory: 文件落在这里;第一次写文件时才创建。
54
+ :param keep_recent: 最多保留多少个文件,必须为正数。
55
+ :param keep: 为真时永不删除任何文件。
56
+ :param ephemeral: 为真时 :meth:`release` 删除整个目录(内存会话)。
57
+ """
58
+
59
+ __slots__ = (
60
+ "_directory",
61
+ "_ephemeral",
62
+ "_keep",
63
+ "_keep_recent",
64
+ "_open",
65
+ "_paths",
66
+ "_prepared",
67
+ )
68
+
69
+ def __init__(
70
+ self,
71
+ directory: str,
72
+ *,
73
+ keep_recent: int = DEFAULT_KEPT_OUTPUT_FILES,
74
+ keep: bool = False,
75
+ ephemeral: bool = False,
76
+ ) -> None:
77
+ if keep_recent < 1:
78
+ raise ValueError(f"keep_recent 必须是正整数,收到 {keep_recent}")
79
+ self._directory = os.path.abspath(directory)
80
+ self._keep_recent = keep_recent
81
+ self._keep = keep
82
+ self._ephemeral = ephemeral
83
+ self._paths: list[str] = []
84
+ self._open: set[str] = set()
85
+ self._prepared = False
86
+
87
+ @classmethod
88
+ def for_session(
89
+ cls,
90
+ session: SessionLike,
91
+ *,
92
+ keep: bool = False,
93
+ keep_recent: int = DEFAULT_KEPT_OUTPUT_FILES,
94
+ retention_days: float = DEFAULT_OUTPUT_RETENTION_DAYS,
95
+ now: float | None = None,
96
+ memory_root: str | None = None,
97
+ ) -> ToolOutputStore:
98
+ """按会话的落盘方式决定目录,并清掉同级会话里过期的输出。
99
+
100
+ :param memory_root: 内存会话的临时根;``None`` 表示系统临时目录下的
101
+ ``braid-session-outputs``。测试用它把产物圈在自己的目录里。
102
+ """
103
+ parent = _session_parent_dir(session, memory_root)
104
+ ephemeral = not session.is_persisted()
105
+ if not keep:
106
+ sweep_expired_outputs(parent, max_age_days=retention_days, now=now)
107
+ return cls(
108
+ os.path.join(parent, session.get_session_id(), _OUTPUT_DIR_NAME),
109
+ keep_recent=keep_recent,
110
+ keep=keep,
111
+ ephemeral=ephemeral,
112
+ )
113
+
114
+ @property
115
+ def directory(self) -> str:
116
+ return self._directory
117
+
118
+ def open_output_file(self, prefix: str, suffix: str = ".log") -> tuple[str, int]:
119
+ """新建一个输出文件,返回 ``(绝对路径, 文件描述符)``。
120
+
121
+ 描述符交给调用方写,写完要调 :meth:`close_output_file` 登记。
122
+ """
123
+ self._prepare()
124
+ descriptor, path = tempfile.mkstemp(prefix=f"{prefix}-", suffix=suffix, dir=self._directory)
125
+ self._paths.append(path)
126
+ self._open.add(path)
127
+ self.prune()
128
+ return path, descriptor
129
+
130
+ def close_output_file(self, path: str) -> None:
131
+ """登记"这个文件已经写完"。正在写的文件不会被裁剪策略删掉。"""
132
+ self._open.discard(path)
133
+
134
+ def write_output(self, data: bytes, *, prefix: str, suffix: str = ".log") -> str:
135
+ """一次写完一段内容,返回路径。
136
+
137
+ 与 :meth:`open_output_file` 的区别只在于调用方不需要自己管描述符:截断后
138
+ 写全文、二进制资源落盘这两条路径都是"拿到完整的字节,写完就算",开一个
139
+ 描述符再手工关掉只会多一处漏关的机会。
140
+ """
141
+ path, descriptor = self.open_output_file(prefix, suffix)
142
+ with os.fdopen(descriptor, "wb") as handle:
143
+ handle.write(data)
144
+ self.close_output_file(path)
145
+ return path
146
+
147
+ def prune(self) -> list[str]:
148
+ """按数量上限删掉最旧的文件,返回被删的路径。"""
149
+ if self._keep:
150
+ return []
151
+ removed: list[str] = []
152
+ for path in list(self._paths):
153
+ if len(self._paths) <= self._keep_recent:
154
+ break
155
+ if path in self._open:
156
+ continue
157
+ self._paths.remove(path)
158
+ _unlink(path)
159
+ removed.append(path)
160
+ return removed
161
+
162
+ def release(self) -> None:
163
+ """会话结束。内存会话删掉整个目录,落盘会话把文件留给保留期。"""
164
+ if self._keep or not self._ephemeral:
165
+ return
166
+ if os.path.isdir(self._directory):
167
+ shutil.rmtree(self._directory)
168
+ _remove_if_empty(os.path.dirname(self._directory))
169
+
170
+ def files(self) -> list[str]:
171
+ """当前目录里的文件,按修改时间从旧到新。"""
172
+ return list(self._paths)
173
+
174
+ def _prepare(self) -> None:
175
+ """建目录,并把目录里已有的文件按修改时间接管进来(恢复会话时)。"""
176
+ if self._prepared:
177
+ return
178
+ os.makedirs(self._directory, mode=0o700, exist_ok=True)
179
+ existing = [
180
+ entry.path
181
+ for entry in os.scandir(self._directory)
182
+ if entry.is_file(follow_symlinks=False)
183
+ ]
184
+ existing.sort(key=os.path.getmtime)
185
+ self._paths = existing
186
+ self._prepared = True
187
+
188
+
189
+ def sweep_expired_outputs(
190
+ parent: str,
191
+ *,
192
+ max_age_days: float = DEFAULT_OUTPUT_RETENTION_DAYS,
193
+ now: float | None = None,
194
+ ) -> list[str]:
195
+ """删除 ``parent`` 下各会话里超过保留期的输出目录,返回被删的路径。
196
+
197
+ ``parent`` 是装会话目录的那一层:落盘会话的 ``--<cwd>--`` 目录,或内存会话的
198
+ 临时根。判据是输出目录自己的修改时间——文件只在创建时写一次。
199
+ """
200
+ if not os.path.isdir(parent):
201
+ return []
202
+ cutoff = (time.time() if now is None else now) - max_age_days * _SECONDS_PER_DAY
203
+ removed: list[str] = []
204
+ for session_dir in _subdirectories(parent):
205
+ outputs = os.path.join(session_dir, _OUTPUT_DIR_NAME)
206
+ if not os.path.isdir(outputs):
207
+ continue
208
+ if os.path.getmtime(outputs) >= cutoff:
209
+ continue
210
+ shutil.rmtree(outputs)
211
+ removed.append(outputs)
212
+ _remove_if_empty(session_dir)
213
+ return removed
214
+
215
+
216
+ def _session_parent_dir(session: SessionLike, memory_root: str | None) -> str:
217
+ """装会话目录的那一层,与 :func:`sweep_expired_outputs` 的 ``parent`` 同义。"""
218
+ if session.is_persisted():
219
+ return session.get_session_dir()
220
+ root = memory_root if memory_root is not None else tempfile.gettempdir()
221
+ return os.path.join(root, _TEMP_ROOT_NAME)
222
+
223
+
224
+ def _subdirectories(parent: str) -> list[str]:
225
+ return [entry.path for entry in os.scandir(parent) if entry.is_dir(follow_symlinks=False)]
226
+
227
+
228
+ def _unlink(path: str) -> None:
229
+ """删文件。``missing_ok`` 说明的是意图:这个文件可能已经被另一个进程删掉。"""
230
+ Path(path).unlink(missing_ok=True)
231
+
232
+
233
+ def _remove_if_empty(path: str) -> None:
234
+ if os.path.isdir(path) and not os.listdir(path):
235
+ os.rmdir(path)
236
+
237
+
238
+ __all__ = [
239
+ "DEFAULT_KEPT_OUTPUT_FILES",
240
+ "DEFAULT_OUTPUT_RETENTION_DAYS",
241
+ "SessionLike",
242
+ "ToolOutputStore",
243
+ "sweep_expired_outputs",
244
+ ]
@@ -0,0 +1,91 @@
1
+ """路径归一化:把模型写的路径变成可以交给文件系统的绝对路径。
2
+
3
+ 工具收到的路径来自模型,形状比人手输入的更野:``@src/a.py``(IDE 拖拽格式)、
4
+ ``~/notes.md``(家目录)、以及从网页复制来的 **U+202F 窄不换行空格**(macOS 截图
5
+ 文件名里就有)。这些都不该让工具失败——先归一化,再落到路径。
6
+
7
+ ## 只做三件事
8
+
9
+ 1. 把各种 Unicode 空格变体换成普通空格;
10
+ 2. 去掉开头的 ``@``(``@file`` 引用语法);
11
+ 3. 展开开头的 ``~``,相对路径拼到 ``cwd`` 上,最后做一次 ``normpath``
12
+ (消除 ``a/../b`` 与重复分隔符)。
13
+
14
+ **不解析符号链接**。解析会让"模型看到 a.py、写入却落到 b.py"这种替换变得无声无息;
15
+ 真正需要真实路径的地方(:mod:`braid_coding_agent.tools.mutation_queue` 的锁键)单独处理。
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ import re
22
+ from typing import Final
23
+
24
+ #: Unicode 空格变体。U+00A0 不换行空格、U+2000–U+200A 各种宽度空格、
25
+ #: U+202F 窄不换行空格、U+205F 数学空格、U+3000 全角空格。
26
+ _UNICODE_SPACES: Final[re.Pattern[str]] = re.compile(r"[\u00a0\u2000-\u200a\u202f\u205f\u3000]")
27
+
28
+
29
+ def normalize_path(
30
+ file_path: str,
31
+ *,
32
+ trim: bool = False,
33
+ expand_tilde: bool = True,
34
+ home_dir: str | None = None,
35
+ strip_at_prefix: bool = False,
36
+ ) -> str:
37
+ """归一化一个路径字符串(无 I/O)。"""
38
+ normalized = file_path.strip() if trim else file_path
39
+ normalized = _UNICODE_SPACES.sub(" ", normalized)
40
+ if strip_at_prefix and normalized.startswith("@"):
41
+ normalized = normalized[1:]
42
+ if expand_tilde:
43
+ home = home_dir if home_dir is not None else os.path.expanduser("~")
44
+ if normalized == "~":
45
+ return home
46
+ if normalized.startswith("~/") or normalized.startswith("~\\"):
47
+ return os.path.join(home, normalized[2:])
48
+ return normalized
49
+
50
+
51
+ def expand_path(file_path: str) -> str:
52
+ """``read``/``edit`` 这类"用户给的路径"用的归一化:展开 ``~`` 与 ``@``。"""
53
+ return normalize_path(file_path, strip_at_prefix=True)
54
+
55
+
56
+ def resolve_to_cwd(file_path: str, cwd: str) -> str:
57
+ """相对路径按 ``cwd`` 解析,绝对路径保持绝对;结果一律 ``normpath`` 过。
58
+
59
+ ``cwd`` 自己也归一化一次:调用方可能传入带 ``~`` 或尾部斜杠的目录。
60
+ """
61
+ normalized = expand_path(file_path)
62
+ base = normalize_path(cwd, expand_tilde=True)
63
+ if os.path.isabs(normalized):
64
+ return os.path.normpath(normalized)
65
+ return os.path.normpath(os.path.join(os.path.abspath(base), normalized))
66
+
67
+
68
+ def to_posix(path: str) -> str:
69
+ """输出给模型的路径统一用 ``/``:Windows 的反斜杠在提示词里会被当成转义符。"""
70
+ return path.replace(os.sep, "/") if os.sep != "/" else path
71
+
72
+
73
+ def relative_posix(path: str, root: str) -> str:
74
+ """``path`` 相对 ``root`` 的 posix 写法;不在 ``root`` 下时返回原路径的 posix 形式。"""
75
+ try:
76
+ relative = os.path.relpath(path, root)
77
+ except ValueError:
78
+ # Windows 跨盘符时 relpath 抛 ValueError:没有"相对"可言。
79
+ return to_posix(path)
80
+ if relative == os.pardir or relative.startswith(os.pardir + os.sep):
81
+ return to_posix(path)
82
+ return to_posix(relative)
83
+
84
+
85
+ __all__ = [
86
+ "expand_path",
87
+ "normalize_path",
88
+ "relative_posix",
89
+ "resolve_to_cwd",
90
+ "to_posix",
91
+ ]
@@ -0,0 +1,141 @@
1
+ """``update_plan``:把多步骤任务变成一份可审阅、可恢复的步骤表。
2
+
3
+ ## 为什么这个工具不改上下文
4
+
5
+ 计划写进会话树(``custom`` 条目),工具结果里只回一份摘要。这不是省 token 的技巧,
6
+ 而是两条真实需求的交集:
7
+
8
+ - **模型需要当前状态**(否则它会记错序号、重复做已完成的事)——摘要每次都完整给出;
9
+ - **模型不需要历史版本**("第 2 版和第 3 版的差别"对完成任务没有帮助)——历史留在
10
+ 会话文件里给人和评测用。
11
+
12
+ 如果计划写进模型上下文,一个五步任务至少产生五条消息,压缩时还要为它挑切点;写成
13
+ ``custom`` 条目,投影对它返回零条消息。
14
+
15
+ ## 为什么状态只有三档
16
+
17
+ ``pending`` / ``in_progress`` / ``completed`` 覆盖了"还没做、正在做、做完了"。没有
18
+ ``blocked`` 与 ``failed``:这两种情况在对话里由模型用一句话说清("第三步被缺凭证挡住
19
+ 了"),塞进状态枚举只会让模型把解释也写成枚举值。
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import cast
25
+
26
+ from braid_agent.tools import AgentTool, AgentToolResult, ToolUpdateSink
27
+ from braid_ai.cancel import CancelToken
28
+ from braid_ai.types import JsonValue, TextContent
29
+ from braid_coding_agent.session.plan import (
30
+ PLAN_STEP_STATUSES,
31
+ PlanStep,
32
+ PlanStepStatus,
33
+ PlanStore,
34
+ plan_to_wire,
35
+ )
36
+ from braid_coding_agent.tools.args import object_list_arg
37
+
38
+ __all__ = [
39
+ "PROMPT_GUIDELINES",
40
+ "PROMPT_SNIPPET",
41
+ "UPDATE_PLAN_PARAMETERS",
42
+ "create_update_plan_tool",
43
+ ]
44
+
45
+ UPDATE_PLAN_PARAMETERS: dict[str, JsonValue] = {
46
+ "type": "object",
47
+ "properties": {
48
+ "steps": {
49
+ "type": "array",
50
+ "description": (
51
+ "Ordered step list. Replace the whole plan on every call: include the steps "
52
+ "you have already finished, with status completed."
53
+ ),
54
+ "items": {
55
+ "type": "object",
56
+ "properties": {
57
+ "step": {
58
+ "type": "string",
59
+ "description": "One sentence describing what will be done",
60
+ },
61
+ "status": {
62
+ "type": "string",
63
+ "enum": list(PLAN_STEP_STATUSES),
64
+ "description": "pending / in_progress / completed",
65
+ },
66
+ },
67
+ "required": ["step", "status"],
68
+ "additionalProperties": False,
69
+ },
70
+ },
71
+ },
72
+ "required": ["steps"],
73
+ "additionalProperties": False,
74
+ }
75
+
76
+
77
+ def create_update_plan_tool(store: PlanStore) -> AgentTool:
78
+ """构造 ``update_plan``。``store`` 决定计划落在哪个会话树上。"""
79
+
80
+ async def execute(
81
+ tool_call_id: str,
82
+ args: dict[str, JsonValue],
83
+ signal: CancelToken | None,
84
+ on_update: ToolUpdateSink,
85
+ ) -> AgentToolResult:
86
+ del tool_call_id, signal, on_update
87
+ raw_steps = object_list_arg(args, "steps")
88
+ # 缺 ``status`` 时 KeyError:schema 已经保证它存在,缺了说明这层保证失效了。
89
+ # 猜一个 ``pending`` 会让"模型漏字段"变成一条静默写坏的计划。
90
+ steps = tuple(
91
+ PlanStep(step=_text(item["step"]), status=_status(item["status"])) for item in raw_steps
92
+ )
93
+ changed = store.update(steps)
94
+ return AgentToolResult(
95
+ content=[TextContent(text=store.summary())],
96
+ details={"plan": plan_to_wire(store.state), "changed": changed},
97
+ )
98
+
99
+ return AgentTool(
100
+ name="update_plan",
101
+ label="update_plan",
102
+ description=(
103
+ "Record or update the step list for a multi-step task. Call this before starting "
104
+ "the work, then call it again whenever a step changes state. Always pass the full "
105
+ "list: keep finished steps with status completed. The plan is shown to the user "
106
+ "and survives compaction, but it is not part of the conversation history."
107
+ ),
108
+ parameters=UPDATE_PLAN_PARAMETERS,
109
+ execute=execute,
110
+ )
111
+
112
+
113
+ def _text(value: JsonValue) -> str:
114
+ if not isinstance(value, str):
115
+ raise ValueError(f"计划步骤的 step 应为字符串,实际是 {type(value).__name__}")
116
+ return value
117
+
118
+
119
+ def _status(value: JsonValue) -> PlanStepStatus:
120
+ if not isinstance(value, str):
121
+ raise ValueError(f"计划步骤的 status 应为字符串,实际是 {type(value).__name__}")
122
+ # 取值合法性由 ``PlanStore._normalize`` 统一判定:校验只写在一处,工具不重复实现。
123
+ return cast("PlanStepStatus", value)
124
+
125
+
126
+ #: 系统提示词里这一行怎么介绍 ``update_plan``。
127
+ PROMPT_SNIPPET = "Record and update a step list for multi-step work"
128
+
129
+ #: 只有 ``update_plan`` 可执行时才出现的规则条目。
130
+ #:
131
+ #: 四条顺序即执行顺序:先读再计划、计划里只有一个在进行、每完成一步就更新、收尾时
132
+ #: 跑验证并报告。写成规则而不是写进 ``preamble``,是因为没有这个工具的会话(例如
133
+ #: 只读子代理)不该被要求"先给计划"。
134
+ PROMPT_GUIDELINES: tuple[str, ...] = (
135
+ "For multi-step tasks, read the relevant files first, then call update_plan with concrete "
136
+ "steps before editing anything",
137
+ "Keep exactly one step in_progress while you work, and update the plan as soon as a step "
138
+ "finishes instead of batching the updates at the end",
139
+ "Before your final answer, run the project's verification command for what you changed and "
140
+ "mark the corresponding steps completed",
141
+ )
@@ -0,0 +1,52 @@
1
+ """``lsp`` / ``verify`` / ``format`` 三个工程能力工具在系统提示词里的四段文字。
2
+
3
+ ## 为什么单独放在这个文件里
4
+
5
+ ``braid_coding_agent.tools`` 是提示词表的唯一汇总点(见包文档),它需要这三组文字。
6
+ 但那三个工具的实现分散在各自的包里,而它们的实现模块要 import ``tools.args`` /
7
+ ``tools.path_utils`` / ``tools.truncate``——一旦汇总点反过来 import 实现模块,
8
+ 两边就会在"谁先初始化"上互相等待:先 import ``lsp.tool`` 时,``tools.__init__``
9
+ 还没跑完,汇总点去读 ``lsp.tool`` 的属性只能读到半截模块。
10
+
11
+ 把这些字符串放进一个不 import 任何东西的模块,两个方向都能安全 import:
12
+
13
+ - ``tools.__init__`` 直接读这里,不必碰实现模块;
14
+ - 实现模块从这里取自己的那两段,公开的 ``PROMPT_SNIPPET`` / ``PROMPT_GUIDELINES``
15
+ 仍然是它自己模块上的名字(测试与调用方按那个路径取)。
16
+
17
+ 文字本身仍然属于对应工具:改 ``lsp`` 的措辞只改这里的一处。
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ LSP_SNIPPET = "Query the language server: diagnostics, definition, references, symbols"
23
+
24
+ LSP_GUIDELINES: tuple[str, ...] = (
25
+ "After editing a file, call lsp with action=diagnostics on it and fix the errors it "
26
+ "reports before telling the user the change is done; do not claim code type-checks "
27
+ "without asking the language server or running the project's type checker",
28
+ )
29
+
30
+ VERIFY_SNIPPET = "Run the project's configured lint / typecheck / test commands"
31
+
32
+ VERIFY_GUIDELINES: tuple[str, ...] = (
33
+ "Before your final answer, run verify and report its result. If it fails, fix the "
34
+ "errors and run it again; never describe a check as passing without a verify or bash "
35
+ "run in this session",
36
+ )
37
+
38
+ FORMAT_SNIPPET = "Format a file with the project's configured formatter"
39
+
40
+ FORMAT_GUIDELINES: tuple[str, ...] = (
41
+ "After editing a file that the project formats, run format on it; do not hand-format "
42
+ "code the project's formatter would rewrite",
43
+ )
44
+
45
+ __all__ = [
46
+ "FORMAT_GUIDELINES",
47
+ "FORMAT_SNIPPET",
48
+ "LSP_GUIDELINES",
49
+ "LSP_SNIPPET",
50
+ "VERIFY_GUIDELINES",
51
+ "VERIFY_SNIPPET",
52
+ ]