File size: 9,127 Bytes
eca5751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Code Tools - code search, lint, format."""
from __future__ import annotations

import os
import re
import subprocess
from typing import Dict, Any, List

from .base import Tool, ToolResult, ToolContext, ToolCategory, ToolSafety


class CodeSearchTool(Tool):
    """Search code trong files với regex."""
    category = ToolCategory.CODE
    safety = ToolSafety.SAFE
    
    @property
    def name(self) -> str:
        return "code_search"
    
    @property
    def description(self) -> str:
        return "Search trong code files bằng regex. Hỗ trợ file pattern, context lines."
    
    @property
    def parameters(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "pattern": {"type": "string", "description": "Regex pattern"},
                "path": {"type": "string", "default": "."},
                "file_pattern": {"type": "string", "default": "*.py"},
                "case_insensitive": {"type": "boolean", "default": False},
                "context": {"type": "integer", "default": 0, "description": "Lines of context"},
                "max_results": {"type": "integer", "default": 50},
            },
            "required": ["pattern"],
        }
    
    def execute(self, args: Dict[str, Any], context: ToolContext) -> ToolResult:
        pattern = args["pattern"]
        path = args.get("path", ".")
        file_pattern = args.get("file_pattern", "*.py")
        case_insensitive = args.get("case_insensitive", False)
        context_lines = args.get("context", 0)
        max_results = args.get("max_results", 50)
        
        flags = re.IGNORECASE if case_insensitive else 0
        try:
            regex = re.compile(pattern, flags)
        except re.error as e:
            return ToolResult(success=False, error=f"Invalid regex: {e}", return_code=2)
        
        full_path = path if os.path.isabs(path) else os.path.join(context.working_dir, path)
        
        matches = []
        files_scanned = 0
        
        for root, dirs, files in os.walk(full_path):
            # Skip hidden dirs, venv, __pycache__, .git
            dirs[:] = [d for d in dirs if not d.startswith(".") and d not in (
                "venv", "__pycache__", "node_modules", ".git", "dist", "build",
            )]
            for fname in files:
                if not _matches_pattern(fname, file_pattern):
                    continue
                fpath = os.path.join(root, fname)
                files_scanned += 1
                try:
                    with open(fpath, "r", encoding="utf-8", errors="replace") as f:
                        lines = f.readlines()
                    for i, line in enumerate(lines):
                        if regex.search(line):
                            start = max(0, i - context_lines)
                            end = min(len(lines), i + context_lines + 1)
                            context_text = "".join(
                                f"  {j+1}: {lines[j]}" for j in range(start, end)
                            )
                            matches.append({
                                "file": fpath,
                                "line": i + 1,
                                "match": line.rstrip(),
                                "context": context_text,
                            })
                            if len(matches) >= max_results:
                                return ToolResult(
                                    success=True,
                                    output=_format_matches(matches),
                                    metadata={
                                        "total_matches": len(matches),
                                        "files_scanned": files_scanned,
                                        "truncated": True,
                                    },
                                )
                except Exception:
                    continue
        
        return ToolResult(
            success=True,
            output=_format_matches(matches) if matches else "No matches found.",
            metadata={"total_matches": len(matches), "files_scanned": files_scanned},
        )


def _matches_pattern(fname: str, pattern: str) -> bool:
    """Simple glob matching."""
    import fnmatch
    return fnmatch.fnmatch(fname, pattern)


def _format_matches(matches: List[Dict]) -> str:
    lines = []
    for m in matches:
        lines.append(f"📄 {m['file']}:{m['line']}")
        lines.append(f"  → {m['match']}")
        if m.get("context"):
            lines.append(m["context"])
        lines.append("")
    return "\n".join(lines)


class CodeLintTool(Tool):
    """Lint code với nhiều linters."""
    category = ToolCategory.CODE
    safety = ToolSafety.SAFE
    
    @property
    def name(self) -> str:
        return "code_lint"
    
    @property
    def description(self) -> str:
        return "Lint Python code với pyflakes, pycodestyle, hoặc pylint."
    
    @property
    def parameters(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "path": {"type": "string"},
                "linter": {"type": "string", "default": "auto", "enum": ["auto", "pyflakes", "pycodestyle", "pylint", "flake8", "ruff"]},
            },
            "required": ["path"],
        }
    
    def execute(self, args: Dict[str, Any], context: ToolContext) -> ToolResult:
        path = args["path"]
        linter = args.get("linter", "auto")
        
        linters_to_try = ["ruff", "flake8", "pyflakes", "pycodestyle"] if linter == "auto" else [linter]
        
        for l in linters_to_try:
            try:
                result = subprocess.run(
                    [l, path],
                    capture_output=True,
                    text=True,
                    timeout=context.timeout,
                    check=False,
                )
                if result.returncode == 0 or result.stdout or result.stderr:
                    return ToolResult(
                        success=(result.returncode == 0),
                        output=result.stdout or "(no issues)",
                        error=result.stderr if result.stderr else None,
                        return_code=result.returncode,
                        metadata={"linter": l, "path": path},
                    )
            except FileNotFoundError:
                continue
            except Exception:
                continue
        
        return ToolResult(
            success=False,
            error="No linter available. Install: pip install ruff flake8",
            return_code=1,
        )


class CodeFormatTool(Tool):
    """Format code với black, autopep8, hoặc isort."""
    category = ToolCategory.CODE
    safety = ToolSafety.MODERATE
    
    @property
    def name(self) -> str:
        return "code_format"
    
    @property
    def description(self) -> str:
        return "Format Python code với black / autopep8 / isort."
    
    @property
    def parameters(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "path": {"type": "string"},
                "formatter": {"type": "string", "default": "auto", "enum": ["auto", "black", "autopep8", "isort"]},
                "check_only": {"type": "boolean", "default": False},
            },
            "required": ["path"],
        }
    
    def execute(self, args: Dict[str, Any], context: ToolContext) -> ToolResult:
        path = args["path"]
        formatter = args.get("formatter", "auto")
        check_only = args.get("check_only", False)
        
        formatters = ["black", "autopep8", "isort"] if formatter == "auto" else [formatter]
        
        for fmt in formatters:
            cmd = [fmt]
            if fmt == "black":
                cmd.append("--check" if check_only else "--write")
            elif fmt == "autopep8":
                cmd.append("--in-place" if not check_only else "--diff")
            elif fmt == "isort":
                cmd.append("--check-only" if check_only else "--write")
            cmd.append(path)
            
            try:
                result = subprocess.run(
                    cmd,
                    capture_output=True,
                    text=True,
                    timeout=context.timeout,
                    check=False,
                )
                return ToolResult(
                    success=(result.returncode == 0),
                    output=result.stdout or f"Formatted with {fmt}",
                    error=result.stderr if result.stderr else None,
                    return_code=result.returncode,
                    metadata={"formatter": fmt, "path": path, "check_only": check_only},
                )
            except FileNotFoundError:
                continue
            except Exception:
                continue
        
        return ToolResult(
            success=False,
            error="No formatter available. Install: pip install black",
            return_code=1,
        )