1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
|
"""Content search across the workspace.
Regex-based, the way an agent actually needs to find things: a symbol's
definition and its call sites, a string literal, an error message. Every result
carries enough context to act on without a second read.
Results are capped and files are skipped by extension and directory, because an
unbounded search is how an agent fills its own context window with noise.
"""
from __future__ import annotations
import os
import re
from ..errors import ToolError
from .base import BaseTool
#: Directories that are never worth grepping.
SKIP_DIRS = {
".git", ".hg", ".svn", "node_modules", "__pycache__", ".venv", "venv",
".mypy_cache", ".pytest_cache", ".ruff_cache", ".tox", "dist", "build",
".idea", ".vscode", "target", ".next", ".gradle", ".cache", "site-packages",
".eggs", "*.egg-info",
}
#: Binary and generated formats with nothing useful in them as text.
SKIP_SUFFIXES = {
".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".webp", ".svgz",
".pdf", ".zip", ".gz", ".bz2", ".xz", ".tar", ".7z", ".rar",
".so", ".dylib", ".dll", ".exe", ".bin", ".o", ".a", ".class", ".jar",
".pyc", ".pyo", ".wasm", ".woff", ".woff2", ".ttf", ".eot", ".otf",
".mp3", ".mp4", ".mov", ".avi", ".wav", ".flac", ".ogg",
".db", ".sqlite", ".sqlite3", ".lock",
}
#: Files larger than this are reported but not searched: a 4 MB minified bundle
#: matches everything and tells the model nothing.
MAX_FILE_BYTES = 1_000_000
#: Caps that keep a search result readable and the context window survivable.
MAX_MATCHES = 200
MAX_FILES = 2_000
MAX_LINE_CHARS = 400
MAX_FILE_LIST = 100
class SearchTool(BaseTool):
"""Find text in files across the workspace."""
def __init__(self, root: Optional[str] = None) -> None:
self.root = os.path.realpath(root or os.getcwd())
@property
def name(self) -> str:
return "search"
@property
def description(self) -> str:
return (
"Search file contents with a regular expression. Returns matching "
"lines with file:line references and surrounding context. Use this "
"to find where something is defined or used before reading whole "
"files. Also supports listing file paths by glob pattern when "
"'content_pattern' is omitted."
)
@property
def parameters(self) -> Dict[str, Any]:
return {
"type": "object",
"properties": {
"content_pattern": {
"type": "string",
"description": (
"Regular expression to search for. Omit to list files "
"whose paths match 'file_pattern' instead."
),
},
"path": {
"type": "string",
"description": "File or directory to search under. Defaults to the project root.",
},
"file_pattern": {
"type": "string",
"description": (
"Glob restricting which files are searched, e.g. '*.py' "
"or 'src/**/*.ts'. Omit to search all text files."
),
},
"context_lines": {
"type": "integer",
"description": "Lines of context to show around each match. Defaults to 1.",
},
"ignore_case": {
"type": "boolean",
"description": "Case-insensitive match. Defaults to false.",
},
"max_matches": {
"type": "integer",
"description": "Maximum matches to return. Defaults to 200.",
},
},
"required": [],
}
# ------------------------------------------------------------------
# Path handling
# ------------------------------------------------------------------
def _base(self, path: Optional[str]) -> str:
if not path:
return self.root
candidate = path if os.path.isabs(path) else os.path.join(self.root, path)
resolved = os.path.realpath(os.path.expanduser(candidate))
if not resolved.startswith(self.root + os.sep) and resolved != self.root:
raise ToolError(f"Path {path!r} is outside the workspace root {self.root}.")
return resolved
def _walk(self, base: str) -> Iterator[str]:
"""Yield searchable files under ``base``, pruning noise directories."""
if os.path.isfile(base):
yield base
return
checked = 0
for dirpath, dirnames, filenames in os.walk(base):
dirnames[:] = sorted(
d for d in dirnames
if d not in SKIP_DIRS and not d.endswith(".egg-info")
)
for filename in sorted(filenames):
if os.path.splitext(filename)[1].lower() in SKIP_SUFFIXES:
continue
full = os.path.join(dirpath, filename)
try:
if os.path.getsize(full) > MAX_FILE_BYTES:
continue
except OSError:
continue
yield full
checked += 1
if checked >= MAX_FILES:
return
def _matches_glob(self, path: str, pattern: Optional[str]) -> bool:
if not pattern:
return True
try:
from fnmatch import fnmatch
if fnmatch(path, pattern):
return True
# A bare '*.py' should also match nested paths.
return fnmatch(os.path.basename(path), pattern)
except Exception:
return True
# ------------------------------------------------------------------
# Actions
# ------------------------------------------------------------------
def _list_files(self, base: str, file_pattern: Optional[str]) -> str:
matches = [
os.path.relpath(p, self.root)
for p in self._walk(base)
if self._matches_glob(p, file_pattern)
]
if not matches:
scope = os.path.relpath(base, self.root) or "."
return f"No files matching {file_pattern!r} under {scope}."
shown = matches[:MAX_FILE_LIST]
lines = "\n".join(shown)
footer = ""
if len(matches) > MAX_FILE_LIST:
footer = f"\n... {len(matches) - MAX_FILE_LIST} more (narrow 'file_pattern')"
return f"{len(matches)} file(s):\n{lines}{footer}"
def _grep(
self,
base: str,
pattern: str,
file_pattern: Optional[str],
context_lines: int,
ignore_case: bool,
max_matches: int,
) -> str:
flags = re.IGNORECASE if ignore_case else 0
try:
regex = re.compile(pattern, flags)
except re.error as exc:
raise ToolError(
f"Invalid regular expression {pattern!r}: {exc}"
) from exc
span = max(0, min(int(context_lines or 0), 5))
results: List[str] = []
matched_files: List[str] = []
truncated_at: Optional[str] = None
total = 0
for full in self._walk(base):
if not self._matches_glob(full, file_pattern):
continue
try:
with open(full, encoding="utf-8", errors="replace") as handle:
lines = handle.readlines()
except (OSError, PermissionError):
continue
rel = os.path.relpath(full, self.root)
hits = [i for i, line in enumerate(lines) if regex.search(line)]
if not hits:
continue
matched_files.append(rel)
total += len(hits)
# Collapse a run of nearby hits into one block instead of repeating
# the same context lines for every match.
shown_lines: set = set()
for index in hits:
if len(results) >= max_matches:
truncated_at = rel
break
start, end = max(0, index - span), min(len(lines), index + span + 1)
if any(j in shown_lines for j in range(start, end)):
continue
shown_lines.update(range(start, end))
if start > 0:
results.append(" ...")
for j in range(start, end):
marker = ">" if j == index else " "
text = lines[j].rstrip("\n")
if len(text) > MAX_LINE_CHARS:
text = text[:MAX_LINE_CHARS] + "..."
results.append(f"{marker} {rel}:{j + 1}: {text}")
if end < len(lines):
results.append(" ...")
if truncated_at:
break
if not results:
scope = os.path.relpath(base, self.root) or "."
where = f" under {scope}" if scope != "." else ""
suffix = f" matching {file_pattern!r}" if file_pattern else ""
return f"No matches for {pattern!r}{where}{suffix}."
header = f"{total} match(es) for {pattern!r} in {len(matched_files)} file(s)"
footer = ""
if truncated_at:
footer = (
f"\n\n... stopped at {max_matches} matches (in {truncated_at}). "
"Narrow the pattern or the file_pattern to see the rest."
)
elif total > max_matches:
footer = "\n\n... output capped."
return f"{header}\n\n" + "\n".join(results) + footer
async def execute(
self,
content_pattern: Optional[str] = None,
path: Optional[str] = None,
file_pattern: Optional[str] = None,
context_lines: int = 1,
ignore_case: bool = False,
max_matches: int = MAX_MATCHES,
**kwargs: Any,
) -> str:
base = self._base(path)
if not content_pattern:
return self._list_files(base, file_pattern)
return self._grep(
base=base,
pattern=content_pattern,
file_pattern=file_pattern,
context_lines=context_lines,
ignore_case=bool(ignore_case),
max_matches=max(1, min(int(max_matches or MAX_MATCHES), 500)),
)
__all__ = ["SearchTool"]
|