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,260 @@
1
+ """按配置顺序跑验证命令,把退出码与关键输出折成一段可行动的摘要。
2
+
3
+ ## 为什么不是直接让模型跑 ``bash``
4
+
5
+ ``bash`` 能跑同样的命令,但两件事它做不到:
6
+
7
+ 1. **顺序与完整性由配置保证**。哪几条命令算"验证"是项目约定,不该每次由模型临场决定;
8
+ 模型漏跑类型检查时,用户从回答里看不出来。
9
+ 2. **失败预算**。连续三次验证失败之后必须停下来报告,而不是继续"再改一版试试"。
10
+ 这个计数需要一个跨调用存在的对象,``bash`` 是无状态的。
11
+
12
+ ## 输出怎么截
13
+
14
+ 一条 ``pytest`` 失败可能打印几千行。汇总里每条命令只保留**尾部** 40 行 / 8KB:
15
+ 失败的原因与统计都在尾部。整段输出超过 512KB 时保留头尾各 256KB,中间插一行标记——
16
+ ``ruff`` 的错误在头部、``pytest`` 的结论在尾部,只留一边都会丢掉关键信息。
17
+
18
+ ## 退出码与"没跑完"是两件事
19
+
20
+ 超时不算"失败退出码 1":前者的含义是"这条命令的结果未知",后者是"它跑完了并报告有
21
+ 问题"。摘要里分开写,模型才知道该重跑还是该改代码。
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import time
27
+ from collections.abc import Mapping
28
+ from dataclasses import dataclass
29
+
30
+ from braid_ai.cancel import CancelToken
31
+ from braid_coding_agent.cancellation import OperationAborted
32
+ from braid_coding_agent.tools.operations import CommandTimedOut, ShellOperations
33
+ from braid_coding_agent.tools.truncate import clip_tail
34
+ from braid_coding_agent.verify.settings import VerifyCommand, VerifySettings
35
+
36
+ #: 单条命令展示的行数与字节上限。
37
+ STEP_MAX_LINES = 40
38
+ STEP_MAX_BYTES = 8 * 1024
39
+ #: 缓冲的头尾各留多少字节。超过这个量就认为输出太长,只保留两端。
40
+ _BUFFER_SIDE_BYTES = 256 * 1024
41
+
42
+
43
+ @dataclass(slots=True, frozen=True)
44
+ class StepOutcome:
45
+ """一条验证命令的结果。``exit_code`` 为 ``None`` 表示它没有跑完。"""
46
+
47
+ name: str
48
+ command: str
49
+ exit_code: int | None
50
+ duration_seconds: float
51
+ output: str
52
+ timed_out: bool = False
53
+
54
+ @property
55
+ def passed(self) -> bool:
56
+ return self.exit_code == 0
57
+
58
+ @property
59
+ def status(self) -> str:
60
+ if self.timed_out:
61
+ return "timed out"
62
+ if self.exit_code is None:
63
+ return "did not finish"
64
+ return "passed" if self.exit_code == 0 else f"failed (exit {self.exit_code})"
65
+
66
+
67
+ @dataclass(slots=True, frozen=True)
68
+ class VerifyReport:
69
+ """一次验证的完整结果。
70
+
71
+ ``configured`` 是配置里的命令名,``steps`` 可能只是它的前缀(``fail_fast`` 之后
72
+ 剩下的没有执行)。两者分开存,摘要才能写清"哪些没跑"。
73
+ """
74
+
75
+ steps: tuple[StepOutcome, ...]
76
+ configured: tuple[str, ...]
77
+ duration_seconds: float
78
+
79
+ @property
80
+ def total(self) -> int:
81
+ return len(self.configured)
82
+
83
+ @property
84
+ def passed(self) -> bool:
85
+ return len(self.steps) == self.total and all(step.passed for step in self.steps)
86
+
87
+ @property
88
+ def failures(self) -> tuple[StepOutcome, ...]:
89
+ return tuple(step for step in self.steps if not step.passed)
90
+
91
+ @property
92
+ def skipped(self) -> tuple[str, ...]:
93
+ """没有执行的命令名,按配置顺序。"""
94
+ return self.configured[len(self.steps) :]
95
+
96
+
97
+ @dataclass(slots=True)
98
+ class VerifyBudget:
99
+ """连续失败计数。跨工具调用存在,一个用户回合开始时清零。
100
+
101
+ ``limit`` 来自 ``verify.max_consecutive_failures``。计数只在验证**通过**时清零:
102
+ 一次通过说明这一轮修复有效,之前的失败不再累积。
103
+ """
104
+
105
+ limit: int
106
+ consecutive_failures: int = 0
107
+ #: 上一次失败的报告摘要。预算用尽时把它原样交回模型,省掉一次没有结果的调用。
108
+ last_summary: str = ""
109
+
110
+ def begin_turn(self) -> None:
111
+ """新的用户回合:重新给满额度。"""
112
+ self.consecutive_failures = 0
113
+ self.last_summary = ""
114
+
115
+ def record(self, report: VerifyReport, summary: str) -> None:
116
+ if report.passed:
117
+ self.consecutive_failures = 0
118
+ self.last_summary = ""
119
+ return
120
+ self.consecutive_failures += 1
121
+ self.last_summary = summary
122
+
123
+ @property
124
+ def exhausted(self) -> bool:
125
+ return self.consecutive_failures >= self.limit
126
+
127
+ def streak_text(self) -> str:
128
+ """``failure streak: 1/3`` 这类一行说明。模型需要知道还剩几次机会。"""
129
+ return f"failure streak: {self.consecutive_failures}/{self.limit}"
130
+
131
+
132
+ class VerifyRunner:
133
+ """一个会话的验证执行器。``shell`` 决定命令在哪里跑(本机或沙箱)。"""
134
+
135
+ def __init__(
136
+ self,
137
+ settings: VerifySettings,
138
+ *,
139
+ cwd: str,
140
+ shell: ShellOperations,
141
+ env: Mapping[str, str] | None = None,
142
+ ) -> None:
143
+ self._settings = settings
144
+ self._cwd = cwd
145
+ self._shell = shell
146
+ self._env = env
147
+ self._budget = VerifyBudget(limit=settings.max_consecutive_failures)
148
+
149
+ @property
150
+ def settings(self) -> VerifySettings:
151
+ return self._settings
152
+
153
+ @property
154
+ def budget(self) -> VerifyBudget:
155
+ return self._budget
156
+
157
+ async def run(self, *, signal: CancelToken | None = None) -> VerifyReport:
158
+ """按配置顺序执行。取消直接抛出,不把半次验证当成一次失败。"""
159
+ started = time.monotonic()
160
+ outcomes: list[StepOutcome] = []
161
+ for command in self._settings.commands:
162
+ if signal is not None and signal.cancelled:
163
+ raise OperationAborted("verify aborted")
164
+ outcome = await self._run_step(command, signal)
165
+ outcomes.append(outcome)
166
+ if not outcome.passed and self._settings.fail_fast:
167
+ break
168
+ return VerifyReport(
169
+ steps=tuple(outcomes),
170
+ configured=self._settings.names(),
171
+ duration_seconds=round(time.monotonic() - started, 1),
172
+ )
173
+
174
+ async def _run_step(self, command: VerifyCommand, signal: CancelToken | None) -> StepOutcome:
175
+ buffer = _OutputBuffer()
176
+ started = time.monotonic()
177
+ timeout = self._settings.timeout_for(command)
178
+ try:
179
+ exit_code: int | None = await self._shell.exec(
180
+ command.command,
181
+ self._cwd,
182
+ on_data=buffer.append,
183
+ timeout=timeout,
184
+ signal=signal,
185
+ env=self._env,
186
+ )
187
+ timed_out = False
188
+ except CommandTimedOut:
189
+ exit_code = None
190
+ timed_out = True
191
+ duration = round(time.monotonic() - started, 1)
192
+ return StepOutcome(
193
+ name=command.name,
194
+ command=command.command,
195
+ exit_code=exit_code,
196
+ duration_seconds=duration,
197
+ output=clip_tail(buffer.text(), max_lines=STEP_MAX_LINES, max_bytes=STEP_MAX_BYTES),
198
+ timed_out=timed_out,
199
+ )
200
+
201
+
202
+ def format_report(report: VerifyReport) -> str:
203
+ """模型看到的那段文本。首行给结论,之后逐条给状态与输出。"""
204
+ passed = sum(1 for step in report.steps if step.passed)
205
+ head = f"verify: {passed}/{report.total} passed in {report.duration_seconds:g}s"
206
+ if not report.passed:
207
+ reasons = ", ".join(f"{step.name} {step.status}" for step in report.failures)
208
+ head += f" — {reasons}"
209
+ if report.skipped:
210
+ head += f" — not run: {', '.join(report.skipped)}"
211
+ lines = [head]
212
+ for index, step in enumerate(report.steps, start=1):
213
+ lines.append(
214
+ f"[{index}/{report.total}] {step.name} — {step.command} → {step.status} "
215
+ f"({step.duration_seconds:g}s)"
216
+ )
217
+ if step.output:
218
+ lines.extend(f" {line}" for line in step.output.splitlines())
219
+ return "\n".join(lines)
220
+
221
+
222
+ class _OutputBuffer:
223
+ """命令输出的头尾保留。超过上限时中间那段被丢掉并标记。"""
224
+
225
+ __slots__ = ("_dropped", "_head", "_tail")
226
+
227
+ def __init__(self) -> None:
228
+ self._head = bytearray()
229
+ self._tail = bytearray()
230
+ self._dropped = False
231
+
232
+ def append(self, data: bytes) -> None:
233
+ if len(self._head) < _BUFFER_SIDE_BYTES:
234
+ take = _BUFFER_SIDE_BYTES - len(self._head)
235
+ self._head += data[:take]
236
+ data = data[take:]
237
+ if not data:
238
+ return
239
+ self._dropped = True
240
+ self._tail += data
241
+ if len(self._tail) > _BUFFER_SIDE_BYTES:
242
+ del self._tail[: len(self._tail) - _BUFFER_SIDE_BYTES]
243
+
244
+ def text(self) -> str:
245
+ head = self._head.decode("utf-8", errors="replace")
246
+ if not self._dropped:
247
+ return head
248
+ tail = self._tail.decode("utf-8", errors="replace")
249
+ return f"{head}\n[... middle of the output dropped ...]\n{tail}"
250
+
251
+
252
+ __all__ = [
253
+ "STEP_MAX_BYTES",
254
+ "STEP_MAX_LINES",
255
+ "StepOutcome",
256
+ "VerifyBudget",
257
+ "VerifyReport",
258
+ "VerifyRunner",
259
+ "format_report",
260
+ ]
@@ -0,0 +1,64 @@
1
+ """验证命令的配置形状:按什么顺序跑、各自超时多久、失败几次就停。
2
+
3
+ ``verify.commands`` 是一个有序数组,顺序就是执行顺序。典型的一份配置把
4
+ "最便宜、最快给出信号的检查"放前面:lint → 类型 → 测试。``fail_fast = false``
5
+ (默认)会把全部命令跑完再汇总,因为模型一次拿到三类错误比修一轮问一轮更省请求;
6
+ 把最慢的测试放前面时,``fail_fast = true`` 更合适。
7
+
8
+ ``max_consecutive_failures`` 是**连续**失败的上限:一次验证通过就把计数清零。
9
+ 它保护的是"改一版跑一次、跑了三次还是红的"这种循环——三次之后工具拒绝再跑,
10
+ 模型必须停下把剩余错误报给用户。
11
+
12
+ 命令是**一段字符串**,交给 shell 执行。这与 ``bash`` 工具一致:验证命令天然需要
13
+ 管道与 ``&&``(``uv run pytest -q 2>&1 | tail -40``),拆成 argv 会让常见写法写不出来。
14
+ 代价是配置里的字符串等价于一条 shell 命令,谁改配置谁就拥有这段执行权——配置本来
15
+ 就是这个级别的东西,``lsp.*.command`` 里的 argv 也是同一个信任边界。
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from dataclasses import dataclass, field
21
+
22
+ #: 单条验证命令的默认超时(秒)。整套测试在中等项目上常在五分钟上下。
23
+ DEFAULT_VERIFY_TIMEOUT_SECONDS = 600.0
24
+ #: 连续失败多少次后停止。路线图给的是 3。
25
+ DEFAULT_MAX_CONSECUTIVE_FAILURES = 3
26
+
27
+
28
+ @dataclass(slots=True, frozen=True)
29
+ class VerifyCommand:
30
+ """一条验证命令。``name`` 用于汇总行,``timeout_seconds`` 覆盖全局值。"""
31
+
32
+ name: str
33
+ command: str
34
+ timeout_seconds: float | None = None
35
+
36
+
37
+ @dataclass(slots=True, frozen=True)
38
+ class VerifySettings:
39
+ """验证闭环的全部配置。"""
40
+
41
+ enabled: bool = True
42
+ timeout_seconds: float = DEFAULT_VERIFY_TIMEOUT_SECONDS
43
+ fail_fast: bool = False
44
+ max_consecutive_failures: int = DEFAULT_MAX_CONSECUTIVE_FAILURES
45
+ commands: tuple[VerifyCommand, ...] = field(default_factory=tuple[VerifyCommand, ...])
46
+
47
+ @property
48
+ def has_commands(self) -> bool:
49
+ """有可用命令时才给会话装 ``verify`` 工具。"""
50
+ return self.enabled and bool(self.commands)
51
+
52
+ def timeout_for(self, command: VerifyCommand) -> float:
53
+ return self.timeout_seconds if command.timeout_seconds is None else command.timeout_seconds
54
+
55
+ def names(self) -> tuple[str, ...]:
56
+ return tuple(command.name for command in self.commands)
57
+
58
+
59
+ __all__ = [
60
+ "DEFAULT_MAX_CONSECUTIVE_FAILURES",
61
+ "DEFAULT_VERIFY_TIMEOUT_SECONDS",
62
+ "VerifyCommand",
63
+ "VerifySettings",
64
+ ]
@@ -0,0 +1,143 @@
1
+ """``verify`` 工具:把"任务做完了"这句话绑在一次真实执行的检查上。
2
+
3
+ ## 预算的意义
4
+
5
+ 模型修 bug 的典型失败模式是"改一版、跑一次、还是红、再改一版"。三次之内这是正常
6
+ 迭代;三次之后继续同一个循环只是在消耗用户的 token 与时间,并且它已经不再读错误
7
+ 信息了。这里把"连续三次失败"变成一个硬边界:
8
+
9
+ 1. 第 1、2 次失败:结果里带上完整摘要与 ``failure streak: n/3``,模型继续修;
10
+ 2. 第 3 次失败:摘要里写明"下一次调用会被拒绝,现在就把剩余错误报给用户";
11
+ 3. 第 4 次调用:**不执行**,直接返回上一次的摘要并置 ``terminate``,本次 run 到此结束。
12
+
13
+ 第 3 步用的是工具结果里的 ``terminate`` 建议:整批调用的结果都为真时,循环在这一批
14
+ 执行完就停,不再请求模型。这样"停"是真实的停止,不依赖模型自愿听话。
15
+
16
+ 预算在用户发出新提示时清零(会话层调用 :meth:`VerifyBudget.begin_turn`):换了一个
17
+ 需求就是新的一轮,之前那个任务的失败次数不该继续压着它。
18
+
19
+ ## 空参数
20
+
21
+ 工具没有参数。要跑哪些命令、按什么顺序、各自超时多久,全部来自配置——模型能决定的
22
+ 只有"什么时候验证",而不是"验证什么"。把命令选择交给模型,等于让它挑几条容易通过的
23
+ 检查来证明自己做完了。
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from braid_agent.tools import AgentTool, AgentToolResult, ToolUpdateSink
29
+ from braid_ai.cancel import CancelToken
30
+ from braid_ai.types import JsonValue, TextContent
31
+ from braid_coding_agent.tools.prompt_notes import VERIFY_GUIDELINES, VERIFY_SNIPPET
32
+ from braid_coding_agent.verify.runner import VerifyRunner, format_report
33
+
34
+ VERIFY_PARAMETERS: dict[str, JsonValue] = {
35
+ "type": "object",
36
+ "properties": {},
37
+ "additionalProperties": False,
38
+ }
39
+
40
+
41
+ def create_verify_tool(runner: VerifyRunner) -> AgentTool:
42
+ """构造 ``verify``。``runner`` 持有命令配置与连续失败预算。"""
43
+
44
+ async def execute(
45
+ tool_call_id: str,
46
+ args: dict[str, JsonValue],
47
+ signal: CancelToken | None,
48
+ on_update: ToolUpdateSink,
49
+ ) -> AgentToolResult:
50
+ del tool_call_id, args, on_update
51
+ budget = runner.budget
52
+ if budget.exhausted:
53
+ # 第 4 次:不执行,把上一次的摘要原样退回,并结束本次 run。
54
+ return AgentToolResult(
55
+ content=[
56
+ TextContent(
57
+ text=(
58
+ f"verify refused: {budget.limit} consecutive verification runs "
59
+ "already failed, so it will not run again in this turn. Stop "
60
+ "editing and report the remaining errors to the user.\n\n"
61
+ f"{budget.last_summary}"
62
+ )
63
+ )
64
+ ],
65
+ details={
66
+ "refused": True,
67
+ "consecutive_failures": budget.consecutive_failures,
68
+ "limit": budget.limit,
69
+ },
70
+ is_error=True,
71
+ terminate=True,
72
+ )
73
+
74
+ report = await runner.run(signal=signal)
75
+ text = format_report(report)
76
+ budget.record(report, text)
77
+ text = f"{text}\n{budget.streak_text()}"
78
+ if not report.passed:
79
+ if budget.exhausted:
80
+ text += (
81
+ "\nThe failure limit is reached: the next verify call will be refused. "
82
+ "Report what still fails to the user instead of making more edits."
83
+ )
84
+ else:
85
+ text += (
86
+ "\nFix the errors above, then call verify again. "
87
+ f"{budget.limit - budget.consecutive_failures} attempt(s) left."
88
+ )
89
+ return AgentToolResult(
90
+ content=[TextContent(text=text)],
91
+ details={
92
+ "passed": report.passed,
93
+ "consecutive_failures": budget.consecutive_failures,
94
+ "limit": budget.limit,
95
+ },
96
+ structured_content={
97
+ "passed": report.passed,
98
+ "duration_seconds": report.duration_seconds,
99
+ "consecutive_failures": budget.consecutive_failures,
100
+ "limit": budget.limit,
101
+ "steps": [
102
+ {
103
+ "name": step.name,
104
+ "command": step.command,
105
+ "exit_code": step.exit_code,
106
+ "duration_seconds": step.duration_seconds,
107
+ "timed_out": step.timed_out,
108
+ }
109
+ for step in report.steps
110
+ ],
111
+ "skipped": list(report.skipped),
112
+ },
113
+ is_error=not report.passed,
114
+ )
115
+
116
+ names = ", ".join(runner.settings.names())
117
+ return AgentTool(
118
+ name="verify",
119
+ label="verify",
120
+ description=(
121
+ "Run the project's configured verification commands in order (lint, type check, "
122
+ f"tests: {names}) and get a summary with exit codes and the tail of each output. "
123
+ "Run this before telling the user a change is done, and again after fixing "
124
+ "failures."
125
+ ),
126
+ parameters=VERIFY_PARAMETERS,
127
+ execute=execute,
128
+ )
129
+
130
+
131
+ #: 系统提示词里这一行怎么介绍 ``verify``。
132
+ PROMPT_SNIPPET = VERIFY_SNIPPET
133
+
134
+ #: 只有 ``verify`` 可执行时才出现的规则条目。
135
+ PROMPT_GUIDELINES: tuple[str, ...] = VERIFY_GUIDELINES
136
+
137
+
138
+ __all__ = [
139
+ "PROMPT_GUIDELINES",
140
+ "PROMPT_SNIPPET",
141
+ "VERIFY_PARAMETERS",
142
+ "create_verify_tool",
143
+ ]
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.4
2
+ Name: braid-coding-agent
3
+ Version: 0.1.0
4
+ Summary: 产品组装层:会话、编码工具、提示词与命令行入口
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Dist: braid-ai>=0.1.0,<0.2
8
+ Requires-Dist: braid-agent>=0.1.0,<0.2
9
+ Requires-Dist: braid-mcp>=0.1.0,<0.2
10
+ Requires-Dist: braid-tui>=0.1.0,<0.2
11
+ Requires-Dist: httpx>=0.28
12
+ Requires-Dist: keyring>=25.0
13
+ Requires-Dist: packaging>=24.0
14
+ Requires-Dist: pathspec>=0.12
15
+ Requires-Dist: prompt-toolkit>=3.0
16
+ Requires-Dist: pyyaml>=6.0
17
+ Requires-Dist: rich>=14.0
18
+ Requires-Dist: wcwidth>=0.2
19
+ Requires-Python: >=3.12