edit.go 12 KB

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