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.
- braid_coding_agent/__init__.py +13 -0
- braid_coding_agent/assembly.py +460 -0
- braid_coding_agent/cancellation.py +25 -0
- braid_coding_agent/checkpoint/__init__.py +106 -0
- braid_coding_agent/checkpoint/git.py +305 -0
- braid_coding_agent/checkpoint/settings.py +26 -0
- braid_coding_agent/checkpoint/store.py +1261 -0
- braid_coding_agent/checkpoint/workspace.py +220 -0
- braid_coding_agent/cli.py +2168 -0
- braid_coding_agent/commands/__init__.py +50 -0
- braid_coding_agent/commands/auth.py +161 -0
- braid_coding_agent/commands/config.py +180 -0
- braid_coding_agent/commands/doctor.py +511 -0
- braid_coding_agent/commands/mcp.py +928 -0
- braid_coding_agent/commands/models.py +95 -0
- braid_coding_agent/commands/setup.py +89 -0
- braid_coding_agent/commands/uninstall.py +277 -0
- braid_coding_agent/commands/upgrade.py +381 -0
- braid_coding_agent/compaction/__init__.py +174 -0
- braid_coding_agent/compaction/prepare.py +430 -0
- braid_coding_agent/compaction/summarize.py +542 -0
- braid_coding_agent/compaction/tokens.py +204 -0
- braid_coding_agent/compaction/tool_results.py +196 -0
- braid_coding_agent/compaction/utils.py +181 -0
- braid_coding_agent/config.py +2776 -0
- braid_coding_agent/config_files.py +191 -0
- braid_coding_agent/credentials.py +252 -0
- braid_coding_agent/discovery.py +415 -0
- braid_coding_agent/extensions/__init__.py +77 -0
- braid_coding_agent/extensions/api.py +480 -0
- braid_coding_agent/extensions/runner.py +553 -0
- braid_coding_agent/formatting/__init__.py +62 -0
- braid_coding_agent/formatting/settings.py +87 -0
- braid_coding_agent/formatting/tool.py +179 -0
- braid_coding_agent/lsp/__init__.py +105 -0
- braid_coding_agent/lsp/client.py +546 -0
- braid_coding_agent/lsp/manager.py +187 -0
- braid_coding_agent/lsp/model.py +316 -0
- braid_coding_agent/lsp/protocol.py +105 -0
- braid_coding_agent/lsp/settings.py +120 -0
- braid_coding_agent/lsp/tool.py +429 -0
- braid_coding_agent/mcp/__init__.py +101 -0
- braid_coding_agent/mcp/cache.py +230 -0
- braid_coding_agent/mcp/catalog.py +108 -0
- braid_coding_agent/mcp/config.py +664 -0
- braid_coding_agent/mcp/config_store.py +142 -0
- braid_coding_agent/mcp/inspector.py +85 -0
- braid_coding_agent/mcp/panel.py +254 -0
- braid_coding_agent/mcp/runtime.py +1060 -0
- braid_coding_agent/mcp/tools.py +579 -0
- braid_coding_agent/mcp/trust.py +150 -0
- braid_coding_agent/mcp/tui_panel.py +444 -0
- braid_coding_agent/messages.py +152 -0
- braid_coding_agent/models_view.py +105 -0
- braid_coding_agent/modes/__init__.py +64 -0
- braid_coding_agent/modes/json_mode.py +480 -0
- braid_coding_agent/modes/lifecycle.py +217 -0
- braid_coding_agent/modes/print_mode.py +257 -0
- braid_coding_agent/modes/repl.py +2687 -0
- braid_coding_agent/modes/repl_commands.py +263 -0
- braid_coding_agent/modes/rpc.py +953 -0
- braid_coding_agent/modes/skill_commands.py +88 -0
- braid_coding_agent/modes/tui.py +2226 -0
- braid_coding_agent/modes/tui_control.py +90 -0
- braid_coding_agent/modes/tui_model.py +1043 -0
- braid_coding_agent/modes/tui_render.py +327 -0
- braid_coding_agent/modes/tui_rich.py +751 -0
- braid_coding_agent/modes/tui_style.py +42 -0
- braid_coding_agent/modes/wire.py +81 -0
- braid_coding_agent/netsafe.py +82 -0
- braid_coding_agent/network/__init__.py +20 -0
- braid_coding_agent/network/cache.py +77 -0
- braid_coding_agent/network/fetch.py +311 -0
- braid_coding_agent/network/html_text.py +160 -0
- braid_coding_agent/network/search.py +347 -0
- braid_coding_agent/network/settings.py +103 -0
- braid_coding_agent/network/urls.py +89 -0
- braid_coding_agent/observability/__init__.py +101 -0
- braid_coding_agent/observability/audit.py +124 -0
- braid_coding_agent/observability/collector.py +314 -0
- braid_coding_agent/observability/exporter.py +74 -0
- braid_coding_agent/observability/logging_setup.py +149 -0
- braid_coding_agent/observability/redaction.py +96 -0
- braid_coding_agent/observability/settings.py +29 -0
- braid_coding_agent/observability/spans.py +239 -0
- braid_coding_agent/permissions/__init__.py +185 -0
- braid_coding_agent/permissions/command.py +586 -0
- braid_coding_agent/permissions/engine.py +522 -0
- braid_coding_agent/permissions/evaluate.py +309 -0
- braid_coding_agent/permissions/matching.py +233 -0
- braid_coding_agent/permissions/model.py +278 -0
- braid_coding_agent/permissions/policy.py +99 -0
- braid_coding_agent/permissions/readonly.py +236 -0
- braid_coding_agent/permissions/store.py +379 -0
- braid_coding_agent/project_init.py +313 -0
- braid_coding_agent/prompt/__init__.py +98 -0
- braid_coding_agent/prompt/context_files.py +253 -0
- braid_coding_agent/prompt/project_context.py +172 -0
- braid_coding_agent/prompt/system_prompt.py +378 -0
- braid_coding_agent/questions.py +71 -0
- braid_coding_agent/render/__init__.py +56 -0
- braid_coding_agent/render/batch.py +66 -0
- braid_coding_agent/render/history.py +143 -0
- braid_coding_agent/render/stream.py +823 -0
- braid_coding_agent/render/theme.py +243 -0
- braid_coding_agent/sandbox/__init__.py +89 -0
- braid_coding_agent/sandbox/backend.py +184 -0
- braid_coding_agent/sandbox/bubblewrap.py +96 -0
- braid_coding_agent/sandbox/operations.py +301 -0
- braid_coding_agent/sandbox/policy.py +221 -0
- braid_coding_agent/sandbox/proxy.py +320 -0
- braid_coding_agent/sandbox/seatbelt.py +222 -0
- braid_coding_agent/sdk/__init__.py +31 -0
- braid_coding_agent/sdk/async_client.py +366 -0
- braid_coding_agent/sdk/client.py +386 -0
- braid_coding_agent/sdk/errors.py +52 -0
- braid_coding_agent/sdk/events.py +162 -0
- braid_coding_agent/sdk/types.py +63 -0
- braid_coding_agent/sdk/wire.py +59 -0
- braid_coding_agent/server/__init__.py +54 -0
- braid_coding_agent/server/errors.py +52 -0
- braid_coding_agent/server/http_server.py +419 -0
- braid_coding_agent/server/hub.py +530 -0
- braid_coding_agent/server/openapi.py +157 -0
- braid_coding_agent/server/registry.py +354 -0
- braid_coding_agent/server/router.py +275 -0
- braid_coding_agent/server/run.py +148 -0
- braid_coding_agent/server/schema.py +194 -0
- braid_coding_agent/server/service.py +975 -0
- braid_coding_agent/session/__init__.py +293 -0
- braid_coding_agent/session/agent_session.py +2706 -0
- braid_coding_agent/session/context_breakdown.py +302 -0
- braid_coding_agent/session/discovery.py +212 -0
- braid_coding_agent/session/entries.py +809 -0
- braid_coding_agent/session/evidence.py +295 -0
- braid_coding_agent/session/lock.py +176 -0
- braid_coding_agent/session/manager.py +1185 -0
- braid_coding_agent/session/plan.py +243 -0
- braid_coding_agent/session/plan_mode.py +423 -0
- braid_coding_agent/session/projection.py +262 -0
- braid_coding_agent/session/rewind.py +257 -0
- braid_coding_agent/session/status.py +240 -0
- braid_coding_agent/settings.py +94 -0
- braid_coding_agent/skills/__init__.py +70 -0
- braid_coding_agent/skills/loader.py +681 -0
- braid_coding_agent/startup/__init__.py +76 -0
- braid_coding_agent/startup/cache.py +72 -0
- braid_coding_agent/startup/diagnostics.py +37 -0
- braid_coding_agent/startup/monitor.py +245 -0
- braid_coding_agent/startup/phases.py +79 -0
- braid_coding_agent/startup/project.py +165 -0
- braid_coding_agent/startup/report.py +560 -0
- braid_coding_agent/startup/scheduler.py +347 -0
- braid_coding_agent/statusline.py +163 -0
- braid_coding_agent/subagents/__init__.py +22 -0
- braid_coding_agent/subagents/contract.py +75 -0
- braid_coding_agent/subagents/definitions.py +583 -0
- braid_coding_agent/subagents/registry.py +277 -0
- braid_coding_agent/subagents/runtime.py +610 -0
- braid_coding_agent/subagents/settings.py +156 -0
- braid_coding_agent/subagents/worktree.py +63 -0
- braid_coding_agent/tools/__init__.py +327 -0
- braid_coding_agent/tools/args.py +87 -0
- braid_coding_agent/tools/bash.py +359 -0
- braid_coding_agent/tools/edit.py +298 -0
- braid_coding_agent/tools/edit_diff.py +344 -0
- braid_coding_agent/tools/find.py +158 -0
- braid_coding_agent/tools/grep.py +305 -0
- braid_coding_agent/tools/ignore.py +198 -0
- braid_coding_agent/tools/ls.py +127 -0
- braid_coding_agent/tools/mutation_queue.py +90 -0
- braid_coding_agent/tools/operations.py +274 -0
- braid_coding_agent/tools/output_accumulator.py +282 -0
- braid_coding_agent/tools/output_store.py +244 -0
- braid_coding_agent/tools/path_utils.py +91 -0
- braid_coding_agent/tools/plan.py +141 -0
- braid_coding_agent/tools/prompt_notes.py +52 -0
- braid_coding_agent/tools/question.py +180 -0
- braid_coding_agent/tools/read.py +223 -0
- braid_coding_agent/tools/submit_plan.py +102 -0
- braid_coding_agent/tools/truncate.py +423 -0
- braid_coding_agent/tools/write.py +100 -0
- braid_coding_agent/untrusted.py +50 -0
- braid_coding_agent/verify/__init__.py +78 -0
- braid_coding_agent/verify/runner.py +260 -0
- braid_coding_agent/verify/settings.py +64 -0
- braid_coding_agent/verify/tool.py +143 -0
- braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
- braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
- braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
- braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
- braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
"""``edit`` 的匹配、替换与 diff 生成。
|
|
2
|
+
|
|
3
|
+
这个模块只有纯函数:给一段原文和若干
|
|
4
|
+
"旧文本 → 新文本",要么返回新内容与两份 diff,要么抛出**模型能读懂**的错误。
|
|
5
|
+
|
|
6
|
+
## 匹配为什么必须在原文上做
|
|
7
|
+
|
|
8
|
+
「所有 ``oldText`` 都对着**同一份原文**匹配」是这条工具最容易写错的地方。边改边匹配
|
|
9
|
+
会让第二段的偏移量建立在第一段替换后的文本上:两段相邻、第二段位于第一段之后时,
|
|
10
|
+
结果会错位;两段重叠时,重叠部分被改两次。先把全部匹配位置算出来、
|
|
11
|
+
按位置排序、检查重叠,最后**从后往前**替换——倒序替换时前面的偏移量不受影响。
|
|
12
|
+
|
|
13
|
+
## 只做精确匹配
|
|
14
|
+
|
|
15
|
+
模糊匹配会写入模型没有逐字给出的内容,而 ``details.diff`` 又是
|
|
16
|
+
给人看的"我要改什么",两者一旦不一致,确认就失去意义。模型写错空白时应当看到
|
|
17
|
+
"没找到,必须逐字匹配",把原文重新读一遍。
|
|
18
|
+
|
|
19
|
+
## 换行与 BOM
|
|
20
|
+
|
|
21
|
+
匹配前统一转成 LF,写回时按原文件的风格还原:一个 CRLF 文件不能因为一次编辑变成
|
|
22
|
+
混合换行。BOM 在匹配前剥掉、写回时补上——模型看不到 BOM,``oldText`` 里当然也没有。
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import difflib
|
|
28
|
+
from collections.abc import Sequence
|
|
29
|
+
from dataclasses import dataclass
|
|
30
|
+
from itertools import pairwise
|
|
31
|
+
from typing import Final, Literal
|
|
32
|
+
|
|
33
|
+
#: UTF-8 BOM。它在文本里不可见,但会让 `oldText` 的首行匹配失败。
|
|
34
|
+
BOM: Final[str] = "\ufeff"
|
|
35
|
+
|
|
36
|
+
CONTEXT_LINES: Final[int] = 4
|
|
37
|
+
|
|
38
|
+
type LineEnding = Literal["\r\n", "\n"]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def split_bom(content: str) -> tuple[str, str]:
|
|
42
|
+
"""拆出 ``(BOM, 正文)``;没有 BOM 时返回 ``("", content)``。"""
|
|
43
|
+
if content.startswith(BOM):
|
|
44
|
+
return BOM, content[len(BOM) :]
|
|
45
|
+
return "", content
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def detect_line_ending(content: str) -> LineEnding:
|
|
49
|
+
"""看第一个换行是 CRLF 还是 LF。没有换行时按 LF 处理。"""
|
|
50
|
+
crlf = content.find("\r\n")
|
|
51
|
+
lf = content.find("\n")
|
|
52
|
+
if lf == -1 or crlf == -1:
|
|
53
|
+
return "\n"
|
|
54
|
+
return "\r\n" if crlf < lf else "\n"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def normalize_to_lf(text: str) -> str:
|
|
58
|
+
"""CRLF 与孤立 CR 都变成 LF。"""
|
|
59
|
+
return text.replace("\r\n", "\n").replace("\r", "\n")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def restore_line_endings(text: str, ending: LineEnding) -> str:
|
|
63
|
+
"""把 LF 还原成原文件的换行风格。"""
|
|
64
|
+
return text.replace("\n", "\r\n") if ending == "\r\n" else text
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(slots=True, frozen=True)
|
|
68
|
+
class Edit:
|
|
69
|
+
"""一段精确替换。``old_text`` 必须在原文中唯一出现。"""
|
|
70
|
+
|
|
71
|
+
old_text: str
|
|
72
|
+
new_text: str
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(slots=True, frozen=True)
|
|
76
|
+
class AppliedEdits:
|
|
77
|
+
"""一次 ``edit`` 的完整产出:改前、改后、第一处改动的行号、两份 diff。"""
|
|
78
|
+
|
|
79
|
+
base_content: str
|
|
80
|
+
new_content: str
|
|
81
|
+
first_changed_line: int | None
|
|
82
|
+
diff: str
|
|
83
|
+
patch: str
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class EditError(ValueError):
|
|
87
|
+
"""编辑无法应用。消息会原样进工具结果,因此必须说清"哪一段、为什么"。"""
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _not_found(path: str, index: int, total: int) -> EditError:
|
|
91
|
+
if total == 1:
|
|
92
|
+
return EditError(
|
|
93
|
+
f"Could not find the exact text in {path}. "
|
|
94
|
+
"The old text must match exactly including all whitespace and newlines."
|
|
95
|
+
)
|
|
96
|
+
return EditError(
|
|
97
|
+
f"Could not find edits[{index}] in {path}. "
|
|
98
|
+
"The oldText must match exactly including all whitespace and newlines."
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _not_unique(path: str, index: int, total: int, occurrences: int) -> EditError:
|
|
103
|
+
if total == 1:
|
|
104
|
+
return EditError(
|
|
105
|
+
f"Found {occurrences} occurrences of the text in {path}. "
|
|
106
|
+
"The text must be unique. Please provide more context to make it unique."
|
|
107
|
+
)
|
|
108
|
+
return EditError(
|
|
109
|
+
f"Found {occurrences} occurrences of edits[{index}] in {path}. "
|
|
110
|
+
"Each oldText must be unique. Please provide more context to make it unique."
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _empty_old_text(path: str, index: int, total: int) -> EditError:
|
|
115
|
+
if total == 1:
|
|
116
|
+
return EditError(f"oldText must not be empty in {path}.")
|
|
117
|
+
return EditError(f"edits[{index}].oldText must not be empty in {path}.")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _no_change(path: str, total: int) -> EditError:
|
|
121
|
+
if total == 1:
|
|
122
|
+
return EditError(
|
|
123
|
+
f"No changes made to {path}. The replacement produced identical content. "
|
|
124
|
+
"This might indicate an issue with special characters or the text not existing "
|
|
125
|
+
"as expected."
|
|
126
|
+
)
|
|
127
|
+
return EditError(f"No changes made to {path}. The replacements produced identical content.")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def apply_edits(
|
|
131
|
+
normalized_content: str,
|
|
132
|
+
edits: Sequence[Edit],
|
|
133
|
+
path: str,
|
|
134
|
+
*,
|
|
135
|
+
context_lines: int = CONTEXT_LINES,
|
|
136
|
+
) -> AppliedEdits:
|
|
137
|
+
"""把 ``edits`` 应用到 LF 归一化后的原文上。
|
|
138
|
+
|
|
139
|
+
:param normalized_content: 已转成 LF 的原文(BOM 已剥掉)。
|
|
140
|
+
:param path: 只用于错误消息与 patch 头,不做 I/O。
|
|
141
|
+
:raises EditError: 空 ``old_text``、找不到、不唯一、重叠、替换后无变化。
|
|
142
|
+
"""
|
|
143
|
+
if not edits:
|
|
144
|
+
raise EditError("Edit tool input is invalid. edits must contain at least one replacement.")
|
|
145
|
+
|
|
146
|
+
normalized = [Edit(normalize_to_lf(e.old_text), normalize_to_lf(e.new_text)) for e in edits]
|
|
147
|
+
total = len(normalized)
|
|
148
|
+
for index, edit in enumerate(normalized):
|
|
149
|
+
if not edit.old_text:
|
|
150
|
+
raise _empty_old_text(path, index, total)
|
|
151
|
+
|
|
152
|
+
matches: list[tuple[int, int, str, int]] = []
|
|
153
|
+
for index, edit in enumerate(normalized):
|
|
154
|
+
occurrences = normalized_content.count(edit.old_text)
|
|
155
|
+
if occurrences == 0:
|
|
156
|
+
raise _not_found(path, index, total)
|
|
157
|
+
if occurrences > 1:
|
|
158
|
+
raise _not_unique(path, index, total, occurrences)
|
|
159
|
+
start = normalized_content.index(edit.old_text)
|
|
160
|
+
matches.append((start, len(edit.old_text), edit.new_text, index))
|
|
161
|
+
|
|
162
|
+
matches.sort(key=lambda item: item[0])
|
|
163
|
+
for previous, current in pairwise(matches):
|
|
164
|
+
if previous[0] + previous[1] > current[0]:
|
|
165
|
+
raise EditError(
|
|
166
|
+
f"edits[{previous[3]}] and edits[{current[3]}] overlap in {path}. "
|
|
167
|
+
"Merge them into one edit or target disjoint regions."
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
new_content = normalized_content
|
|
171
|
+
# 倒序替换:每次替换都不影响尚未处理的那几段的下标。
|
|
172
|
+
for start, length, replacement, _ in reversed(matches):
|
|
173
|
+
new_content = new_content[:start] + replacement + new_content[start + length :]
|
|
174
|
+
|
|
175
|
+
if new_content == normalized_content:
|
|
176
|
+
raise _no_change(path, total)
|
|
177
|
+
|
|
178
|
+
diff, first_changed_line = generate_diff_string(normalized_content, new_content, context_lines)
|
|
179
|
+
return AppliedEdits(
|
|
180
|
+
base_content=normalized_content,
|
|
181
|
+
new_content=new_content,
|
|
182
|
+
first_changed_line=first_changed_line,
|
|
183
|
+
diff=diff,
|
|
184
|
+
patch=generate_unified_patch(path, normalized_content, new_content, context_lines),
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
type _PartTag = Literal["equal", "insert", "delete"]
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@dataclass(slots=True, frozen=True)
|
|
192
|
+
class _Part:
|
|
193
|
+
"""diff 的一段:连续的相同行、新增行或删除行。"""
|
|
194
|
+
|
|
195
|
+
tag: _PartTag
|
|
196
|
+
lines: list[str]
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _diff_parts(old_content: str, new_content: str) -> list[_Part]:
|
|
200
|
+
"""按行做 LCS 差分,返回等价的"分段"序列。
|
|
201
|
+
|
|
202
|
+
``replace`` 被拆成"先删后增",与 ``diff`` 包的输出形状一致:阅读 diff 时,
|
|
203
|
+
同一段里新旧内容并排出现。
|
|
204
|
+
"""
|
|
205
|
+
old_lines = old_content.split("\n")
|
|
206
|
+
new_lines = new_content.split("\n")
|
|
207
|
+
matcher = difflib.SequenceMatcher(None, old_lines, new_lines, autojunk=False)
|
|
208
|
+
parts: list[_Part] = []
|
|
209
|
+
for tag, old_start, old_end, new_start, new_end in matcher.get_opcodes():
|
|
210
|
+
if tag == "equal":
|
|
211
|
+
parts.append(_Part("equal", old_lines[old_start:old_end]))
|
|
212
|
+
elif tag == "delete":
|
|
213
|
+
parts.append(_Part("delete", old_lines[old_start:old_end]))
|
|
214
|
+
elif tag == "insert":
|
|
215
|
+
parts.append(_Part("insert", new_lines[new_start:new_end]))
|
|
216
|
+
else:
|
|
217
|
+
parts.append(_Part("delete", old_lines[old_start:old_end]))
|
|
218
|
+
parts.append(_Part("insert", new_lines[new_start:new_end]))
|
|
219
|
+
return parts
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def generate_diff_string(
|
|
223
|
+
old_content: str, new_content: str, context_lines: int = CONTEXT_LINES
|
|
224
|
+
) -> tuple[str, int | None]:
|
|
225
|
+
"""生成带行号的展示型 diff,返回 ``(文本, 第一处改动的行号)``。
|
|
226
|
+
|
|
227
|
+
只显示变化附近 ``context_lines`` 行;两段变化之间的空白折叠成一行 ``...``。
|
|
228
|
+
行号是新旧两套:删除行用旧行号,新增行与上下文行用新行号——与 ``git diff``
|
|
229
|
+
的读法一致。``first_changed_line`` 是新文件里的行号,供 UI 跳转。
|
|
230
|
+
"""
|
|
231
|
+
parts = _diff_parts(old_content, new_content)
|
|
232
|
+
old_total = len(old_content.split("\n"))
|
|
233
|
+
new_total = len(new_content.split("\n"))
|
|
234
|
+
width = len(str(max(old_total, new_total)))
|
|
235
|
+
|
|
236
|
+
output: list[str] = []
|
|
237
|
+
old_line = 1
|
|
238
|
+
new_line = 1
|
|
239
|
+
last_was_change = False
|
|
240
|
+
first_changed: int | None = None
|
|
241
|
+
|
|
242
|
+
for index, part in enumerate(parts):
|
|
243
|
+
if part.tag != "equal":
|
|
244
|
+
if first_changed is None:
|
|
245
|
+
first_changed = new_line
|
|
246
|
+
for line in part.lines:
|
|
247
|
+
if part.tag == "insert":
|
|
248
|
+
output.append(f"+{new_line:>{width}} {line}")
|
|
249
|
+
new_line += 1
|
|
250
|
+
else:
|
|
251
|
+
output.append(f"-{old_line:>{width}} {line}")
|
|
252
|
+
old_line += 1
|
|
253
|
+
last_was_change = True
|
|
254
|
+
continue
|
|
255
|
+
|
|
256
|
+
next_is_change = index < len(parts) - 1 and parts[index + 1].tag != "equal"
|
|
257
|
+
lines = part.lines
|
|
258
|
+
if last_was_change and next_is_change:
|
|
259
|
+
if len(lines) <= context_lines * 2:
|
|
260
|
+
for line in lines:
|
|
261
|
+
output.append(f" {old_line:>{width}} {line}")
|
|
262
|
+
old_line += 1
|
|
263
|
+
new_line += 1
|
|
264
|
+
else:
|
|
265
|
+
for line in lines[:context_lines]:
|
|
266
|
+
output.append(f" {old_line:>{width}} {line}")
|
|
267
|
+
old_line += 1
|
|
268
|
+
new_line += 1
|
|
269
|
+
output.append(f" {'':>{width}} ...")
|
|
270
|
+
skipped = len(lines) - context_lines * 2
|
|
271
|
+
old_line += skipped
|
|
272
|
+
new_line += skipped
|
|
273
|
+
for line in lines[len(lines) - context_lines :]:
|
|
274
|
+
output.append(f" {old_line:>{width}} {line}")
|
|
275
|
+
old_line += 1
|
|
276
|
+
new_line += 1
|
|
277
|
+
elif last_was_change:
|
|
278
|
+
shown = lines[:context_lines]
|
|
279
|
+
for line in shown:
|
|
280
|
+
output.append(f" {old_line:>{width}} {line}")
|
|
281
|
+
old_line += 1
|
|
282
|
+
new_line += 1
|
|
283
|
+
skipped = len(lines) - len(shown)
|
|
284
|
+
if skipped > 0:
|
|
285
|
+
output.append(f" {'':>{width}} ...")
|
|
286
|
+
old_line += skipped
|
|
287
|
+
new_line += skipped
|
|
288
|
+
elif next_is_change:
|
|
289
|
+
skipped = max(0, len(lines) - context_lines)
|
|
290
|
+
if skipped > 0:
|
|
291
|
+
output.append(f" {'':>{width}} ...")
|
|
292
|
+
old_line += skipped
|
|
293
|
+
new_line += skipped
|
|
294
|
+
for line in lines[skipped:]:
|
|
295
|
+
output.append(f" {old_line:>{width}} {line}")
|
|
296
|
+
old_line += 1
|
|
297
|
+
new_line += 1
|
|
298
|
+
else:
|
|
299
|
+
old_line += len(lines)
|
|
300
|
+
new_line += len(lines)
|
|
301
|
+
last_was_change = False
|
|
302
|
+
|
|
303
|
+
return "\n".join(output), first_changed
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def generate_unified_patch(
|
|
307
|
+
path: str,
|
|
308
|
+
old_content: str,
|
|
309
|
+
new_content: str,
|
|
310
|
+
context_lines: int = CONTEXT_LINES,
|
|
311
|
+
) -> str:
|
|
312
|
+
"""标准 unified diff(``--- / +++ / @@``),可以交给 ``git apply`` 或 ``patch``。
|
|
313
|
+
|
|
314
|
+
只用 ``difflib``:格式是 RFC 级别的常识,自己拼字符串迟早会在"文件没有结尾换行"
|
|
315
|
+
这类细节上出错。
|
|
316
|
+
"""
|
|
317
|
+
old_lines = old_content.split("\n")
|
|
318
|
+
new_lines = new_content.split("\n")
|
|
319
|
+
patch_lines = difflib.unified_diff(
|
|
320
|
+
old_lines,
|
|
321
|
+
new_lines,
|
|
322
|
+
fromfile=path,
|
|
323
|
+
tofile=path,
|
|
324
|
+
n=context_lines,
|
|
325
|
+
lineterm="",
|
|
326
|
+
)
|
|
327
|
+
return "\n".join(patch_lines)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
__all__ = [
|
|
331
|
+
"BOM",
|
|
332
|
+
"CONTEXT_LINES",
|
|
333
|
+
"AppliedEdits",
|
|
334
|
+
"Edit",
|
|
335
|
+
"EditError",
|
|
336
|
+
"LineEnding",
|
|
337
|
+
"apply_edits",
|
|
338
|
+
"detect_line_ending",
|
|
339
|
+
"generate_diff_string",
|
|
340
|
+
"generate_unified_patch",
|
|
341
|
+
"normalize_to_lf",
|
|
342
|
+
"restore_line_endings",
|
|
343
|
+
"split_bom",
|
|
344
|
+
]
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""``find``:按 glob 模式找文件。
|
|
2
|
+
|
|
3
|
+
输出是**相对搜索目录**的
|
|
4
|
+
路径:模型拿到 ``src/app.ts`` 就能直接把它喂给 ``read``/``edit``,而绝对路径既长
|
|
5
|
+
又在换机器后失效。
|
|
6
|
+
|
|
7
|
+
结果条数默认上限 1000:一次列出十万个文件对模型没有价值,反而挤掉它真正需要的上下文。
|
|
8
|
+
到上限时给出 ``Use limit=2000`` 的继续方式。
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
from braid_agent.tools import AgentTool, AgentToolResult, ToolUpdateSink
|
|
16
|
+
from braid_ai.cancel import CancelToken
|
|
17
|
+
from braid_ai.types import JsonValue, TextContent
|
|
18
|
+
from braid_coding_agent.tools.args import optional_integer_arg, optional_string_arg, string_arg
|
|
19
|
+
from braid_coding_agent.tools.ignore import iter_files, matches_glob
|
|
20
|
+
from braid_coding_agent.tools.operations import (
|
|
21
|
+
FileOperations,
|
|
22
|
+
LocalFileOperations,
|
|
23
|
+
ensure_not_cancelled,
|
|
24
|
+
)
|
|
25
|
+
from braid_coding_agent.tools.path_utils import resolve_to_cwd, to_posix
|
|
26
|
+
from braid_coding_agent.tools.truncate import DEFAULT_MAX_BYTES, format_size, truncate_head
|
|
27
|
+
|
|
28
|
+
DEFAULT_LIMIT = 1000
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(slots=True, frozen=True)
|
|
32
|
+
class FindOutcome:
|
|
33
|
+
"""一次按 glob 找文件的结果。``paths`` 相对搜索目录。"""
|
|
34
|
+
|
|
35
|
+
paths: tuple[str, ...]
|
|
36
|
+
limit_reached: bool
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
async def find_paths(
|
|
40
|
+
operations: FileOperations,
|
|
41
|
+
search_path: str,
|
|
42
|
+
*,
|
|
43
|
+
pattern: str,
|
|
44
|
+
limit: int = DEFAULT_LIMIT,
|
|
45
|
+
signal: CancelToken | None = None,
|
|
46
|
+
) -> FindOutcome:
|
|
47
|
+
"""在 ``search_path`` 下按 glob 找文件。``find`` 工具与 ``GET /files/find`` 共用。"""
|
|
48
|
+
results: list[str] = []
|
|
49
|
+
limit_reached = False
|
|
50
|
+
async for _absolute, relative in iter_files(operations, search_path):
|
|
51
|
+
ensure_not_cancelled(signal)
|
|
52
|
+
if not matches_glob(relative, pattern):
|
|
53
|
+
continue
|
|
54
|
+
results.append(to_posix(relative))
|
|
55
|
+
if len(results) >= limit:
|
|
56
|
+
limit_reached = True
|
|
57
|
+
break
|
|
58
|
+
return FindOutcome(paths=tuple(results), limit_reached=limit_reached)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
FIND_PARAMETERS: dict[str, JsonValue] = {
|
|
62
|
+
"type": "object",
|
|
63
|
+
"properties": {
|
|
64
|
+
"pattern": {
|
|
65
|
+
"type": "string",
|
|
66
|
+
"description": (
|
|
67
|
+
"Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'"
|
|
68
|
+
),
|
|
69
|
+
},
|
|
70
|
+
"path": {
|
|
71
|
+
"type": "string",
|
|
72
|
+
"description": "Directory to search in (default: current directory)",
|
|
73
|
+
},
|
|
74
|
+
"limit": {
|
|
75
|
+
"type": "integer",
|
|
76
|
+
"description": f"Maximum number of results (default: {DEFAULT_LIMIT})",
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
"required": ["pattern"],
|
|
80
|
+
"additionalProperties": False,
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def create_find_tool(
|
|
85
|
+
cwd: str,
|
|
86
|
+
*,
|
|
87
|
+
operations: FileOperations | None = None,
|
|
88
|
+
max_bytes: int = DEFAULT_MAX_BYTES,
|
|
89
|
+
) -> AgentTool:
|
|
90
|
+
"""构造 ``find`` 工具。``cwd`` 是相对路径的基准目录。"""
|
|
91
|
+
ops: FileOperations = operations if operations is not None else LocalFileOperations()
|
|
92
|
+
|
|
93
|
+
async def execute(
|
|
94
|
+
tool_call_id: str,
|
|
95
|
+
args: dict[str, JsonValue],
|
|
96
|
+
signal: CancelToken | None,
|
|
97
|
+
on_update: ToolUpdateSink,
|
|
98
|
+
) -> AgentToolResult:
|
|
99
|
+
pattern = string_arg(args, "pattern")
|
|
100
|
+
search_dir = optional_string_arg(args, "path")
|
|
101
|
+
limit = max(1, optional_integer_arg(args, "limit") or DEFAULT_LIMIT)
|
|
102
|
+
|
|
103
|
+
search_path = resolve_to_cwd(search_dir or ".", cwd)
|
|
104
|
+
if not await ops.exists(search_path):
|
|
105
|
+
raise ValueError(f"Path not found: {search_path}")
|
|
106
|
+
|
|
107
|
+
outcome = await find_paths(ops, search_path, pattern=pattern, limit=limit, signal=signal)
|
|
108
|
+
|
|
109
|
+
if not outcome.paths:
|
|
110
|
+
return AgentToolResult(content=[TextContent(text="No files found matching pattern")])
|
|
111
|
+
|
|
112
|
+
results = list(outcome.paths)
|
|
113
|
+
raw_output = "\n".join(results)
|
|
114
|
+
truncation = truncate_head(raw_output, max_lines=len(results), max_bytes=max_bytes)
|
|
115
|
+
details: dict[str, JsonValue] = {}
|
|
116
|
+
notices: list[str] = []
|
|
117
|
+
if outcome.limit_reached:
|
|
118
|
+
notices.append(
|
|
119
|
+
f"{limit} results limit reached. Use limit={limit * 2} for more, or refine pattern"
|
|
120
|
+
)
|
|
121
|
+
details["result_limit_reached"] = limit
|
|
122
|
+
if truncation.truncated:
|
|
123
|
+
notices.append(f"{format_size(max_bytes)} limit reached")
|
|
124
|
+
details["truncation"] = truncation.to_details()
|
|
125
|
+
output = truncation.content
|
|
126
|
+
if notices:
|
|
127
|
+
output += f"\n\n[{'. '.join(notices)}]"
|
|
128
|
+
return AgentToolResult(
|
|
129
|
+
content=[TextContent(text=output)], details=details if details else None
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
return AgentTool(
|
|
133
|
+
name="find",
|
|
134
|
+
label="find",
|
|
135
|
+
description=(
|
|
136
|
+
"Search for files by glob pattern. Returns matching file paths relative to the "
|
|
137
|
+
f"search directory. Respects .gitignore. Output is truncated to {DEFAULT_LIMIT} "
|
|
138
|
+
f"results or {max_bytes // 1024}KB (whichever is hit first)."
|
|
139
|
+
),
|
|
140
|
+
parameters=FIND_PARAMETERS,
|
|
141
|
+
execute=execute,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
PROMPT_SNIPPET = "Find files by glob pattern (respects .gitignore)"
|
|
146
|
+
|
|
147
|
+
PROMPT_GUIDELINES: tuple[str, ...] = ()
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
__all__ = [
|
|
151
|
+
"DEFAULT_LIMIT",
|
|
152
|
+
"FIND_PARAMETERS",
|
|
153
|
+
"PROMPT_GUIDELINES",
|
|
154
|
+
"PROMPT_SNIPPET",
|
|
155
|
+
"FindOutcome",
|
|
156
|
+
"create_find_tool",
|
|
157
|
+
"find_paths",
|
|
158
|
+
]
|