1package tools
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "io/fs"
8 "os"
9 "path/filepath"
10 "sort"
11 "strings"
12 "time"
13
14 "github.com/bmatcuk/doublestar/v4"
15 "github.com/kujtimiihoxha/termai/internal/config"
16)
17
18const (
19 GlobToolName = "glob"
20 globDescription = `Fast file pattern matching tool that finds files by name and pattern, returning matching paths sorted by modification time (newest first).
21
22WHEN TO USE THIS TOOL:
23- Use when you need to find files by name patterns or extensions
24- Great for finding specific file types across a directory structure
25- Useful for discovering files that match certain naming conventions
26
27HOW TO USE:
28- Provide a glob pattern to match against file paths
29- Optionally specify a starting directory (defaults to current working directory)
30- Results are sorted with most recently modified files first
31
32GLOB PATTERN SYNTAX:
33- '*' matches any sequence of non-separator characters
34- '**' matches any sequence of characters, including separators
35- '?' matches any single non-separator character
36- '[...]' matches any character in the brackets
37- '[!...]' matches any character not in the brackets
38
39COMMON PATTERN EXAMPLES:
40- '*.js' - Find all JavaScript files in the current directory
41- '**/*.js' - Find all JavaScript files in any subdirectory
42- 'src/**/*.{ts,tsx}' - Find all TypeScript files in the src directory
43- '*.{html,css,js}' - Find all HTML, CSS, and JS files
44
45LIMITATIONS:
46- Results are limited to 100 files (newest first)
47- Does not search file contents (use Grep tool for that)
48- Hidden files (starting with '.') are skipped
49
50TIPS:
51- For the most useful results, combine with the Grep tool: first find files with Glob, then search their contents with Grep
52- When doing iterative exploration that may require multiple rounds of searching, consider using the Agent tool instead
53- Always check if results are truncated and refine your search pattern if needed`
54)
55
56type fileInfo struct {
57 path string
58 modTime time.Time
59}
60
61type GlobParams struct {
62 Pattern string `json:"pattern"`
63 Path string `json:"path"`
64}
65
66type GlobResponseMetadata struct {
67 NumberOfFiles int `json:"number_of_files"`
68 Truncated bool `json:"truncated"`
69}
70
71type globTool struct{}
72
73func NewGlobTool() BaseTool {
74 return &globTool{}
75}
76
77func (g *globTool) Info() ToolInfo {
78 return ToolInfo{
79 Name: GlobToolName,
80 Description: globDescription,
81 Parameters: map[string]any{
82 "pattern": map[string]any{
83 "type": "string",
84 "description": "The glob pattern to match files against",
85 },
86 "path": map[string]any{
87 "type": "string",
88 "description": "The directory to search in. Defaults to the current working directory.",
89 },
90 },
91 Required: []string{"pattern"},
92 }
93}
94
95func (g *globTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
96 var params GlobParams
97 if err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {
98 return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
99 }
100
101 if params.Pattern == "" {
102 return NewTextErrorResponse("pattern is required"), nil
103 }
104
105 searchPath := params.Path
106 if searchPath == "" {
107 searchPath = config.WorkingDirectory()
108 }
109
110 files, truncated, err := globFiles(params.Pattern, searchPath, 100)
111 if err != nil {
112 return ToolResponse{}, fmt.Errorf("error finding files: %w", err)
113 }
114
115 var output string
116 if len(files) == 0 {
117 output = "No files found"
118 } else {
119 output = strings.Join(files, "\n")
120 if truncated {
121 output += "\n\n(Results are truncated. Consider using a more specific path or pattern.)"
122 }
123 }
124
125 return WithResponseMetadata(
126 NewTextResponse(output),
127 GlobResponseMetadata{
128 NumberOfFiles: len(files),
129 Truncated: truncated,
130 },
131 ), nil
132}
133
134func globFiles(pattern, searchPath string, limit int) ([]string, bool, error) {
135 if !strings.HasPrefix(pattern, "/") && !strings.HasPrefix(pattern, searchPath) {
136 if !strings.HasSuffix(searchPath, "/") {
137 searchPath += "/"
138 }
139 pattern = searchPath + pattern
140 }
141
142 fsys := os.DirFS("/")
143
144 relPattern := strings.TrimPrefix(pattern, "/")
145
146 var matches []fileInfo
147
148 err := doublestar.GlobWalk(fsys, relPattern, func(path string, d fs.DirEntry) error {
149 if d.IsDir() {
150 return nil
151 }
152 if skipHidden(path) {
153 return nil
154 }
155
156 info, err := d.Info()
157 if err != nil {
158 return nil // Skip files we can't access
159 }
160
161 absPath := "/" + path // Restore absolute path
162 matches = append(matches, fileInfo{
163 path: absPath,
164 modTime: info.ModTime(),
165 })
166
167 if len(matches) >= limit*2 { // Collect more than needed for sorting
168 return fs.SkipAll
169 }
170
171 return nil
172 })
173 if err != nil {
174 return nil, false, fmt.Errorf("glob walk error: %w", err)
175 }
176
177 sort.Slice(matches, func(i, j int) bool {
178 return matches[i].modTime.After(matches[j].modTime)
179 })
180
181 truncated := len(matches) > limit
182 if truncated {
183 matches = matches[:limit]
184 }
185
186 results := make([]string, len(matches))
187 for i, m := range matches {
188 results[i] = m.path
189 }
190
191 return results, truncated, nil
192}
193
194func skipHidden(path string) bool {
195 base := filepath.Base(path)
196 return base != "." && strings.HasPrefix(base, ".")
197}