1package tools
2
3import (
4 "cmp"
5 "context"
6 _ "embed"
7 "fmt"
8 "html/template"
9 "os"
10 "path/filepath"
11 "strings"
12
13 "charm.land/fantasy"
14 "github.com/charmbracelet/crush/internal/config"
15 "github.com/charmbracelet/crush/internal/filepathext"
16 "github.com/charmbracelet/crush/internal/fsext"
17 "github.com/charmbracelet/crush/internal/permission"
18)
19
20type LSParams struct {
21 Path string `json:"path,omitempty" description:"The path to the directory to list (defaults to current working directory)"`
22 Ignore []string `json:"ignore,omitempty" description:"List of glob patterns to ignore"`
23 Depth int `json:"depth,omitempty" description:"The maximum depth to traverse"`
24}
25
26type LSPermissionsParams struct {
27 Path string `json:"path"`
28 Ignore []string `json:"ignore"`
29 Depth int `json:"depth"`
30}
31
32type NodeType string
33
34const (
35 NodeTypeFile NodeType = "file"
36 NodeTypeDirectory NodeType = "directory"
37)
38
39type TreeNode struct {
40 Name string `json:"name"`
41 Path string `json:"path"`
42 Type NodeType `json:"type"`
43 Children []*TreeNode `json:"children,omitempty"`
44}
45
46type LSResponseMetadata struct {
47 NumberOfFiles int `json:"number_of_files"`
48 Truncated bool `json:"truncated"`
49}
50
51const (
52 LSToolName = "ls"
53 maxLSFiles = 1000
54)
55
56//go:embed ls.md.tpl
57var lsDescriptionTmpl []byte
58
59var lsDescriptionTpl = template.Must(
60 template.New("lsDescription").
61 Parse(string(lsDescriptionTmpl)),
62)
63
64type lsDescriptionData struct {
65 MaxFiles int
66}
67
68func lsDescription() string {
69 return renderTemplate(lsDescriptionTpl, lsDescriptionData{
70 MaxFiles: maxLSFiles,
71 })
72}
73
74func NewLsTool(permissions permission.Service, workingDir string, lsConfig config.ToolLs) fantasy.AgentTool {
75 return fantasy.NewAgentTool(
76 LSToolName,
77 lsDescription(),
78 func(ctx context.Context, params LSParams, call fantasy.ToolCall) (fantasy.ToolResponse, error) {
79 searchPath, err := fsext.Expand(cmp.Or(params.Path, workingDir))
80 if err != nil {
81 return fantasy.NewTextErrorResponse(fmt.Sprintf("error expanding path: %v", err)), nil
82 }
83
84 searchPath = filepathext.SmartJoin(workingDir, searchPath)
85
86 // Check if directory is outside working directory and request permission if needed
87 absWorkingDir, err := filepath.Abs(workingDir)
88 if err != nil {
89 return fantasy.NewTextErrorResponse(fmt.Sprintf("error resolving working directory: %v", err)), nil
90 }
91
92 absSearchPath, err := filepath.Abs(searchPath)
93 if err != nil {
94 return fantasy.NewTextErrorResponse(fmt.Sprintf("error resolving search path: %v", err)), nil
95 }
96
97 relPath, err := filepath.Rel(absWorkingDir, absSearchPath)
98 if err != nil || strings.HasPrefix(relPath, "..") {
99 // Directory is outside working directory, request permission
100 sessionID := GetSessionFromContext(ctx)
101 if sessionID == "" {
102 return fantasy.ToolResponse{}, fmt.Errorf("session ID is required for accessing directories outside working directory")
103 }
104
105 granted, err := permissions.Request(ctx,
106 permission.CreatePermissionRequest{
107 SessionID: sessionID,
108 Path: absSearchPath,
109 ToolCallID: call.ID,
110 ToolName: LSToolName,
111 Action: "list",
112 Description: fmt.Sprintf("List directory outside working directory: %s", absSearchPath),
113 Params: LSPermissionsParams(params),
114 },
115 )
116 if err != nil {
117 return fantasy.ToolResponse{}, err
118 }
119 if !granted {
120 return NewPermissionDeniedResponse(), nil
121 }
122 }
123
124 output, metadata, err := ListDirectoryTree(searchPath, params, lsConfig)
125 if err != nil {
126 return fantasy.NewTextErrorResponse(err.Error()), nil
127 }
128
129 return fantasy.WithResponseMetadata(
130 fantasy.NewTextResponse(output),
131 metadata,
132 ), nil
133 })
134}
135
136func ListDirectoryTree(searchPath string, params LSParams, lsConfig config.ToolLs) (string, LSResponseMetadata, error) {
137 if _, err := os.Stat(searchPath); os.IsNotExist(err) {
138 return "", LSResponseMetadata{}, fmt.Errorf("path does not exist: %s", searchPath)
139 }
140
141 depth, limit := lsConfig.Limits()
142 maxFiles := cmp.Or(limit, maxLSFiles)
143 files, truncated, err := fsext.ListDirectory(
144 searchPath,
145 params.Ignore,
146 cmp.Or(params.Depth, depth),
147 maxFiles,
148 )
149 if err != nil {
150 return "", LSResponseMetadata{}, fmt.Errorf("error listing directory: %w", err)
151 }
152
153 metadata := LSResponseMetadata{
154 NumberOfFiles: len(files),
155 Truncated: truncated,
156 }
157 tree := createFileTree(files, searchPath)
158
159 var output string
160 if truncated {
161 output = fmt.Sprintf("There are more than %d files in the directory. Use a more specific path or use the Glob tool to find specific files. The first %[1]d files and directories are included below.\n", maxFiles)
162 }
163 if depth > 0 {
164 output = fmt.Sprintf("The directory tree is shown up to a depth of %d. Use a higher depth and a specific path to see more levels.\n", cmp.Or(params.Depth, depth))
165 }
166 return output + "\n" + printTree(tree, searchPath), metadata, nil
167}
168
169func createFileTree(sortedPaths []string, rootPath string) []*TreeNode {
170 root := []*TreeNode{}
171 pathMap := make(map[string]*TreeNode)
172
173 for _, path := range sortedPaths {
174 relativePath := strings.TrimPrefix(path, rootPath)
175 parts := strings.Split(relativePath, string(filepath.Separator))
176 currentPath := ""
177 var parentPath string
178
179 var cleanParts []string
180 for _, part := range parts {
181 if part != "" {
182 cleanParts = append(cleanParts, part)
183 }
184 }
185 parts = cleanParts
186
187 if len(parts) == 0 {
188 continue
189 }
190
191 for i, part := range parts {
192 if currentPath == "" {
193 currentPath = part
194 } else {
195 currentPath = filepath.Join(currentPath, part)
196 }
197
198 if _, exists := pathMap[currentPath]; exists {
199 parentPath = currentPath
200 continue
201 }
202
203 isLastPart := i == len(parts)-1
204 isDir := !isLastPart || strings.HasSuffix(relativePath, string(filepath.Separator))
205 nodeType := NodeTypeFile
206 if isDir {
207 nodeType = NodeTypeDirectory
208 }
209 newNode := &TreeNode{
210 Name: part,
211 Path: currentPath,
212 Type: nodeType,
213 Children: []*TreeNode{},
214 }
215
216 pathMap[currentPath] = newNode
217
218 if i > 0 && parentPath != "" {
219 if parent, ok := pathMap[parentPath]; ok {
220 parent.Children = append(parent.Children, newNode)
221 }
222 } else {
223 root = append(root, newNode)
224 }
225
226 parentPath = currentPath
227 }
228 }
229
230 return root
231}
232
233func printTree(tree []*TreeNode, rootPath string) string {
234 var result strings.Builder
235
236 result.WriteString("- ")
237 result.WriteString(filepath.ToSlash(rootPath))
238 if rootPath[len(rootPath)-1] != '/' {
239 result.WriteByte('/')
240 }
241 result.WriteByte('\n')
242
243 for _, node := range tree {
244 printNode(&result, node, 1)
245 }
246
247 return result.String()
248}
249
250func printNode(builder *strings.Builder, node *TreeNode, level int) {
251 indent := strings.Repeat(" ", level)
252
253 nodeName := node.Name
254 if node.Type == NodeTypeDirectory {
255 nodeName = nodeName + "/"
256 }
257
258 fmt.Fprintf(builder, "%s- %s\n", indent, nodeName)
259
260 if node.Type == NodeTypeDirectory && len(node.Children) > 0 {
261 for _, child := range node.Children {
262 printNode(builder, child, level+1)
263 }
264 }
265}