edit.go 12 KB

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