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,359 @@
1
+ """``bash``:在本机执行一条命令,把 stdout 与 stderr 合成一段输出。
2
+
3
+ 这个工具是整套工具里唯一能产生**任意副作用**的一个,
4
+ 所以它的边界条件比其他六个都多:
5
+
6
+ 1. **stdout 与 stderr 合并**。模型不关心一段报错走的是哪个文件描述符,分两段发给它
7
+ 反而要它自己拼时间顺序。合并后按到达顺序排列——这也是人看终端时的顺序。
8
+ 2. **超时与取消都要杀进程组**。只 ``kill`` shell 不够:``bash -c 'sleep 100 &'`` 的
9
+ 后台进程会继续持有管道,读端等不到 EOF,工具就永远不返回。
10
+ 3. **非 0 退出码是错误结果,但输出必须完整保留**。模型需要看到命令打印了什么才能
11
+ 判断为什么失败;``is_error=True`` 只影响下一回合的措辞,不影响内容。
12
+ 4. **截断保留尾部**。命令输出"结尾最重要":最后的报错、最后的统计。完整输出落盘,
13
+ 结果里给出路径,模型可以接着 ``read`` 或 ``grep`` 它。文件放在调用方给的
14
+ :class:`ToolOutputStore` 里,目录与保留期由会话决定。
15
+
16
+ 超时单位是**秒**。不给参数时用 :data:`DEFAULT_TIMEOUT_SECONDS`(120 秒),上限是
17
+ :data:`MAX_TIMEOUT_SECONDS`(600 秒):一条编译命令跑几分钟是正常的,但"永远等下去"
18
+ 不是——模型看不到终端的计时器,只能靠结果里的那句话知道自己等在哪一步。
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import asyncio
24
+ import os
25
+ import time
26
+ from collections.abc import Mapping, Sequence
27
+ from typing import TYPE_CHECKING
28
+
29
+ from braid_agent.tools import AgentTool, AgentToolResult, ToolUpdateSink, resolve_tool_timeout
30
+ from braid_ai.cancel import CancelToken
31
+ from braid_ai.types import JsonValue, TextContent
32
+ from braid_coding_agent.sandbox.proxy import NetworkDenial
33
+ from braid_coding_agent.tools.args import optional_number_arg, string_arg
34
+ from braid_coding_agent.tools.operations import (
35
+ CommandTimedOut,
36
+ LocalShellOperations,
37
+ OperationAborted,
38
+ ShellOperations,
39
+ )
40
+ from braid_coding_agent.tools.output_accumulator import OutputAccumulator, OutputSnapshot
41
+ from braid_coding_agent.tools.output_store import ToolOutputStore
42
+ from braid_coding_agent.tools.truncate import DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, format_size
43
+
44
+ if TYPE_CHECKING:
45
+ # 运行时不导入:``sandbox.operations`` 依赖 ``tools.operations``,导入会成环。
46
+ from braid_coding_agent.sandbox.operations import SandboxOperations
47
+
48
+ BASH_UPDATE_THROTTLE_MS = 100
49
+
50
+ #: 模型没给 ``timeout`` 时的执行上限(秒)。
51
+ DEFAULT_TIMEOUT_SECONDS = 120.0
52
+
53
+ #: ``timeout`` 的上限(秒)。更长的命令应当拆小,或交给后台任务。
54
+ MAX_TIMEOUT_SECONDS = 600.0
55
+
56
+ #: 更新循环的检查间隔(秒)。50ms 的粒度意味着"停止更新"最多晚 50ms,可忽略。
57
+ _TICK_SECONDS = 0.05
58
+
59
+ BASH_PARAMETERS: dict[str, JsonValue] = {
60
+ "type": "object",
61
+ "properties": {
62
+ "command": {"type": "string", "description": "Shell command to execute"},
63
+ "timeout": {
64
+ "type": "number",
65
+ "description": (
66
+ f"Timeout in seconds. Defaults to {DEFAULT_TIMEOUT_SECONDS:g}; "
67
+ f"the maximum is {MAX_TIMEOUT_SECONDS:g}."
68
+ ),
69
+ },
70
+ },
71
+ "required": ["command"],
72
+ "additionalProperties": False,
73
+ }
74
+
75
+
76
+ def create_bash_tool(
77
+ cwd: str,
78
+ *,
79
+ output_store: ToolOutputStore,
80
+ operations: ShellOperations | None = None,
81
+ shell: str = "bash",
82
+ command_prefix: str | None = None,
83
+ env: Mapping[str, str] | None = None,
84
+ max_lines: int = DEFAULT_MAX_LINES,
85
+ max_bytes: int = DEFAULT_MAX_BYTES,
86
+ sandbox: SandboxOperations | None = None,
87
+ ) -> AgentTool:
88
+ """构造 ``bash`` 工具。
89
+
90
+ :param output_store: 完整输出的落盘目录。会话级,负责数量上限与保留期。
91
+ :param command_prefix: 每条命令前先执行的一段脚本(例如 ``source .venv/bin/activate``)。
92
+ :param env: 额外环境变量;``None`` 表示继承当前进程环境。
93
+ :param sandbox: 沙箱执行层。给了就把它当作 ``operations``,并把「这次生效的边界」
94
+ 写进结果——模型看不到进程边界,只能从结果里读出来。
95
+ """
96
+ ops: ShellOperations = (
97
+ sandbox
98
+ if sandbox is not None
99
+ else operations
100
+ if operations is not None
101
+ else LocalShellOperations(shell=shell)
102
+ )
103
+
104
+ async def execute(
105
+ tool_call_id: str,
106
+ args: dict[str, JsonValue],
107
+ signal: CancelToken | None,
108
+ on_update: ToolUpdateSink,
109
+ ) -> AgentToolResult:
110
+ command = string_arg(args, "command")
111
+ timeout = resolve_tool_timeout(
112
+ requested=optional_number_arg(args, "timeout"),
113
+ default_s=DEFAULT_TIMEOUT_SECONDS,
114
+ max_s=MAX_TIMEOUT_SECONDS,
115
+ )
116
+ resolved_command = f"{command_prefix}\n{command}" if command_prefix else command
117
+ output = OutputAccumulator(
118
+ store=output_store, max_lines=max_lines, max_bytes=max_bytes, temp_prefix="braid-bash"
119
+ )
120
+ started = time.monotonic()
121
+ reporter = _Reporter(output, on_update)
122
+
123
+ def on_data(data: bytes) -> None:
124
+ output.append(data)
125
+ reporter.mark_dirty()
126
+
127
+ await on_update(AgentToolResult())
128
+ await reporter.start()
129
+ try:
130
+ exit_code = await ops.exec(
131
+ resolved_command,
132
+ os.path.abspath(cwd),
133
+ on_data=on_data,
134
+ timeout=timeout,
135
+ signal=signal,
136
+ env=env,
137
+ )
138
+ except CommandTimedOut as error:
139
+ raise RuntimeError(
140
+ _failure_text(output, f"Command timed out after {error.seconds:g} seconds")
141
+ ) from error
142
+ except OperationAborted as error:
143
+ raise RuntimeError(_failure_text(output, "Command aborted")) from error
144
+ finally:
145
+ await reporter.stop()
146
+
147
+ snapshot = _finish(output)
148
+ wall_time = round((time.monotonic() - started) * 10) / 10
149
+ # 先关再读:临时文件是缓冲写,不 close 就读只能读到一半。
150
+ output.close()
151
+ full_output = output.read_full_output()
152
+
153
+ # 拒绝记录在命令退出后取:代理是异步的,执行期间可能刚好记下一条。
154
+ denials = sandbox.take_denials() if sandbox is not None else ()
155
+ formatted = _format_output(snapshot)
156
+ text = formatted.text
157
+ if denials:
158
+ text = _append_status(text, _denial_text(denials))
159
+
160
+ structured: dict[str, JsonValue] = {
161
+ "output": full_output.content,
162
+ "truncated": full_output.truncated,
163
+ "exit_code": exit_code,
164
+ "wall_time_seconds": wall_time,
165
+ }
166
+ if full_output.truncated and snapshot.full_output_path is not None:
167
+ structured["full_output_path"] = snapshot.full_output_path
168
+ if sandbox is not None:
169
+ structured["sandbox"] = {
170
+ **sandbox.info.to_json(),
171
+ "network_denials": [denial.to_json() for denial in denials],
172
+ }
173
+
174
+ if exit_code != 0:
175
+ return AgentToolResult(
176
+ content=[
177
+ TextContent(text=_append_status(text, f"Command exited with code {exit_code}"))
178
+ ],
179
+ details=formatted.details,
180
+ structured_content=structured,
181
+ is_error=True,
182
+ )
183
+ return AgentToolResult(
184
+ content=[TextContent(text=text)],
185
+ details=formatted.details,
186
+ structured_content=structured,
187
+ )
188
+
189
+ description = (
190
+ "Execute a bash command in the current working directory. Returns stdout and "
191
+ f"stderr. Output is truncated to last {max_lines} lines or {max_bytes // 1024}KB "
192
+ "(whichever is hit first). If truncated, full output is saved to a temp file. "
193
+ f"The command is stopped after {DEFAULT_TIMEOUT_SECONDS:g} seconds unless you pass "
194
+ f"a larger timeout (maximum {MAX_TIMEOUT_SECONDS:g})."
195
+ )
196
+ if sandbox is not None:
197
+ info = sandbox.info
198
+ description += (
199
+ f" Sandbox: {info.mode} (filesystem {info.filesystem}, network {info.network})."
200
+ " Writes outside the workspace and temp dirs are denied; network egress is"
201
+ " filtered by policy and denied hosts are reported in the result."
202
+ )
203
+
204
+ return AgentTool(
205
+ name="bash",
206
+ label="bash",
207
+ description=description,
208
+ parameters=BASH_PARAMETERS,
209
+ execute=execute,
210
+ default_timeout_s=DEFAULT_TIMEOUT_SECONDS,
211
+ max_timeout_s=MAX_TIMEOUT_SECONDS,
212
+ timeout_parameter="timeout",
213
+ )
214
+
215
+
216
+ class _FormattedOutput:
217
+ """模型可见文本 + ``details``。两者必须同时产出,否则截断信息会丢一处。"""
218
+
219
+ __slots__ = ("details", "text")
220
+
221
+ def __init__(self, text: str, details: JsonValue) -> None:
222
+ self.text = text
223
+ self.details = details
224
+
225
+
226
+ def _finish(output: OutputAccumulator) -> OutputSnapshot:
227
+ """结束累积并取快照。超时/取消/正常退出三条路径都要走它。"""
228
+ output.finish()
229
+ return output.snapshot(persist_if_truncated=True)
230
+
231
+
232
+ def _failure_text(output: OutputAccumulator, status: str) -> str:
233
+ """失败时的错误文本:已产生的输出 + 失败原因。
234
+
235
+ 只抛一句 ``Command timed out`` 会让模型丢掉"超时前打印了什么"——而那通常是
236
+ 判断"要不要缩小范围重试"的唯一线索。
237
+ """
238
+ snapshot = _finish(output)
239
+ output.close()
240
+ return _append_status(_format_output(snapshot, empty_text="").text, status)
241
+
242
+
243
+ def _format_output(
244
+ snapshot: OutputSnapshot, *, empty_text: str = "(no output)"
245
+ ) -> _FormattedOutput:
246
+ truncation = snapshot.truncation
247
+ text = snapshot.content or empty_text
248
+ details: JsonValue = None
249
+ if truncation.truncated:
250
+ details = {
251
+ "truncation": truncation.to_details(),
252
+ "full_output_path": snapshot.full_output_path,
253
+ }
254
+ start_line = truncation.total_lines - truncation.output_lines + 1
255
+ end_line = truncation.total_lines
256
+ if truncation.last_line_partial:
257
+ text += (
258
+ f"\n\n[Showing last {format_size(truncation.output_bytes)} of line {end_line}. "
259
+ f"Full output: {snapshot.full_output_path}]"
260
+ )
261
+ elif truncation.truncated_by == "lines":
262
+ text += (
263
+ f"\n\n[Showing lines {start_line}-{end_line} of {truncation.total_lines}. "
264
+ f"Full output: {snapshot.full_output_path}]"
265
+ )
266
+ else:
267
+ text += (
268
+ f"\n\n[Showing lines {start_line}-{end_line} of {truncation.total_lines} "
269
+ f"({format_size(truncation.max_bytes)} limit). "
270
+ f"Full output: {snapshot.full_output_path}]"
271
+ )
272
+ return _FormattedOutput(text, details)
273
+
274
+
275
+ def _append_status(text: str, status: str) -> str:
276
+ return f"{text}\n\n{status}" if text else status
277
+
278
+
279
+ def _denial_text(denials: Sequence[NetworkDenial]) -> str:
280
+ """把被拒绝的出站连接写成模型能行动的一段话。
281
+
282
+ 只说 ``exit code 1`` 时模型会重试同一条命令;写清主机与被哪条策略拦下,它才有
283
+ 机会换域名、换方案或请用户加白名单。
284
+ """
285
+ lines = ["sandbox network requests denied:"]
286
+ for denial in denials:
287
+ lines.append(f"- {denial.method} {denial.host}:{denial.port} — {denial.reason}")
288
+ lines.append(
289
+ "Add the host to sandbox.allow_domains, pass --sandbox-allow-domain, or set"
290
+ ' network = "allow" if the user really wants unrestricted egress.'
291
+ )
292
+ return "\n".join(lines)
293
+
294
+
295
+ class _Reporter:
296
+ """把累积中的输出按固定间隔推给 UI。
297
+
298
+ 用"轮询 + 脏标记":命令可能每秒产出几千块,逐块推会把事件流塞满;固定间隔则
299
+ 无论多快都只推 10 次/秒。停止也不用取消任务——循环自己看标志退出,避免
300
+ ``Task.cancel()`` 穿透到 ``on_update`` 里的 await。
301
+ """
302
+
303
+ __slots__ = ("_dirty", "_on_update", "_output", "_stopped", "_task")
304
+
305
+ def __init__(self, output: OutputAccumulator, on_update: ToolUpdateSink) -> None:
306
+ self._output = output
307
+ self._on_update = on_update
308
+ self._dirty = False
309
+ self._stopped = False
310
+ self._task: asyncio.Task[None] | None = None
311
+
312
+ async def start(self) -> None:
313
+ self._task = asyncio.create_task(self._run())
314
+
315
+ def mark_dirty(self) -> None:
316
+ self._dirty = True
317
+
318
+ async def stop(self) -> None:
319
+ self._stopped = True
320
+ task = self._task
321
+ self._task = None
322
+ if task is not None:
323
+ await task
324
+
325
+ async def _run(self) -> None:
326
+ last_emit = time.monotonic()
327
+ while not self._stopped:
328
+ await asyncio.sleep(_TICK_SECONDS)
329
+ if not self._dirty:
330
+ continue
331
+ if time.monotonic() - last_emit < BASH_UPDATE_THROTTLE_MS / 1000:
332
+ continue
333
+ self._dirty = False
334
+ last_emit = time.monotonic()
335
+ snapshot = self._output.snapshot(persist_if_truncated=True)
336
+ await self._on_update(
337
+ AgentToolResult(
338
+ content=[TextContent(text=snapshot.content)],
339
+ details={"full_output_path": snapshot.full_output_path},
340
+ )
341
+ )
342
+
343
+
344
+ PROMPT_SNIPPET = "Execute bash commands (ls, grep, find, etc.)"
345
+
346
+ PROMPT_GUIDELINES: tuple[str, ...] = (
347
+ "You can inspect PI_* environment variables for current model and session details.",
348
+ )
349
+
350
+
351
+ __all__ = [
352
+ "BASH_PARAMETERS",
353
+ "BASH_UPDATE_THROTTLE_MS",
354
+ "DEFAULT_TIMEOUT_SECONDS",
355
+ "MAX_TIMEOUT_SECONDS",
356
+ "PROMPT_GUIDELINES",
357
+ "PROMPT_SNIPPET",
358
+ "create_bash_tool",
359
+ ]
@@ -0,0 +1,298 @@
1
+ """``edit``:对单个文件做一处或多处精确文本替换。
2
+
3
+ 工具本身只负责 I/O 与形态还原,匹配与替换在
4
+ :mod:`braid_coding_agent.tools.edit_diff`。
5
+
6
+ ## 为什么一次调用可以带多段替换
7
+
8
+ 模型改一个文件的三处内容时,如果拆成三次调用,每次都要重读文件、每次都可能因为
9
+ 中间状态而失配;更糟的是第二次的 ``oldText`` 可能被第一次的替换改掉了。一次调用带
10
+ 多段、全部对**同一份原文**匹配,把"多段编辑"变成一个原子操作。
11
+
12
+ ## 参数修补(``prepare_arguments``)
13
+
14
+ 真实模型有两种常见写法与声明的 schema 不符:
15
+
16
+ - 把 ``edits`` 写成 JSON **字符串**(Opus 4.6 / GLM-5.1 有这种行为);
17
+ - 把单段编辑写成顶层 ``oldText``/``newText``(旧版工具声明的形状)。
18
+
19
+ 这两类都在校验**之前**修好。它们属于"这一个工具的参数历史",与厂商无关,因此放在
20
+ 工具里;修好之后仍要走完整的 schema 校验,执行代码不再自己判一遍。
21
+
22
+ ## 换行、BOM 与写回
23
+
24
+ 匹配在 LF 归一化、无 BOM 的文本上做;写回时按**原文件**的换行风格与 BOM 还原。
25
+ 一个 CRLF 文件不能因为一次编辑变成混合换行——那样整篇文件的 diff 都会变脏,
26
+ 后续的 ``git diff`` 也看不出真实改动。
27
+
28
+ ## 编码与二进制保护
29
+
30
+ 读到的字节按 ``encoding``(默认 ``utf-8``)严格解码,写回用同一个编码。宽松解码会把
31
+ 无法识别的字节变成 ``U+FFFD``,一次成功报告背后是整篇文件被改写。解码、编码两步都在
32
+ **打开写句柄之前**完成:任何一步失败都抛 :class:`EditError`,文件字节保持原样。含 NUL
33
+ 字节的文件按二进制拒绝,避免把编译产物、UTF-16 数据当文本重写。
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import json
39
+ from typing import Final
40
+
41
+ from braid_agent.tools import AgentTool, AgentToolResult, ToolUpdateSink
42
+ from braid_ai.cancel import CancelToken
43
+ from braid_ai.types import JsonValue, TextContent
44
+ from braid_coding_agent.tools.args import object_list_arg, optional_string_arg, string_arg
45
+ from braid_coding_agent.tools.edit_diff import (
46
+ Edit,
47
+ EditError,
48
+ apply_edits,
49
+ detect_line_ending,
50
+ normalize_to_lf,
51
+ restore_line_endings,
52
+ split_bom,
53
+ )
54
+ from braid_coding_agent.tools.mutation_queue import DEFAULT_MUTATION_QUEUE, FileMutationQueue
55
+ from braid_coding_agent.tools.operations import (
56
+ FileOperations,
57
+ LocalFileOperations,
58
+ ensure_not_cancelled,
59
+ )
60
+ from braid_coding_agent.tools.path_utils import resolve_to_cwd
61
+
62
+ #: 不传 ``encoding`` 时使用的文本编码。写回时用同一个值。
63
+ DEFAULT_EDIT_ENCODING: Final[str] = "utf-8"
64
+
65
+ EDIT_PARAMETERS: dict[str, JsonValue] = {
66
+ "type": "object",
67
+ "properties": {
68
+ "path": {
69
+ "type": "string",
70
+ "description": "Path to the file to edit (relative or absolute)",
71
+ },
72
+ "encoding": {
73
+ "type": "string",
74
+ "description": (
75
+ "Text encoding of the file (default: utf-8). The file is decoded strictly "
76
+ "with this encoding and written back with the same one. Use gbk, shift_jis "
77
+ "or latin-1 for files that are not UTF-8."
78
+ ),
79
+ },
80
+ "edits": {
81
+ "type": "array",
82
+ "description": (
83
+ "One or more targeted replacements. Each edit is matched against the original "
84
+ "file, not incrementally. Do not include overlapping or nested edits. If two "
85
+ "changes touch the same block or nearby lines, merge them into one edit instead."
86
+ ),
87
+ "items": {
88
+ "type": "object",
89
+ "properties": {
90
+ "oldText": {
91
+ "type": "string",
92
+ "description": (
93
+ "Exact text for one targeted replacement. It must be unique in the "
94
+ "original file and must not overlap with any other edits[].oldText "
95
+ "in the same call."
96
+ ),
97
+ },
98
+ "newText": {
99
+ "type": "string",
100
+ "description": "Replacement text for this targeted edit.",
101
+ },
102
+ },
103
+ "required": ["oldText", "newText"],
104
+ "additionalProperties": False,
105
+ },
106
+ },
107
+ },
108
+ "required": ["path", "edits"],
109
+ "additionalProperties": False,
110
+ }
111
+
112
+
113
+ def decode_edit_source(raw: bytes, path: str, encoding: str) -> str:
114
+ """把待编辑的字节严格解码成文本;失败时抛 ``EditError``,调用方不会写文件。"""
115
+ if b"\x00" in raw:
116
+ raise EditError(
117
+ f"Could not edit file: {path}. The file contains NUL bytes and appears to be binary. "
118
+ "edit only writes text files. Convert it to a text encoding before editing."
119
+ )
120
+ try:
121
+ return raw.decode(encoding)
122
+ except UnicodeDecodeError as error:
123
+ bad_byte = raw[error.start : error.start + 1].hex() or "end of file"
124
+ raise EditError(
125
+ f"Could not edit file: {path}. The file is not valid {encoding}: "
126
+ f"byte 0x{bad_byte} at offset {error.start} ({error.reason}). "
127
+ "The file was left unchanged. Pass the matching encoding "
128
+ '(for example encoding="gbk") or convert the file to UTF-8 before editing.'
129
+ ) from error
130
+ except LookupError as error:
131
+ raise EditError(
132
+ f"Could not edit file: {path}. Unknown encoding {encoding!r}. "
133
+ "Use a Python codec name such as utf-8, gbk, shift_jis or latin-1."
134
+ ) from error
135
+
136
+
137
+ def encode_edit_content(content: str, path: str, encoding: str) -> bytes:
138
+ """按读时相同的编码写回;编码失败时抛 ``EditError``,文件保持原样。"""
139
+ try:
140
+ return content.encode(encoding)
141
+ except UnicodeEncodeError as error:
142
+ raise EditError(
143
+ f"Could not edit file: {path}. The replacement text cannot be encoded as "
144
+ f"{encoding} (character {error.object[error.start]!r} at position {error.start}). "
145
+ "The file was left unchanged. Use characters representable in this encoding, "
146
+ "or convert the file to UTF-8 first."
147
+ ) from error
148
+
149
+
150
+ def create_edit_tool(
151
+ cwd: str,
152
+ *,
153
+ operations: FileOperations | None = None,
154
+ queue: FileMutationQueue | None = None,
155
+ ) -> AgentTool:
156
+ """构造 ``edit`` 工具。``cwd`` 是相对路径的基准目录。"""
157
+ ops: FileOperations = operations if operations is not None else LocalFileOperations()
158
+ mutations = queue if queue is not None else DEFAULT_MUTATION_QUEUE
159
+
160
+ async def execute(
161
+ tool_call_id: str,
162
+ args: dict[str, JsonValue],
163
+ signal: CancelToken | None,
164
+ on_update: ToolUpdateSink,
165
+ ) -> AgentToolResult:
166
+ path = string_arg(args, "path")
167
+ edits = [
168
+ Edit(string_arg(item, "oldText"), string_arg(item, "newText"))
169
+ for item in object_list_arg(args, "edits")
170
+ ]
171
+ encoding_arg = optional_string_arg(args, "encoding")
172
+ encoding = DEFAULT_EDIT_ENCODING if encoding_arg is None else encoding_arg
173
+ absolute_path = resolve_to_cwd(path, cwd)
174
+
175
+ async def edit() -> AgentToolResult:
176
+ ensure_not_cancelled(signal)
177
+ try:
178
+ await ops.check_access(absolute_path, write=True)
179
+ except OSError as error:
180
+ raise EditError(f"Could not edit file: {path}. {error}.") from error
181
+
182
+ raw = await ops.read_bytes(absolute_path)
183
+ ensure_not_cancelled(signal)
184
+ source = decode_edit_source(raw, path, encoding)
185
+
186
+ bom, content = split_bom(source)
187
+ ending = detect_line_ending(content)
188
+ applied = apply_edits(normalize_to_lf(content), edits, path)
189
+ final_content = bom + restore_line_endings(applied.new_content, ending)
190
+ final_bytes = encode_edit_content(final_content, path, encoding)
191
+
192
+ await ops.write_bytes(absolute_path, final_bytes)
193
+ ensure_not_cancelled(signal)
194
+ return AgentToolResult(
195
+ content=[
196
+ TextContent(text=f"Successfully replaced {len(edits)} block(s) in {path}.")
197
+ ],
198
+ details={
199
+ "path": absolute_path,
200
+ "diff": applied.diff,
201
+ "patch": applied.patch,
202
+ "first_changed_line": applied.first_changed_line,
203
+ "encoding": encoding,
204
+ },
205
+ )
206
+
207
+ return await mutations.run(absolute_path, edit)
208
+
209
+ return AgentTool(
210
+ name="edit",
211
+ label="edit",
212
+ description=(
213
+ "Edit a single file using exact text replacement. Every edits[].oldText must match "
214
+ "a unique, non-overlapping region of the original file. If two changes affect the "
215
+ "same block or nearby lines, merge them into one edit instead of emitting "
216
+ "overlapping edits. Do not include large unchanged regions just to connect distant "
217
+ "changes. Files are decoded strictly as UTF-8 by default; pass encoding for "
218
+ "text files in other encodings."
219
+ ),
220
+ parameters=EDIT_PARAMETERS,
221
+ execute=execute,
222
+ prepare_arguments=prepare_edit_arguments,
223
+ )
224
+
225
+
226
+ def prepare_edit_arguments(args: dict[str, JsonValue]) -> dict[str, JsonValue]:
227
+ """把"JSON 字符串形式的 edits"与"顶层 oldText/newText"修成 schema 认可的形状。
228
+
229
+ 修补是**幂等**的:已经是正确形状的参数原样返回(复制一份,不改调用方的对象)。
230
+ """
231
+ prepared = dict(args)
232
+ edits = prepared.get("edits")
233
+ if isinstance(edits, str):
234
+ prepared["edits"] = _parse_edits_string(edits)
235
+ elif is_single_edit(edits):
236
+ prepared["edits"] = [edits]
237
+
238
+ legacy_old = prepared.get("oldText")
239
+ legacy_new = prepared.get("newText")
240
+ if isinstance(legacy_old, str) and isinstance(legacy_new, str):
241
+ merged = prepared.get("edits")
242
+ collected = list(merged) if isinstance(merged, list) else []
243
+ collected.append({"oldText": legacy_old, "newText": legacy_new})
244
+ prepared["edits"] = collected
245
+ del prepared["oldText"]
246
+ del prepared["newText"]
247
+ return prepared
248
+
249
+
250
+ def is_single_edit(value: JsonValue) -> bool:
251
+ """``{"oldText": str, "newText": str}`` 这样的单个编辑对象。"""
252
+ if not isinstance(value, dict):
253
+ return False
254
+ return isinstance(value.get("oldText"), str) and isinstance(value.get("newText"), str)
255
+
256
+
257
+ def _parse_edits_string(raw: str) -> JsonValue:
258
+ try:
259
+ parsed: JsonValue = json.loads(raw)
260
+ except json.JSONDecodeError as error:
261
+ raise ValueError(
262
+ f"edits was a string but not valid JSON ({error.msg} at position {error.pos}); "
263
+ "pass edits as an array of {oldText, newText} objects."
264
+ ) from error
265
+ if isinstance(parsed, list):
266
+ return parsed
267
+ if is_single_edit(parsed):
268
+ return [parsed]
269
+ return parsed
270
+
271
+
272
+ PROMPT_SNIPPET = (
273
+ "Make precise file edits with exact text replacement, "
274
+ "including multiple disjoint edits in one call"
275
+ )
276
+
277
+ PROMPT_GUIDELINES: tuple[str, ...] = (
278
+ "Use edit for precise changes (edits[].oldText must match exactly)",
279
+ "When changing multiple separate locations in one file, use one edit call with "
280
+ "multiple entries in edits[] instead of multiple edit calls",
281
+ "Each edits[].oldText is matched against the original file, not after earlier edits "
282
+ "are applied. Do not emit overlapping or nested edits. Merge nearby changes into one edit.",
283
+ "Keep edits[].oldText as small as possible while still being unique in the file. "
284
+ "Do not pad with large unchanged regions.",
285
+ )
286
+
287
+
288
+ __all__ = [
289
+ "DEFAULT_EDIT_ENCODING",
290
+ "EDIT_PARAMETERS",
291
+ "PROMPT_GUIDELINES",
292
+ "PROMPT_SNIPPET",
293
+ "create_edit_tool",
294
+ "decode_edit_source",
295
+ "encode_edit_content",
296
+ "is_single_edit",
297
+ "prepare_edit_arguments",
298
+ ]