view.go

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