@@ -0,0 +1,420 @@
13+ "github.com/cloudwego/eino/components/tool"
14+ "github.com/cloudwego/eino/schema"
15+ "github.com/kujtimiihoxha/termai/internal/permission"
16+ "github.com/sergi/go-diff/diffmatchpatch"
19+type editTool struct {
24+ EditToolName = "edit"
27+type EditParams struct {
28+ FilePath string `json:"file_path"`
29+ OldString string `json:"old_string"`
30+ NewString string `json:"new_string"`
33+func (b *editTool) Info(ctx context.Context) (*schema.ToolInfo, error) {
34+ return &schema.ToolInfo{
36+ Desc: `This is a tool for editing files. For moving or renaming files, you should generally use the Bash tool with the 'mv' command instead. For larger edits, use the Write tool to overwrite files. F.
38+Before using this tool:
40+1. Use the View tool to understand the file's contents and context
42+2. Verify the directory path is correct (only applicable when creating new files):
43+ - Use the LS tool to verify the parent directory exists and is the correct location
45+To make a file edit, provide the following:
46+1. file_path: The absolute path to the file to modify (must be absolute, not relative)
47+2. old_string: The text to replace (must be unique within the file, and must match the file contents exactly, including all whitespace and indentation)
48+3. new_string: The edited text to replace the old_string
50+The tool will replace ONE occurrence of old_string with new_string in the specified file.
52+CRITICAL REQUIREMENTS FOR USING THIS TOOL:
54+1. UNIQUENESS: The old_string MUST uniquely identify the specific instance you want to change. This means:
55+ - Include AT LEAST 3-5 lines of context BEFORE the change point
56+ - Include AT LEAST 3-5 lines of context AFTER the change point
57+ - Include all whitespace, indentation, and surrounding code exactly as it appears in the file
59+2. SINGLE INSTANCE: This tool can only change ONE instance at a time. If you need to change multiple instances:
60+ - Make separate calls to this tool for each instance
61+ - Each call must uniquely identify its specific instance using extensive context
63+3. VERIFICATION: Before using this tool:
64+ - Check how many instances of the target text exist in the file
65+ - If multiple instances exist, gather enough context to uniquely identify each one
66+ - Plan separate tool calls for each instance
68+WARNING: If you do not follow these requirements:
69+ - The tool will fail if old_string matches multiple locations
70+ - The tool will fail if old_string doesn't match exactly (including whitespace)
71+ - You may change the wrong instance if you don't include enough context
74+ - Ensure the edit results in idiomatic, correct code
75+ - Do not leave the code in a broken state
76+ - Always use absolute file paths (starting with /)
78+If you want to create a new file, use:
79+ - A new file path, including dir name if needed
80+ - An empty old_string
81+ - The new file's contents as new_string
83+Remember: when making multiple file edits in a row to the same file, you should prefer to send all edits in a single message with multiple calls to this tool, rather than multiple messages with a single call each.`,
84+ ParamsOneOf: schema.NewParamsOneOfByParams(map[string]*schema.ParameterInfo{
87+ Desc: "The absolute path to the file to modify",
92+ Desc: "The text to replace",
97+ Desc: "The text to replace it with",
104+func (b *editTool) InvokableRun(ctx context.Context, args string, opts ...tool.Option) (string, error) {
105+ var params EditParams
106+ if err := json.Unmarshal([]byte(args), ¶ms); err != nil {
110+ if params.FilePath == "" {
111+ return "", errors.New("file_path is required")
114+ if !filepath.IsAbs(params.FilePath) {
115+ return "", fmt.Errorf("file path must be absolute, got: %s", params.FilePath)
118+ if params.OldString == "" {
119+ return createNewFile(params.FilePath, params.NewString)
122+ if params.NewString == "" {
123+ return deleteContent(params.FilePath, params.OldString)
126+ return replaceContent(params.FilePath, params.OldString, params.NewString)
129+func createNewFile(filePath, content string) (string, error) {
130+ fileInfo, err := os.Stat(filePath)
132+ if fileInfo.IsDir() {
133+ return "", fmt.Errorf("path is a directory, not a file: %s", filePath)
135+ return "", fmt.Errorf("file already exists: %s. Use the Replace tool to overwrite an existing file", filePath)
136+ } else if !os.IsNotExist(err) {
137+ return "", fmt.Errorf("failed to access file: %w", err)
140+ dir := filepath.Dir(filePath)
141+ if err = os.MkdirAll(dir, 0o755); err != nil {
142+ return "", fmt.Errorf("failed to create parent directories: %w", err)
145+ p := permission.Default.Request(
146+ permission.CreatePermissionRequest{
147+ Path: filepath.Dir(filePath),
148+ ToolName: EditToolName,
150+ Description: fmt.Sprintf("Create file %s", filePath),
151+ Params: map[string]interface{}{
152+ "file_path": filePath,
158+ return "", fmt.Errorf("permission denied")
161+ err = os.WriteFile(filePath, []byte(content), 0o644)
163+ return "", fmt.Errorf("failed to write file: %w", err)
166+ recordFileWrite(filePath)
167+ recordFileRead(filePath)
169+ // result := FileEditResult{
170+ // FilePath: filePath,
174+ // Diff: generateDiff("", content),
177+ // resultJSON, err := json.Marshal(result)
179+ // return "", fmt.Errorf("failed to serialize result: %w", err)
182+ return "File created: " + filePath, nil
185+func deleteContent(filePath, oldString string) (string, error) {
186+ fileInfo, err := os.Stat(filePath)
188+ if os.IsNotExist(err) {
189+ return "", fmt.Errorf("file not found: %s", filePath)
191+ return "", fmt.Errorf("failed to access file: %w", err)
194+ if fileInfo.IsDir() {
195+ return "", fmt.Errorf("path is a directory, not a file: %s", filePath)
198+ if getLastReadTime(filePath).IsZero() {
199+ return "", fmt.Errorf("you must read the file before editing it. Use the View tool first")
202+ modTime := fileInfo.ModTime()
203+ lastRead := getLastReadTime(filePath)
204+ if modTime.After(lastRead) {
205+ return "", fmt.Errorf("file %s has been modified since it was last read (mod time: %s, last read: %s)",
206+ filePath, modTime.Format(time.RFC3339), lastRead.Format(time.RFC3339))
209+ content, err := os.ReadFile(filePath)
211+ return "", fmt.Errorf("failed to read file: %w", err)
214+ oldContent := string(content)
216+ index := strings.Index(oldContent, oldString)
218+ return "", fmt.Errorf("old_string not found in file. Make sure it matches exactly, including whitespace and line breaks")
221+ lastIndex := strings.LastIndex(oldContent, oldString)
222+ if index != lastIndex {
223+ return "", fmt.Errorf("old_string appears multiple times in the file. Please provide more context to ensure a unique match")
226+ newContent := oldContent[:index] + oldContent[index+len(oldString):]
228+ p := permission.Default.Request(
229+ permission.CreatePermissionRequest{
230+ Path: filepath.Dir(filePath),
231+ ToolName: EditToolName,
233+ Description: fmt.Sprintf("Delete content from file %s", filePath),
234+ Params: map[string]interface{}{
235+ "file_path": filePath,
241+ return "", fmt.Errorf("permission denied")
244+ err = os.WriteFile(filePath, []byte(newContent), 0o644)
246+ return "", fmt.Errorf("failed to write file: %w", err)
249+ recordFileWrite(filePath)
251+ // result := FileEditResult{
252+ // FilePath: filePath,
256+ // Diff: generateDiff(oldContent, newContent),
257+ // SnippetBefore: getContextSnippet(oldContent, index, len(oldString)),
258+ // SnippetAfter: getContextSnippet(newContent, index, 0),
261+ // resultJSON, err := json.Marshal(result)
263+ // return "", fmt.Errorf("failed to serialize result: %w", err)
266+ return "Content deleted from file: " + filePath, nil
269+func replaceContent(filePath, oldString, newString string) (string, error) {
270+ fileInfo, err := os.Stat(filePath)
272+ if os.IsNotExist(err) {
273+ return fmt.Sprintf("file not found: %s", filePath), nil
275+ return fmt.Sprintf("failed to access file: %s", err), nil
278+ if fileInfo.IsDir() {
279+ return fmt.Sprintf("path is a directory, not a file: %s", filePath), nil
282+ if getLastReadTime(filePath).IsZero() {
283+ return "you must read the file before editing it. Use the View tool first", nil
286+ modTime := fileInfo.ModTime()
287+ lastRead := getLastReadTime(filePath)
288+ if modTime.After(lastRead) {
289+ return fmt.Sprintf("file %s has been modified since it was last read (mod time: %s, last read: %s)",
290+ filePath, modTime.Format(time.RFC3339), lastRead.Format(time.RFC3339)), nil
293+ content, err := os.ReadFile(filePath)
295+ return fmt.Sprintf("failed to read file: %s", err), nil
298+ oldContent := string(content)
300+ index := strings.Index(oldContent, oldString)
302+ return "old_string not found in file. Make sure it matches exactly, including whitespace and line breaks", nil
305+ lastIndex := strings.LastIndex(oldContent, oldString)
306+ if index != lastIndex {
307+ return "old_string appears multiple times in the file. Please provide more context to ensure a unique match", nil
310+ newContent := oldContent[:index] + newString + oldContent[index+len(oldString):]
312+ p := permission.Default.Request(
313+ permission.CreatePermissionRequest{
314+ Path: filepath.Dir(filePath),
315+ ToolName: EditToolName,
317+ Description: fmt.Sprintf("Replace content in file %s", filePath),
318+ Params: map[string]interface{}{
319+ "file_path": filePath,
320+ "old_string": oldString,
321+ "new_string": newString,
326+ return "", fmt.Errorf("permission denied")
329+ err = os.WriteFile(filePath, []byte(newContent), 0o644)
331+ return fmt.Sprintf("failed to write file: %s", err), nil
334+ recordFileWrite(filePath)
336+ // result := FileEditResult{
337+ // FilePath: filePath,
341+ // Diff: generateDiff(oldContent, newContent),
342+ // SnippetBefore: getContextSnippet(oldContent, index, len(oldString)),
343+ // SnippetAfter: getContextSnippet(newContent, index, len(newString)),
346+ // resultJSON, err := json.Marshal(result)
348+ // return "", fmt.Errorf("failed to serialize result: %w", err)
351+ return "Content replaced in file: " + filePath, nil
354+func getContextSnippet(content string, position, length int) string {
357+ lines := strings.Split(content, "\n")
361+ for i, line := range lines {
362+ if currentPos <= position && position < currentPos+len(line)+1 {
366+ currentPos += len(line) + 1 // +1 for the newline
369+ startLine := max(0, lineIndex-contextLines)
370+ endLine := min(len(lines), lineIndex+contextLines+1)
372+ var snippetBuilder strings.Builder
373+ for i := startLine; i < endLine; i++ {
375+ snippetBuilder.WriteString(fmt.Sprintf("> %s\n", lines[i]))
377+ snippetBuilder.WriteString(fmt.Sprintf(" %s\n", lines[i]))
381+ return snippetBuilder.String()
384+func generateDiff(oldContent, newContent string) string {
385+ dmp := diffmatchpatch.New()
387+ diffs := dmp.DiffMain(oldContent, newContent, false)
389+ patches := dmp.PatchMake(oldContent, diffs)
390+ patchText := dmp.PatchToText(patches)
392+ if patchText == "" && (oldContent != newContent) {
393+ var result strings.Builder
395+ result.WriteString("@@ Diff @@\n")
396+ for _, diff := range diffs {
398+ case diffmatchpatch.DiffInsert:
399+ result.WriteString("+ " + diff.Text + "\n")
400+ case diffmatchpatch.DiffDelete:
401+ result.WriteString("- " + diff.Text + "\n")
402+ case diffmatchpatch.DiffEqual:
403+ if len(diff.Text) > 40 {
404+ result.WriteString(" " + diff.Text[:20] + "..." + diff.Text[len(diff.Text)-20:] + "\n")
406+ result.WriteString(" " + diff.Text + "\n")
410+ return result.String()
416+func NewEditTool(workingDir string) tool.InvokableTool {
418+ workingDir: workingDir,