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,305 @@
|
|
|
1
|
+
"""``grep``:按正则或字面量搜索文件内容。
|
|
2
|
+
|
|
3
|
+
Python 侧自己遍历 + 匹配(理由见 :mod:`braid_coding_agent.tools.ignore`)。
|
|
4
|
+
有三处必须显式处理:
|
|
5
|
+
|
|
6
|
+
1. **二进制文件**:``rg`` 遇到 NUL 字节就跳过整个文件。这里读前 8KB 检查 NUL,
|
|
7
|
+
命中即跳过——否则一段编译产物会被当成"几千行都匹配"。
|
|
8
|
+
2. **长行**:模型需要的是一行里的定位片段,不是 50 万字符的压缩产物。超过
|
|
9
|
+
``GREP_MAX_LINE_LENGTH`` 的行截断并标记,结果里说明"要看全文用 read"。
|
|
10
|
+
3. **上限**:匹配条数(默认 100)与字节数同时生效。条数到上限时给出
|
|
11
|
+
``Use limit=N`` 的继续方式,省掉模型猜上限的一步。
|
|
12
|
+
|
|
13
|
+
输出格式沿用 ``rg`` 的 ``path:line: text``:模型对这种形状最熟,且上下文行用
|
|
14
|
+
``path-line- text`` 区分,能一眼看出哪些不是命中行。
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import re
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
|
|
22
|
+
from braid_agent.tools import AgentTool, AgentToolResult, ToolUpdateSink
|
|
23
|
+
from braid_ai.cancel import CancelToken
|
|
24
|
+
from braid_ai.types import JsonValue, TextContent
|
|
25
|
+
from braid_coding_agent.tools.args import (
|
|
26
|
+
optional_bool_arg,
|
|
27
|
+
optional_integer_arg,
|
|
28
|
+
optional_string_arg,
|
|
29
|
+
string_arg,
|
|
30
|
+
)
|
|
31
|
+
from braid_coding_agent.tools.ignore import iter_files, matches_glob
|
|
32
|
+
from braid_coding_agent.tools.operations import (
|
|
33
|
+
FileOperations,
|
|
34
|
+
LocalFileOperations,
|
|
35
|
+
ensure_not_cancelled,
|
|
36
|
+
)
|
|
37
|
+
from braid_coding_agent.tools.path_utils import resolve_to_cwd, to_posix
|
|
38
|
+
from braid_coding_agent.tools.truncate import (
|
|
39
|
+
DEFAULT_MAX_BYTES,
|
|
40
|
+
GREP_MAX_LINE_LENGTH,
|
|
41
|
+
format_size,
|
|
42
|
+
truncate_head,
|
|
43
|
+
truncate_line,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
DEFAULT_LIMIT = 100
|
|
47
|
+
|
|
48
|
+
#: 判断"是不是二进制文件"时检查的字节数。NUL 出现在前 8KB 就足够确定。
|
|
49
|
+
_BINARY_SNIFF_BYTES = 8192
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(slots=True, frozen=True)
|
|
53
|
+
class GrepHit:
|
|
54
|
+
"""一条命中行(或一条上下文行)。``path`` 相对搜索目录。"""
|
|
55
|
+
|
|
56
|
+
path: str
|
|
57
|
+
line: int
|
|
58
|
+
text: str
|
|
59
|
+
#: 这一行是命中行前后的上下文,不是命中本身。
|
|
60
|
+
context: bool = False
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(slots=True, frozen=True)
|
|
64
|
+
class GrepOutcome:
|
|
65
|
+
"""一次内容搜索的结果。工具据此拼文本,HTTP 接口据此返回结构化列表。"""
|
|
66
|
+
|
|
67
|
+
hits: tuple[GrepHit, ...]
|
|
68
|
+
matches: int
|
|
69
|
+
limit_reached: bool
|
|
70
|
+
lines_truncated: bool
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
async def search_contents(
|
|
74
|
+
operations: FileOperations,
|
|
75
|
+
search_path: str,
|
|
76
|
+
*,
|
|
77
|
+
pattern: str,
|
|
78
|
+
glob: str | None = None,
|
|
79
|
+
ignore_case: bool = False,
|
|
80
|
+
literal: bool = False,
|
|
81
|
+
context: int = 0,
|
|
82
|
+
limit: int = DEFAULT_LIMIT,
|
|
83
|
+
signal: CancelToken | None = None,
|
|
84
|
+
) -> GrepOutcome:
|
|
85
|
+
"""在 ``search_path`` 下按行搜索,返回命中与上下文行。
|
|
86
|
+
|
|
87
|
+
``grep`` 工具与 HTTP 的 ``GET /files/search`` 共用它:两个入口对"什么算命中、
|
|
88
|
+
跳过哪些文件、长行怎么截"必须给出同一个答案。
|
|
89
|
+
"""
|
|
90
|
+
matcher = _compile(pattern, literal=literal, ignore_case=ignore_case)
|
|
91
|
+
hits: list[GrepHit] = []
|
|
92
|
+
matched = 0
|
|
93
|
+
limit_reached = False
|
|
94
|
+
lines_truncated = False
|
|
95
|
+
async for absolute, relative in iter_files(operations, search_path):
|
|
96
|
+
if glob is not None and not matches_glob(relative, glob):
|
|
97
|
+
continue
|
|
98
|
+
ensure_not_cancelled(signal)
|
|
99
|
+
raw = await operations.read_bytes(absolute)
|
|
100
|
+
if b"\0" in raw[:_BINARY_SNIFF_BYTES]:
|
|
101
|
+
continue
|
|
102
|
+
text = raw.decode("utf-8", errors="replace").replace("\r\n", "\n").replace("\r", "\n")
|
|
103
|
+
lines = text.split("\n")
|
|
104
|
+
for index, line in enumerate(lines):
|
|
105
|
+
if matcher.search(line) is None:
|
|
106
|
+
continue
|
|
107
|
+
matched += 1
|
|
108
|
+
if context > 0:
|
|
109
|
+
block, truncated_any = _context_block(
|
|
110
|
+
lines, index, relative=relative, context=context
|
|
111
|
+
)
|
|
112
|
+
hits.extend(block)
|
|
113
|
+
lines_truncated = lines_truncated or truncated_any
|
|
114
|
+
else:
|
|
115
|
+
body, truncated = truncate_line(line)
|
|
116
|
+
lines_truncated = lines_truncated or truncated
|
|
117
|
+
hits.append(GrepHit(path=to_posix(relative), line=index + 1, text=body))
|
|
118
|
+
if matched >= limit:
|
|
119
|
+
limit_reached = True
|
|
120
|
+
break
|
|
121
|
+
if limit_reached:
|
|
122
|
+
break
|
|
123
|
+
return GrepOutcome(
|
|
124
|
+
hits=tuple(hits),
|
|
125
|
+
matches=matched,
|
|
126
|
+
limit_reached=limit_reached,
|
|
127
|
+
lines_truncated=lines_truncated,
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def format_hits(hits: tuple[GrepHit, ...]) -> list[str]:
|
|
132
|
+
"""命中 → ``path:line: text`` 行。上下文行用 ``path-line- text`` 区分。"""
|
|
133
|
+
formatted: list[str] = []
|
|
134
|
+
for hit in hits:
|
|
135
|
+
separator = "-" if hit.context else ":"
|
|
136
|
+
formatted.append(f"{hit.path}{separator}{hit.line}{separator} {hit.text}")
|
|
137
|
+
return formatted
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
GREP_PARAMETERS: dict[str, JsonValue] = {
|
|
141
|
+
"type": "object",
|
|
142
|
+
"properties": {
|
|
143
|
+
"pattern": {
|
|
144
|
+
"type": "string",
|
|
145
|
+
"description": "Search pattern (regex or literal string)",
|
|
146
|
+
},
|
|
147
|
+
"path": {
|
|
148
|
+
"type": "string",
|
|
149
|
+
"description": "Directory or file to search (default: current directory)",
|
|
150
|
+
},
|
|
151
|
+
"glob": {
|
|
152
|
+
"type": "string",
|
|
153
|
+
"description": "Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'",
|
|
154
|
+
},
|
|
155
|
+
"ignoreCase": {
|
|
156
|
+
"type": "boolean",
|
|
157
|
+
"description": "Case-insensitive search (default: false)",
|
|
158
|
+
},
|
|
159
|
+
"literal": {
|
|
160
|
+
"type": "boolean",
|
|
161
|
+
"description": "Treat pattern as literal string instead of regex (default: false)",
|
|
162
|
+
},
|
|
163
|
+
"context": {
|
|
164
|
+
"type": "integer",
|
|
165
|
+
"description": "Number of lines to show before and after each match (default: 0)",
|
|
166
|
+
},
|
|
167
|
+
"limit": {
|
|
168
|
+
"type": "integer",
|
|
169
|
+
"description": f"Maximum number of matches to return (default: {DEFAULT_LIMIT})",
|
|
170
|
+
},
|
|
171
|
+
},
|
|
172
|
+
"required": ["pattern"],
|
|
173
|
+
"additionalProperties": False,
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def create_grep_tool(
|
|
178
|
+
cwd: str,
|
|
179
|
+
*,
|
|
180
|
+
operations: FileOperations | None = None,
|
|
181
|
+
max_bytes: int = DEFAULT_MAX_BYTES,
|
|
182
|
+
) -> AgentTool:
|
|
183
|
+
"""构造 ``grep`` 工具。``cwd`` 是相对路径的基准目录。"""
|
|
184
|
+
ops: FileOperations = operations if operations is not None else LocalFileOperations()
|
|
185
|
+
|
|
186
|
+
async def execute(
|
|
187
|
+
tool_call_id: str,
|
|
188
|
+
args: dict[str, JsonValue],
|
|
189
|
+
signal: CancelToken | None,
|
|
190
|
+
on_update: ToolUpdateSink,
|
|
191
|
+
) -> AgentToolResult:
|
|
192
|
+
pattern = string_arg(args, "pattern")
|
|
193
|
+
search_dir = optional_string_arg(args, "path")
|
|
194
|
+
glob = optional_string_arg(args, "glob")
|
|
195
|
+
ignore_case = optional_bool_arg(args, "ignoreCase") or False
|
|
196
|
+
literal = optional_bool_arg(args, "literal") or False
|
|
197
|
+
context = optional_integer_arg(args, "context") or 0
|
|
198
|
+
limit = max(1, optional_integer_arg(args, "limit") or DEFAULT_LIMIT)
|
|
199
|
+
|
|
200
|
+
search_path = resolve_to_cwd(search_dir or ".", cwd)
|
|
201
|
+
if not await ops.exists(search_path):
|
|
202
|
+
raise ValueError(f"Path not found: {search_path}")
|
|
203
|
+
outcome = await search_contents(
|
|
204
|
+
ops,
|
|
205
|
+
search_path,
|
|
206
|
+
pattern=pattern,
|
|
207
|
+
glob=glob,
|
|
208
|
+
ignore_case=ignore_case,
|
|
209
|
+
literal=literal,
|
|
210
|
+
context=context,
|
|
211
|
+
limit=limit,
|
|
212
|
+
signal=signal,
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
if outcome.matches == 0:
|
|
216
|
+
return AgentToolResult(content=[TextContent(text="No matches found")])
|
|
217
|
+
|
|
218
|
+
collected = format_hits(outcome.hits)
|
|
219
|
+
output = "\n".join(collected)
|
|
220
|
+
truncation = truncate_head(output, max_lines=len(collected), max_bytes=max_bytes)
|
|
221
|
+
details: dict[str, JsonValue] = {}
|
|
222
|
+
notices: list[str] = []
|
|
223
|
+
if outcome.limit_reached:
|
|
224
|
+
notices.append(
|
|
225
|
+
f"{limit} matches limit reached. Use limit={limit * 2} for more, or refine pattern"
|
|
226
|
+
)
|
|
227
|
+
details["match_limit_reached"] = limit
|
|
228
|
+
if truncation.truncated:
|
|
229
|
+
notices.append(f"{format_size(max_bytes)} limit reached")
|
|
230
|
+
details["truncation"] = truncation.to_details()
|
|
231
|
+
if outcome.lines_truncated:
|
|
232
|
+
notices.append(
|
|
233
|
+
f"Some lines truncated to {GREP_MAX_LINE_LENGTH} chars. "
|
|
234
|
+
"Use read tool to see full lines"
|
|
235
|
+
)
|
|
236
|
+
details["lines_truncated"] = True
|
|
237
|
+
body = truncation.content
|
|
238
|
+
if notices:
|
|
239
|
+
body += f"\n\n[{'. '.join(notices)}]"
|
|
240
|
+
return AgentToolResult(
|
|
241
|
+
content=[TextContent(text=body)], details=details if details else None
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
return AgentTool(
|
|
245
|
+
name="grep",
|
|
246
|
+
label="grep",
|
|
247
|
+
description=(
|
|
248
|
+
"Search file contents for a pattern. Returns matching lines with file paths and "
|
|
249
|
+
f"line numbers. Respects .gitignore. Output is truncated to {DEFAULT_LIMIT} matches "
|
|
250
|
+
f"or {max_bytes // 1024}KB (whichever is hit first). Long lines are truncated to "
|
|
251
|
+
f"{GREP_MAX_LINE_LENGTH} chars."
|
|
252
|
+
),
|
|
253
|
+
parameters=GREP_PARAMETERS,
|
|
254
|
+
execute=execute,
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _compile(pattern: str, *, literal: bool, ignore_case: bool) -> re.Pattern[str]:
|
|
259
|
+
"""编译搜索模式。非法正则被包成 ``Invalid pattern: …``,把 ``re.error`` 的原话留在里面。"""
|
|
260
|
+
source = re.escape(pattern) if literal else pattern
|
|
261
|
+
flags = re.IGNORECASE if ignore_case else 0
|
|
262
|
+
try:
|
|
263
|
+
return re.compile(source, flags)
|
|
264
|
+
except re.error as error:
|
|
265
|
+
raise ValueError(f"Invalid pattern: {error}") from error
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _context_block(
|
|
269
|
+
lines: list[str], index: int, *, relative: str, context: int
|
|
270
|
+
) -> tuple[list[GrepHit], bool]:
|
|
271
|
+
"""命中行前后各 ``context`` 行,返回 ``(命中列表, 是否有行被截断)``。"""
|
|
272
|
+
start = max(0, index - context)
|
|
273
|
+
end = min(len(lines) - 1, index + context)
|
|
274
|
+
block: list[GrepHit] = []
|
|
275
|
+
truncated_any = False
|
|
276
|
+
for current in range(start, end + 1):
|
|
277
|
+
body, truncated = truncate_line(lines[current])
|
|
278
|
+
truncated_any = truncated_any or truncated
|
|
279
|
+
block.append(
|
|
280
|
+
GrepHit(
|
|
281
|
+
path=to_posix(relative),
|
|
282
|
+
line=current + 1,
|
|
283
|
+
text=body,
|
|
284
|
+
context=current != index,
|
|
285
|
+
)
|
|
286
|
+
)
|
|
287
|
+
return block, truncated_any
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
PROMPT_SNIPPET = "Search file contents for patterns (respects .gitignore)"
|
|
291
|
+
|
|
292
|
+
PROMPT_GUIDELINES: tuple[str, ...] = ()
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
__all__ = [
|
|
296
|
+
"DEFAULT_LIMIT",
|
|
297
|
+
"GREP_PARAMETERS",
|
|
298
|
+
"PROMPT_GUIDELINES",
|
|
299
|
+
"PROMPT_SNIPPET",
|
|
300
|
+
"GrepHit",
|
|
301
|
+
"GrepOutcome",
|
|
302
|
+
"create_grep_tool",
|
|
303
|
+
"format_hits",
|
|
304
|
+
"search_contents",
|
|
305
|
+
]
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""遍历目录时的忽略规则:``.gitignore`` 语义 + 固定剪枝。
|
|
2
|
+
|
|
3
|
+
这里不依赖外部命令(也不该要求用户先装),于是需要自己遍历。
|
|
4
|
+
**``.gitignore`` 的匹配语义交给 ``pathspec``**:它是一个成熟格式,手写通配符翻译迟早
|
|
5
|
+
在 ``**``、否定模式与目录尾斜杠三处出错。
|
|
6
|
+
|
|
7
|
+
## 三层规则,从窄到宽
|
|
8
|
+
|
|
9
|
+
1. **固定剪枝目录**:``.git``(对象库不是源码)与 ``node_modules``(几十万个文件,
|
|
10
|
+
没有一行是模型要改的)。无论 ``.gitignore`` 怎么写都不进。
|
|
11
|
+
2. **逐层 ``.gitignore``**:与 git 一致——深层的文件覆盖浅层的;否定模式(``!``)
|
|
12
|
+
在同一个文件内生效;子目录的规则只作用于该子目录之下。
|
|
13
|
+
3. **符号链接目录不跟进**:链接可能指向自己,遍历会成环。链接**文件**照常返回。
|
|
14
|
+
|
|
15
|
+
## 为什么不用 ``os.walk``
|
|
16
|
+
|
|
17
|
+
``os.walk`` 无法表达"进入某目录前先加载它的 ``.gitignore``"这件事,而且它自带剪枝
|
|
18
|
+
只能靠调用方改 ``dirnames``(一个隐式的原地修改协议)。这里的遍历是显式递归,
|
|
19
|
+
进目录时 push 一层规则、出来时 pop,与 git 的判定范围完全对应。
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import os
|
|
25
|
+
from collections.abc import AsyncIterator, Iterable
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from fnmatch import fnmatchcase
|
|
28
|
+
from typing import Final
|
|
29
|
+
|
|
30
|
+
import pathspec
|
|
31
|
+
|
|
32
|
+
from braid_coding_agent.tools.operations import FileOperations
|
|
33
|
+
from braid_coding_agent.tools.path_utils import relative_posix, to_posix
|
|
34
|
+
|
|
35
|
+
#: 永不进入的目录名。按名字判定:任何层级的 ``.git`` 都不该被搜索。
|
|
36
|
+
DEFAULT_PRUNED_DIRS: Final[frozenset[str]] = frozenset({".git", "node_modules"})
|
|
37
|
+
|
|
38
|
+
#: ``.gitignore`` 文件名。
|
|
39
|
+
_GITIGNORE: Final[str] = ".gitignore"
|
|
40
|
+
|
|
41
|
+
#: 空规则表:目录里没有 ``.gitignore`` 时占位,让规则栈深度与目录深度始终一致。
|
|
42
|
+
_EMPTY_SPEC: Final[pathspec.GitIgnoreSpec] = pathspec.GitIgnoreSpec.from_lines([])
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(slots=True)
|
|
46
|
+
class _Spec:
|
|
47
|
+
"""一份 ``.gitignore`` 以及它生效的目录。"""
|
|
48
|
+
|
|
49
|
+
base: str
|
|
50
|
+
spec: pathspec.GitIgnoreSpec
|
|
51
|
+
|
|
52
|
+
def decision(self, path: str, *, is_dir: bool) -> bool | None:
|
|
53
|
+
"""``True`` 忽略 / ``False`` 显式保留 / ``None`` 这份文件没有表态。
|
|
54
|
+
|
|
55
|
+
从最后一条模式往前找:git 的规则是"最后匹配的模式胜出",而否定模式
|
|
56
|
+
(``include=False``)正是靠这条规则把前面忽略掉的文件捞回来。
|
|
57
|
+
"""
|
|
58
|
+
relative = os.path.relpath(path, self.base)
|
|
59
|
+
if os.path.isabs(relative) or relative == os.pardir:
|
|
60
|
+
return None
|
|
61
|
+
if relative.startswith(os.pardir + os.sep):
|
|
62
|
+
return None
|
|
63
|
+
target = to_posix(relative)
|
|
64
|
+
if is_dir and not target.endswith("/"):
|
|
65
|
+
target += "/"
|
|
66
|
+
for pattern in reversed(self.spec.patterns):
|
|
67
|
+
if pattern.include is None:
|
|
68
|
+
continue
|
|
69
|
+
if pattern.match_file(target):
|
|
70
|
+
return pattern.include
|
|
71
|
+
return None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class IgnoreRules:
|
|
75
|
+
"""一个搜索根目录上的规则栈。每次搜索新建一个,不要跨搜索复用。"""
|
|
76
|
+
|
|
77
|
+
__slots__ = ("_ops", "_pruned", "_specs")
|
|
78
|
+
|
|
79
|
+
def __init__(
|
|
80
|
+
self,
|
|
81
|
+
root: str,
|
|
82
|
+
ops: FileOperations,
|
|
83
|
+
*,
|
|
84
|
+
pruned_dirs: Iterable[str] = DEFAULT_PRUNED_DIRS,
|
|
85
|
+
) -> None:
|
|
86
|
+
self._ops = ops
|
|
87
|
+
self._specs: list[_Spec] = []
|
|
88
|
+
self._pruned = frozenset(pruned_dirs)
|
|
89
|
+
|
|
90
|
+
async def push(self, directory: str) -> None:
|
|
91
|
+
"""进入目录:加载它的 ``.gitignore``(没有就压一层空规则)。"""
|
|
92
|
+
gitignore = os.path.join(directory, _GITIGNORE)
|
|
93
|
+
if not await self._ops.exists(gitignore):
|
|
94
|
+
self._specs.append(_Spec(base=directory, spec=_EMPTY_SPEC))
|
|
95
|
+
return
|
|
96
|
+
text = (await self._ops.read_bytes(gitignore)).decode("utf-8", errors="replace")
|
|
97
|
+
self._specs.append(
|
|
98
|
+
_Spec(base=directory, spec=pathspec.GitIgnoreSpec.from_lines(text.splitlines()))
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
def pop(self) -> None:
|
|
102
|
+
"""离开目录。压/弹必须成对,否则深层规则会污染兄弟目录。"""
|
|
103
|
+
self._specs.pop()
|
|
104
|
+
|
|
105
|
+
def ignored(self, path: str, *, is_dir: bool) -> bool:
|
|
106
|
+
"""``path`` 是否被忽略。深层规则先投票。"""
|
|
107
|
+
if is_dir and os.path.basename(path) in self._pruned:
|
|
108
|
+
return True
|
|
109
|
+
for spec in reversed(self._specs):
|
|
110
|
+
decision = spec.decision(path, is_dir=is_dir)
|
|
111
|
+
if decision is not None:
|
|
112
|
+
return decision
|
|
113
|
+
return False
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
async def iter_files(
|
|
117
|
+
ops: FileOperations,
|
|
118
|
+
root: str,
|
|
119
|
+
*,
|
|
120
|
+
pruned_dirs: Iterable[str] = DEFAULT_PRUNED_DIRS,
|
|
121
|
+
) -> AsyncIterator[tuple[str, str]]:
|
|
122
|
+
"""深度优先遍历 ``root``,产出 ``(绝对路径, 相对 root 的 posix 路径)``。
|
|
123
|
+
|
|
124
|
+
``root`` 是文件时直接产出它自己(只搜一个文件的场景)。读不动的目录
|
|
125
|
+
(权限、竞态删除)跳过:搜索工具的目标是"找到能读的匹配",因为一个子目录
|
|
126
|
+
没权限就整次搜索失败,用户拿不到任何结果。
|
|
127
|
+
"""
|
|
128
|
+
absolute_root = os.path.abspath(root)
|
|
129
|
+
if not await ops.is_dir(absolute_root):
|
|
130
|
+
yield absolute_root, to_posix(os.path.basename(absolute_root))
|
|
131
|
+
return
|
|
132
|
+
rules = IgnoreRules(absolute_root, ops, pruned_dirs=pruned_dirs)
|
|
133
|
+
async for item in _walk(ops, absolute_root, absolute_root, rules):
|
|
134
|
+
yield item
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
async def _walk(
|
|
138
|
+
ops: FileOperations,
|
|
139
|
+
directory: str,
|
|
140
|
+
root: str,
|
|
141
|
+
rules: IgnoreRules,
|
|
142
|
+
) -> AsyncIterator[tuple[str, str]]:
|
|
143
|
+
await rules.push(directory)
|
|
144
|
+
try:
|
|
145
|
+
try:
|
|
146
|
+
names = await ops.readdir(directory)
|
|
147
|
+
except OSError:
|
|
148
|
+
return
|
|
149
|
+
for name in sorted(names):
|
|
150
|
+
path = os.path.join(directory, name)
|
|
151
|
+
is_dir = await ops.is_dir(path)
|
|
152
|
+
if rules.ignored(path, is_dir=is_dir):
|
|
153
|
+
continue
|
|
154
|
+
if is_dir:
|
|
155
|
+
# 符号链接目录不跟进:链成环会让遍历永远跑不完。
|
|
156
|
+
if await ops.is_symlink(path):
|
|
157
|
+
continue
|
|
158
|
+
async for item in _walk(ops, path, root, rules):
|
|
159
|
+
yield item
|
|
160
|
+
else:
|
|
161
|
+
yield path, relative_posix(path, root)
|
|
162
|
+
finally:
|
|
163
|
+
rules.pop()
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def matches_glob(relative_path: str, pattern: str) -> bool:
|
|
167
|
+
"""``grep``/``find`` 的 glob 过滤。
|
|
168
|
+
|
|
169
|
+
含 ``/`` 的模式(``src/**/*.ts``)匹配整条相对路径;不含 ``/`` 的模式
|
|
170
|
+
(``*.py``)只匹配文件名——与 ``rg --glob`` / ``fd --glob`` 的默认行为一致。
|
|
171
|
+
|
|
172
|
+
路径模式按**段**匹配:``fnmatch`` 的 ``*`` 会跨过 ``/``,把整串交给它会错误命中
|
|
173
|
+
``src/deep/a.ts``。``**`` 是唯一能跨层的段,并且可以匹配零层
|
|
174
|
+
(``src/**/*.ts`` 命中 ``src/a.ts``)。
|
|
175
|
+
"""
|
|
176
|
+
if "/" not in pattern:
|
|
177
|
+
return fnmatchcase(os.path.basename(relative_path), pattern)
|
|
178
|
+
return _match_segments(pattern.split("/"), relative_path.split("/"))
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _match_segments(pattern: list[str], parts: list[str]) -> bool:
|
|
182
|
+
"""按目录段递归匹配。``**`` 吃零到多段,其余段用 ``fnmatch`` 逐段比。"""
|
|
183
|
+
if not pattern:
|
|
184
|
+
return not parts
|
|
185
|
+
head = pattern[0]
|
|
186
|
+
if head == "**":
|
|
187
|
+
return any(_match_segments(pattern[1:], parts[index:]) for index in range(len(parts) + 1))
|
|
188
|
+
if not parts or not fnmatchcase(parts[0], head):
|
|
189
|
+
return False
|
|
190
|
+
return _match_segments(pattern[1:], parts[1:])
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
__all__ = [
|
|
194
|
+
"DEFAULT_PRUNED_DIRS",
|
|
195
|
+
"IgnoreRules",
|
|
196
|
+
"iter_files",
|
|
197
|
+
"matches_glob",
|
|
198
|
+
]
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""``ls``:列出目录内容。
|
|
2
|
+
|
|
3
|
+
以下几条行为值得注意:
|
|
4
|
+
|
|
5
|
+
- **目录带 ``/`` 后缀**。模型据此知道下一步该 ``ls`` 还是该 ``read``,不必再试探一次;
|
|
6
|
+
- **包含点文件**。``.gitignore``、``.github/`` 这类路径经常就是任务对象;
|
|
7
|
+
- **按名字排序且忽略大小写**。同一个目录两次列出的顺序一致,模型引用"第 3 个"才成立。
|
|
8
|
+
|
|
9
|
+
无法判断类型的条目(竞态删除、坏链接)按普通文件列出:``isdir`` 对它们返回假,
|
|
10
|
+
而列目录的目的不是审计,一个坏条目不该让整次调用失败。
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
|
|
17
|
+
from braid_agent.tools import AgentTool, AgentToolResult, ToolUpdateSink
|
|
18
|
+
from braid_ai.cancel import CancelToken
|
|
19
|
+
from braid_ai.types import JsonValue, TextContent
|
|
20
|
+
from braid_coding_agent.tools.args import optional_integer_arg, optional_string_arg
|
|
21
|
+
from braid_coding_agent.tools.operations import (
|
|
22
|
+
FileOperations,
|
|
23
|
+
LocalFileOperations,
|
|
24
|
+
ensure_not_cancelled,
|
|
25
|
+
)
|
|
26
|
+
from braid_coding_agent.tools.path_utils import resolve_to_cwd
|
|
27
|
+
from braid_coding_agent.tools.truncate import DEFAULT_MAX_BYTES, format_size, truncate_head
|
|
28
|
+
|
|
29
|
+
DEFAULT_LIMIT = 500
|
|
30
|
+
|
|
31
|
+
LS_PARAMETERS: dict[str, JsonValue] = {
|
|
32
|
+
"type": "object",
|
|
33
|
+
"properties": {
|
|
34
|
+
"path": {
|
|
35
|
+
"type": "string",
|
|
36
|
+
"description": "Directory to list (default: current directory)",
|
|
37
|
+
},
|
|
38
|
+
"limit": {
|
|
39
|
+
"type": "integer",
|
|
40
|
+
"description": f"Maximum number of entries to return (default: {DEFAULT_LIMIT})",
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
"additionalProperties": False,
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def create_ls_tool(
|
|
48
|
+
cwd: str,
|
|
49
|
+
*,
|
|
50
|
+
operations: FileOperations | None = None,
|
|
51
|
+
max_bytes: int = DEFAULT_MAX_BYTES,
|
|
52
|
+
) -> AgentTool:
|
|
53
|
+
"""构造 ``ls`` 工具。``cwd`` 是相对路径的基准目录。"""
|
|
54
|
+
ops: FileOperations = operations if operations is not None else LocalFileOperations()
|
|
55
|
+
|
|
56
|
+
async def execute(
|
|
57
|
+
tool_call_id: str,
|
|
58
|
+
args: dict[str, JsonValue],
|
|
59
|
+
signal: CancelToken | None,
|
|
60
|
+
on_update: ToolUpdateSink,
|
|
61
|
+
) -> AgentToolResult:
|
|
62
|
+
target = optional_string_arg(args, "path")
|
|
63
|
+
limit = max(1, optional_integer_arg(args, "limit") or DEFAULT_LIMIT)
|
|
64
|
+
dir_path = resolve_to_cwd(target or ".", cwd)
|
|
65
|
+
|
|
66
|
+
ensure_not_cancelled(signal)
|
|
67
|
+
if not await ops.exists(dir_path):
|
|
68
|
+
raise ValueError(f"Path not found: {dir_path}")
|
|
69
|
+
if not await ops.is_dir(dir_path):
|
|
70
|
+
raise ValueError(f"Not a directory: {dir_path}")
|
|
71
|
+
|
|
72
|
+
entries = sorted(await ops.readdir(dir_path), key=str.lower)
|
|
73
|
+
results: list[str] = []
|
|
74
|
+
limit_reached = False
|
|
75
|
+
for entry in entries:
|
|
76
|
+
if len(results) >= limit:
|
|
77
|
+
limit_reached = True
|
|
78
|
+
break
|
|
79
|
+
entry_path = os.path.join(dir_path, entry)
|
|
80
|
+
is_dir = await ops.is_dir(entry_path)
|
|
81
|
+
results.append(f"{entry}/" if is_dir else entry)
|
|
82
|
+
|
|
83
|
+
if not results:
|
|
84
|
+
return AgentToolResult(content=[TextContent(text="(empty directory)")])
|
|
85
|
+
|
|
86
|
+
raw_output = "\n".join(results)
|
|
87
|
+
truncation = truncate_head(raw_output, max_lines=len(results), max_bytes=max_bytes)
|
|
88
|
+
details: dict[str, JsonValue] = {}
|
|
89
|
+
notices: list[str] = []
|
|
90
|
+
if limit_reached:
|
|
91
|
+
notices.append(f"{limit} entries limit reached. Use limit={limit * 2} for more")
|
|
92
|
+
details["entry_limit_reached"] = limit
|
|
93
|
+
if truncation.truncated:
|
|
94
|
+
notices.append(f"{format_size(max_bytes)} limit reached")
|
|
95
|
+
details["truncation"] = truncation.to_details()
|
|
96
|
+
output = truncation.content
|
|
97
|
+
if notices:
|
|
98
|
+
output += f"\n\n[{'. '.join(notices)}]"
|
|
99
|
+
return AgentToolResult(
|
|
100
|
+
content=[TextContent(text=output)], details=details if details else None
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
return AgentTool(
|
|
104
|
+
name="ls",
|
|
105
|
+
label="ls",
|
|
106
|
+
description=(
|
|
107
|
+
"List directory contents. Returns entries sorted alphabetically, with '/' suffix "
|
|
108
|
+
f"for directories. Includes dotfiles. Output is truncated to {DEFAULT_LIMIT} entries "
|
|
109
|
+
f"or {max_bytes // 1024}KB (whichever is hit first)."
|
|
110
|
+
),
|
|
111
|
+
parameters=LS_PARAMETERS,
|
|
112
|
+
execute=execute,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
PROMPT_SNIPPET = "List directory contents"
|
|
117
|
+
|
|
118
|
+
PROMPT_GUIDELINES: tuple[str, ...] = ()
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
__all__ = [
|
|
122
|
+
"DEFAULT_LIMIT",
|
|
123
|
+
"LS_PARAMETERS",
|
|
124
|
+
"PROMPT_GUIDELINES",
|
|
125
|
+
"PROMPT_SNIPPET",
|
|
126
|
+
"create_ls_tool",
|
|
127
|
+
]
|