view.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. package tools
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "github.com/kujtimiihoxha/opencode/internal/config"
  12. "github.com/kujtimiihoxha/opencode/internal/lsp"
  13. )
  14. type ViewParams struct {
  15. FilePath string `json:"file_path"`
  16. Offset int `json:"offset"`
  17. Limit int `json:"limit"`
  18. }
  19. type viewTool struct {
  20. lspClients map[string]*lsp.Client
  21. }
  22. const (
  23. ViewToolName = "view"
  24. MaxReadSize = 250 * 1024
  25. DefaultReadLimit = 2000
  26. MaxLineLength = 2000
  27. viewDescription = `File viewing tool that reads and displays the contents of files with line numbers, allowing you to examine code, logs, or text data.
  28. WHEN TO USE THIS TOOL:
  29. - Use when you need to read the contents of a specific file
  30. - Helpful for examining source code, configuration files, or log files
  31. - Perfect for looking at text-based file formats
  32. HOW TO USE:
  33. - Provide the path to the file you want to view
  34. - Optionally specify an offset to start reading from a specific line
  35. - Optionally specify a limit to control how many lines are read
  36. FEATURES:
  37. - Displays file contents with line numbers for easy reference
  38. - Can read from any position in a file using the offset parameter
  39. - Handles large files by limiting the number of lines read
  40. - Automatically truncates very long lines for better display
  41. - Suggests similar file names when the requested file isn't found
  42. LIMITATIONS:
  43. - Maximum file size is 250KB
  44. - Default reading limit is 2000 lines
  45. - Lines longer than 2000 characters are truncated
  46. - Cannot display binary files or images
  47. - Images can be identified but not displayed
  48. TIPS:
  49. - Use with Glob tool to first find files you want to view
  50. - For code exploration, first use Grep to find relevant files, then View to examine them
  51. - When viewing large files, use the offset parameter to read specific sections`
  52. )
  53. func NewViewTool(lspClients map[string]*lsp.Client) BaseTool {
  54. return &viewTool{
  55. lspClients,
  56. }
  57. }
  58. func (v *viewTool) Info() ToolInfo {
  59. return ToolInfo{
  60. Name: ViewToolName,
  61. Description: viewDescription,
  62. Parameters: map[string]any{
  63. "file_path": map[string]any{
  64. "type": "string",
  65. "description": "The path to the file to read",
  66. },
  67. "offset": map[string]any{
  68. "type": "integer",
  69. "description": "The line number to start reading from (0-based)",
  70. },
  71. "limit": map[string]any{
  72. "type": "integer",
  73. "description": "The number of lines to read (defaults to 2000)",
  74. },
  75. },
  76. Required: []string{"file_path"},
  77. }
  78. }
  79. // Run implements Tool.
  80. func (v *viewTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
  81. var params ViewParams
  82. if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
  83. return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
  84. }
  85. if params.FilePath == "" {
  86. return NewTextErrorResponse("file_path is required"), nil
  87. }
  88. // Handle relative paths
  89. filePath := params.FilePath
  90. if !filepath.IsAbs(filePath) {
  91. filePath = filepath.Join(config.WorkingDirectory(), filePath)
  92. }
  93. // Check if file exists
  94. fileInfo, err := os.Stat(filePath)
  95. if err != nil {
  96. if os.IsNotExist(err) {
  97. // Try to offer suggestions for similarly named files
  98. dir := filepath.Dir(filePath)
  99. base := filepath.Base(filePath)
  100. dirEntries, dirErr := os.ReadDir(dir)
  101. if dirErr == nil {
  102. var suggestions []string
  103. for _, entry := range dirEntries {
  104. if strings.Contains(strings.ToLower(entry.Name()), strings.ToLower(base)) ||
  105. strings.Contains(strings.ToLower(base), strings.ToLower(entry.Name())) {
  106. suggestions = append(suggestions, filepath.Join(dir, entry.Name()))
  107. if len(suggestions) >= 3 {
  108. break
  109. }
  110. }
  111. }
  112. if len(suggestions) > 0 {
  113. return NewTextErrorResponse(fmt.Sprintf("File not found: %s\n\nDid you mean one of these?\n%s",
  114. filePath, strings.Join(suggestions, "\n"))), nil
  115. }
  116. }
  117. return NewTextErrorResponse(fmt.Sprintf("File not found: %s", filePath)), nil
  118. }
  119. return ToolResponse{}, fmt.Errorf("error accessing file: %w", err)
  120. }
  121. // Check if it's a directory
  122. if fileInfo.IsDir() {
  123. return NewTextErrorResponse(fmt.Sprintf("Path is a directory, not a file: %s", filePath)), nil
  124. }
  125. // Check file size
  126. if fileInfo.Size() > MaxReadSize {
  127. return NewTextErrorResponse(fmt.Sprintf("File is too large (%d bytes). Maximum size is %d bytes",
  128. fileInfo.Size(), MaxReadSize)), nil
  129. }
  130. // Set default limit if not provided
  131. if params.Limit <= 0 {
  132. params.Limit = DefaultReadLimit
  133. }
  134. // Check if it's an image file
  135. isImage, imageType := isImageFile(filePath)
  136. // TODO: handle images
  137. if isImage {
  138. return NewTextErrorResponse(fmt.Sprintf("This is an image file of type: %s\nUse a different tool to process images", imageType)), nil
  139. }
  140. // Read the file content
  141. content, lineCount, err := readTextFile(filePath, params.Offset, params.Limit)
  142. if err != nil {
  143. return ToolResponse{}, fmt.Errorf("error reading file: %w", err)
  144. }
  145. notifyLspOpenFile(ctx, filePath, v.lspClients)
  146. output := "<file>\n"
  147. // Format the output with line numbers
  148. output += addLineNumbers(content, params.Offset+1)
  149. // Add a note if the content was truncated
  150. if lineCount > params.Offset+len(strings.Split(content, "\n")) {
  151. output += fmt.Sprintf("\n\n(File has more lines. Use 'offset' parameter to read beyond line %d)",
  152. params.Offset+len(strings.Split(content, "\n")))
  153. }
  154. output += "\n</file>\n"
  155. output += getDiagnostics(filePath, v.lspClients)
  156. recordFileRead(filePath)
  157. return NewTextResponse(output), nil
  158. }
  159. func addLineNumbers(content string, startLine int) string {
  160. if content == "" {
  161. return ""
  162. }
  163. lines := strings.Split(content, "\n")
  164. var result []string
  165. for i, line := range lines {
  166. line = strings.TrimSuffix(line, "\r")
  167. lineNum := i + startLine
  168. numStr := fmt.Sprintf("%d", lineNum)
  169. if len(numStr) >= 6 {
  170. result = append(result, fmt.Sprintf("%s|%s", numStr, line))
  171. } else {
  172. paddedNum := fmt.Sprintf("%6s", numStr)
  173. result = append(result, fmt.Sprintf("%s|%s", paddedNum, line))
  174. }
  175. }
  176. return strings.Join(result, "\n")
  177. }
  178. func readTextFile(filePath string, offset, limit int) (string, int, error) {
  179. file, err := os.Open(filePath)
  180. if err != nil {
  181. return "", 0, err
  182. }
  183. defer file.Close()
  184. lineCount := 0
  185. scanner := NewLineScanner(file)
  186. if offset > 0 {
  187. for lineCount < offset && scanner.Scan() {
  188. lineCount++
  189. }
  190. if err = scanner.Err(); err != nil {
  191. return "", 0, err
  192. }
  193. }
  194. if offset == 0 {
  195. _, err = file.Seek(0, io.SeekStart)
  196. if err != nil {
  197. return "", 0, err
  198. }
  199. }
  200. var lines []string
  201. lineCount = offset
  202. for scanner.Scan() && len(lines) < limit {
  203. lineCount++
  204. lineText := scanner.Text()
  205. if len(lineText) > MaxLineLength {
  206. lineText = lineText[:MaxLineLength] + "..."
  207. }
  208. lines = append(lines, lineText)
  209. }
  210. // Continue scanning to get total line count
  211. for scanner.Scan() {
  212. lineCount++
  213. }
  214. if err := scanner.Err(); err != nil {
  215. return "", 0, err
  216. }
  217. return strings.Join(lines, "\n"), lineCount, nil
  218. }
  219. func isImageFile(filePath string) (bool, string) {
  220. ext := strings.ToLower(filepath.Ext(filePath))
  221. switch ext {
  222. case ".jpg", ".jpeg":
  223. return true, "JPEG"
  224. case ".png":
  225. return true, "PNG"
  226. case ".gif":
  227. return true, "GIF"
  228. case ".bmp":
  229. return true, "BMP"
  230. case ".svg":
  231. return true, "SVG"
  232. case ".webp":
  233. return true, "WebP"
  234. default:
  235. return false, ""
  236. }
  237. }
  238. type LineScanner struct {
  239. scanner *bufio.Scanner
  240. }
  241. func NewLineScanner(r io.Reader) *LineScanner {
  242. return &LineScanner{
  243. scanner: bufio.NewScanner(r),
  244. }
  245. }
  246. func (s *LineScanner) Scan() bool {
  247. return s.scanner.Scan()
  248. }
  249. func (s *LineScanner) Text() string {
  250. return s.scanner.Text()
  251. }
  252. func (s *LineScanner) Err() error {
  253. return s.scanner.Err()
  254. }