File size: 1,381 Bytes
93be2a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import json
import os
import shlex
import subprocess
from typing import Any, Dict

from .registry import ToolRegistry


def t_code_search(args: Dict[str, Any]) -> str:
    """Search code using ripgrep or grep.
    Args: pattern, path (default .), max_results
    """
    pattern = args.get("pattern")
    path = args.get("path", ".")
    max_results = int(args.get("max_results", 200))
    if not pattern:
        return json.dumps({"error": "pattern required"})
    rg = shutil.which("rg") if 'shutil' in globals() else None
    try:
        if rg:
            cmd = ["rg", "-n", "-S", str(pattern), str(path)]
        else:
            cmd = ["grep", "-R", "-n", str(pattern), str(path)]
        proc = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
        lines = proc.stdout.splitlines()[:max_results]
        return json.dumps({"matches": lines, "rc": proc.returncode})
    except Exception as e:
        return json.dumps({"error": str(e)})


def register_tools(reg: ToolRegistry) -> None:
    reg.register(
        name="code_search",
        description="Search codebase for a pattern (ripgrep or grep).",
        parameters={"type": "object", "properties": {"pattern": {"type": "string"}, "path": {"type": "string"}, "max_results": {"type": "integer"}}, "required": ["pattern"]},
        handler=t_code_search,
    )