edit.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. package tools
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "time"
  10. "github.com/kujtimiihoxha/termai/internal/config"
  11. "github.com/kujtimiihoxha/termai/internal/lsp"
  12. "github.com/kujtimiihoxha/termai/internal/permission"
  13. "github.com/sergi/go-diff/diffmatchpatch"
  14. )
  15. type editTool struct {
  16. lspClients map[string]*lsp.Client
  17. }
  18. const (
  19. EditToolName = "edit"
  20. )
  21. type EditParams struct {
  22. FilePath string `json:"file_path"`
  23. OldString string `json:"old_string"`
  24. NewString string `json:"new_string"`
  25. }
  26. type EditPermissionsParams struct {
  27. FilePath string `json:"file_path"`
  28. OldString string `json:"old_string"`
  29. NewString string `json:"new_string"`
  30. Diff string `json:"diff"`
  31. }
  32. func (e *editTool) Info() ToolInfo {
  33. return ToolInfo{
  34. Name: EditToolName,
  35. Description: editDescription(),
  36. Parameters: map[string]any{
  37. "file_path": map[string]any{
  38. "type": "string",
  39. "description": "The absolute path to the file to modify",
  40. },
  41. "old_string": map[string]any{
  42. "type": "string",
  43. "description": "The text to replace",
  44. },
  45. "new_string": map[string]any{
  46. "type": "string",
  47. "description": "The text to replace it with",
  48. },
  49. },
  50. Required: []string{"file_path", "old_string", "new_string"},
  51. }
  52. }
  53. // Run implements Tool.
  54. func (e *editTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
  55. var params EditParams
  56. if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
  57. return NewTextErrorResponse("invalid parameters"), nil
  58. }
  59. if params.FilePath == "" {
  60. return NewTextErrorResponse("file_path is required"), nil
  61. }
  62. if !filepath.IsAbs(params.FilePath) {
  63. wd := config.WorkingDirectory()
  64. params.FilePath = filepath.Join(wd, params.FilePath)
  65. }
  66. notifyLspOpenFile(ctx, params.FilePath, e.lspClients)
  67. if params.OldString == "" {
  68. result, err := createNewFile(params.FilePath, params.NewString)
  69. if err != nil {
  70. return NewTextErrorResponse(fmt.Sprintf("error creating file: %s", err)), nil
  71. }
  72. return NewTextResponse(result), nil
  73. }
  74. if params.NewString == "" {
  75. result, err := deleteContent(params.FilePath, params.OldString)
  76. if err != nil {
  77. return NewTextErrorResponse(fmt.Sprintf("error deleting content: %s", err)), nil
  78. }
  79. return NewTextResponse(result), nil
  80. }
  81. result, err := replaceContent(params.FilePath, params.OldString, params.NewString)
  82. if err != nil {
  83. return NewTextErrorResponse(fmt.Sprintf("error replacing content: %s", err)), nil
  84. }
  85. result = fmt.Sprintf("<result>\n%s\n</result>\n", result)
  86. result += appendDiagnostics(params.FilePath, e.lspClients)
  87. return NewTextResponse(result), nil
  88. }
  89. func createNewFile(filePath, content string) (string, error) {
  90. fileInfo, err := os.Stat(filePath)
  91. if err == nil {
  92. if fileInfo.IsDir() {
  93. return "", fmt.Errorf("path is a directory, not a file: %s", filePath)
  94. }
  95. return "", fmt.Errorf("file already exists: %s. Use the Replace tool to overwrite an existing file", filePath)
  96. } else if !os.IsNotExist(err) {
  97. return "", fmt.Errorf("failed to access file: %w", err)
  98. }
  99. dir := filepath.Dir(filePath)
  100. if err = os.MkdirAll(dir, 0o755); err != nil {
  101. return "", fmt.Errorf("failed to create parent directories: %w", err)
  102. }
  103. p := permission.Default.Request(
  104. permission.CreatePermissionRequest{
  105. Path: filepath.Dir(filePath),
  106. ToolName: EditToolName,
  107. Action: "create",
  108. Description: fmt.Sprintf("Create file %s", filePath),
  109. Params: EditPermissionsParams{
  110. FilePath: filePath,
  111. OldString: "",
  112. NewString: content,
  113. Diff: GenerateDiff("", content),
  114. },
  115. },
  116. )
  117. if !p {
  118. return "", fmt.Errorf("permission denied")
  119. }
  120. err = os.WriteFile(filePath, []byte(content), 0o644)
  121. if err != nil {
  122. return "", fmt.Errorf("failed to write file: %w", err)
  123. }
  124. recordFileWrite(filePath)
  125. recordFileRead(filePath)
  126. return "File created: " + filePath, nil
  127. }
  128. func deleteContent(filePath, oldString string) (string, error) {
  129. fileInfo, err := os.Stat(filePath)
  130. if err != nil {
  131. if os.IsNotExist(err) {
  132. return "", fmt.Errorf("file not found: %s", filePath)
  133. }
  134. return "", fmt.Errorf("failed to access file: %w", err)
  135. }
  136. if fileInfo.IsDir() {
  137. return "", fmt.Errorf("path is a directory, not a file: %s", filePath)
  138. }
  139. if getLastReadTime(filePath).IsZero() {
  140. return "", fmt.Errorf("you must read the file before editing it. Use the View tool first")
  141. }
  142. modTime := fileInfo.ModTime()
  143. lastRead := getLastReadTime(filePath)
  144. if modTime.After(lastRead) {
  145. return "", fmt.Errorf("file %s has been modified since it was last read (mod time: %s, last read: %s)",
  146. filePath, modTime.Format(time.RFC3339), lastRead.Format(time.RFC3339))
  147. }
  148. content, err := os.ReadFile(filePath)
  149. if err != nil {
  150. return "", fmt.Errorf("failed to read file: %w", err)
  151. }
  152. oldContent := string(content)
  153. index := strings.Index(oldContent, oldString)
  154. if index == -1 {
  155. return "", fmt.Errorf("old_string not found in file. Make sure it matches exactly, including whitespace and line breaks")
  156. }
  157. lastIndex := strings.LastIndex(oldContent, oldString)
  158. if index != lastIndex {
  159. return "", fmt.Errorf("old_string appears multiple times in the file. Please provide more context to ensure a unique match")
  160. }
  161. newContent := oldContent[:index] + oldContent[index+len(oldString):]
  162. p := permission.Default.Request(
  163. permission.CreatePermissionRequest{
  164. Path: filepath.Dir(filePath),
  165. ToolName: EditToolName,
  166. Action: "delete",
  167. Description: fmt.Sprintf("Delete content from file %s", filePath),
  168. Params: EditPermissionsParams{
  169. FilePath: filePath,
  170. OldString: oldString,
  171. NewString: "",
  172. Diff: GenerateDiff(oldContent, newContent),
  173. },
  174. },
  175. )
  176. if !p {
  177. return "", fmt.Errorf("permission denied")
  178. }
  179. err = os.WriteFile(filePath, []byte(newContent), 0o644)
  180. if err != nil {
  181. return "", fmt.Errorf("failed to write file: %w", err)
  182. }
  183. recordFileWrite(filePath)
  184. recordFileRead(filePath)
  185. return "Content deleted from file: " + filePath, nil
  186. }
  187. func replaceContent(filePath, oldString, newString string) (string, error) {
  188. fileInfo, err := os.Stat(filePath)
  189. if err != nil {
  190. if os.IsNotExist(err) {
  191. return "", fmt.Errorf("file not found: %s", filePath)
  192. }
  193. return "", fmt.Errorf("failed to access file: %w", err)
  194. }
  195. if fileInfo.IsDir() {
  196. return "", fmt.Errorf("path is a directory, not a file: %s", filePath)
  197. }
  198. if getLastReadTime(filePath).IsZero() {
  199. return "", fmt.Errorf("you must read the file before editing it. Use the View tool first")
  200. }
  201. modTime := fileInfo.ModTime()
  202. lastRead := getLastReadTime(filePath)
  203. if modTime.After(lastRead) {
  204. return "", fmt.Errorf("file %s has been modified since it was last read (mod time: %s, last read: %s)",
  205. filePath, modTime.Format(time.RFC3339), lastRead.Format(time.RFC3339))
  206. }
  207. content, err := os.ReadFile(filePath)
  208. if err != nil {
  209. return "", fmt.Errorf("failed to read file: %w", err)
  210. }
  211. oldContent := string(content)
  212. index := strings.Index(oldContent, oldString)
  213. if index == -1 {
  214. return "", fmt.Errorf("old_string not found in file. Make sure it matches exactly, including whitespace and line breaks")
  215. }
  216. lastIndex := strings.LastIndex(oldContent, oldString)
  217. if index != lastIndex {
  218. return "", fmt.Errorf("old_string appears multiple times in the file. Please provide more context to ensure a unique match")
  219. }
  220. newContent := oldContent[:index] + newString + oldContent[index+len(oldString):]
  221. diff := GenerateDiff(oldString, newContent)
  222. p := permission.Default.Request(
  223. permission.CreatePermissionRequest{
  224. Path: filepath.Dir(filePath),
  225. ToolName: EditToolName,
  226. Action: "replace",
  227. Description: fmt.Sprintf("Replace content in file %s", filePath),
  228. Params: EditPermissionsParams{
  229. FilePath: filePath,
  230. OldString: oldString,
  231. NewString: newString,
  232. Diff: diff,
  233. },
  234. },
  235. )
  236. if !p {
  237. return "", fmt.Errorf("permission denied")
  238. }
  239. err = os.WriteFile(filePath, []byte(newContent), 0o644)
  240. if err != nil {
  241. return "", fmt.Errorf("failed to write file: %w", err)
  242. }
  243. recordFileWrite(filePath)
  244. recordFileRead(filePath)
  245. return "Content replaced in file: " + filePath, nil
  246. }
  247. func GenerateDiff(oldContent, newContent string) string {
  248. dmp := diffmatchpatch.New()
  249. fileAdmp, fileBdmp, dmpStrings := dmp.DiffLinesToChars(oldContent, newContent)
  250. diffs := dmp.DiffMain(fileAdmp, fileBdmp, false)
  251. diffs = dmp.DiffCharsToLines(diffs, dmpStrings)
  252. diffs = dmp.DiffCleanupSemantic(diffs)
  253. buff := strings.Builder{}
  254. for _, diff := range diffs {
  255. text := diff.Text
  256. switch diff.Type {
  257. case diffmatchpatch.DiffInsert:
  258. for line := range strings.SplitSeq(text, "\n") {
  259. _, _ = buff.WriteString("+ " + line + "\n")
  260. }
  261. case diffmatchpatch.DiffDelete:
  262. for line := range strings.SplitSeq(text, "\n") {
  263. _, _ = buff.WriteString("- " + line + "\n")
  264. }
  265. case diffmatchpatch.DiffEqual:
  266. if len(text) > 40 {
  267. _, _ = buff.WriteString(" " + text[:20] + "..." + text[len(text)-20:] + "\n")
  268. } else {
  269. for line := range strings.SplitSeq(text, "\n") {
  270. _, _ = buff.WriteString(" " + line + "\n")
  271. }
  272. }
  273. }
  274. }
  275. return buff.String()
  276. }
  277. func editDescription() string {
  278. return `Edits files by replacing text, creating new files, or deleting content. For moving or renaming files, use the Bash tool with the 'mv' command instead. For larger file edits, use the FileWrite tool to overwrite files.
  279. Before using this tool:
  280. 1. Use the FileRead tool to understand the file's contents and context
  281. 2. Verify the directory path is correct (only applicable when creating new files):
  282. - Use the LS tool to verify the parent directory exists and is the correct location
  283. To make a file edit, provide the following:
  284. 1. file_path: The absolute path to the file to modify (must be absolute, not relative)
  285. 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)
  286. 3. new_string: The edited text to replace the old_string
  287. Special cases:
  288. - To create a new file: provide file_path and new_string, leave old_string empty
  289. - To delete content: provide file_path and old_string, leave new_string empty
  290. The tool will replace ONE occurrence of old_string with new_string in the specified file.
  291. CRITICAL REQUIREMENTS FOR USING THIS TOOL:
  292. 1. UNIQUENESS: The old_string MUST uniquely identify the specific instance you want to change. This means:
  293. - Include AT LEAST 3-5 lines of context BEFORE the change point
  294. - Include AT LEAST 3-5 lines of context AFTER the change point
  295. - Include all whitespace, indentation, and surrounding code exactly as it appears in the file
  296. 2. SINGLE INSTANCE: This tool can only change ONE instance at a time. If you need to change multiple instances:
  297. - Make separate calls to this tool for each instance
  298. - Each call must uniquely identify its specific instance using extensive context
  299. 3. VERIFICATION: Before using this tool:
  300. - Check how many instances of the target text exist in the file
  301. - If multiple instances exist, gather enough context to uniquely identify each one
  302. - Plan separate tool calls for each instance
  303. WARNING: If you do not follow these requirements:
  304. - The tool will fail if old_string matches multiple locations
  305. - The tool will fail if old_string doesn't match exactly (including whitespace)
  306. - You may change the wrong instance if you don't include enough context
  307. When making edits:
  308. - Ensure the edit results in idiomatic, correct code
  309. - Do not leave the code in a broken state
  310. - Always use absolute file paths (starting with /)
  311. 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.`
  312. }
  313. func NewEditTool(lspClients map[string]*lsp.Client) BaseTool {
  314. return &editTool{
  315. lspClients,
  316. }
  317. }