1package tools
2
3import (
4 "bytes"
5 "context"
6 _ "embed"
7 "fmt"
8 "log/slog"
9 "os/exec"
10 "path/filepath"
11 "sort"
12 "strings"
13
14 "github.com/charmbracelet/crush/internal/fsext"
15 "github.com/charmbracelet/fantasy/ai"
16)
17
18const GlobToolName = "glob"
19
20//go:embed glob.md
21var globDescription []byte
22
23type GlobParams struct {
24 Pattern string `json:"pattern" description:"The glob pattern to match files against"`
25 Path string `json:"path" description:"The directory to search in. Defaults to the current working directory."`
26}
27
28type GlobResponseMetadata struct {
29 NumberOfFiles int `json:"number_of_files"`
30 Truncated bool `json:"truncated"`
31}
32
33func NewGlobTool(workingDir string) ai.AgentTool {
34 return ai.NewAgentTool(
35 GlobToolName,
36 string(globDescription),
37 func(ctx context.Context, params GlobParams, call ai.ToolCall) (ai.ToolResponse, error) {
38 if params.Pattern == "" {
39 return ai.NewTextErrorResponse("pattern is required"), nil
40 }
41
42 searchPath := params.Path
43 if searchPath == "" {
44 searchPath = workingDir
45 }
46
47 files, truncated, err := globFiles(ctx, params.Pattern, searchPath, 100)
48 if err != nil {
49 return ai.ToolResponse{}, fmt.Errorf("error finding files: %w", err)
50 }
51
52 var output string
53 if len(files) == 0 {
54 output = "No files found"
55 } else {
56 output = strings.Join(files, "\n")
57 if truncated {
58 output += "\n\n(Results are truncated. Consider using a more specific path or pattern.)"
59 }
60 }
61
62 return ai.WithResponseMetadata(
63 ai.NewTextResponse(output),
64 GlobResponseMetadata{
65 NumberOfFiles: len(files),
66 Truncated: truncated,
67 },
68 ), nil
69 })
70}
71
72func globFiles(ctx context.Context, pattern, searchPath string, limit int) ([]string, bool, error) {
73 cmdRg := getRgCmd(ctx, pattern)
74 if cmdRg != nil {
75 cmdRg.Dir = searchPath
76 matches, err := runRipgrep(cmdRg, searchPath, limit)
77 if err == nil {
78 return matches, len(matches) >= limit && limit > 0, nil
79 }
80 slog.Warn("Ripgrep execution failed, falling back to doublestar", "error", err)
81 }
82
83 return fsext.GlobWithDoubleStar(pattern, searchPath, limit)
84}
85
86func runRipgrep(cmd *exec.Cmd, searchRoot string, limit int) ([]string, error) {
87 out, err := cmd.CombinedOutput()
88 if err != nil {
89 if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() == 1 {
90 return nil, nil
91 }
92 return nil, fmt.Errorf("ripgrep: %w\n%s", err, out)
93 }
94
95 var matches []string
96 for p := range bytes.SplitSeq(out, []byte{0}) {
97 if len(p) == 0 {
98 continue
99 }
100 absPath := string(p)
101 if !filepath.IsAbs(absPath) {
102 absPath = filepath.Join(searchRoot, absPath)
103 }
104 if fsext.SkipHidden(absPath) {
105 continue
106 }
107 matches = append(matches, absPath)
108 }
109
110 sort.SliceStable(matches, func(i, j int) bool {
111 return len(matches[i]) < len(matches[j])
112 })
113
114 if limit > 0 && len(matches) > limit {
115 matches = matches[:limit]
116 }
117 return matches, nil
118}