edit.go 12 KB

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