edit.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. package tools
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "time"
  10. "github.com/charmbracelet/crush/internal/config"
  11. "github.com/charmbracelet/crush/internal/diff"
  12. "github.com/charmbracelet/crush/internal/history"
  13. "github.com/charmbracelet/crush/internal/logging"
  14. "github.com/charmbracelet/crush/internal/lsp"
  15. "github.com/charmbracelet/crush/internal/permission"
  16. )
  17. type EditParams struct {
  18. FilePath string `json:"file_path"`
  19. OldString string `json:"old_string"`
  20. NewString string `json:"new_string"`
  21. }
  22. type EditPermissionsParams struct {
  23. FilePath string `json:"file_path"`
  24. OldContent string `json:"old_content,omitempty"`
  25. NewContent string `json:"new_content,omitempty"`
  26. }
  27. type EditResponseMetadata struct {
  28. Additions int `json:"additions"`
  29. Removals int `json:"removals"`
  30. OldContent string `json:"old_content,omitempty"`
  31. NewContent string `json:"new_content,omitempty"`
  32. }
  33. type editTool struct {
  34. lspClients map[string]*lsp.Client
  35. permissions permission.Service
  36. files history.Service
  37. }
  38. const (
  39. EditToolName = "edit"
  40. 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.
  41. Before using this tool:
  42. 1. Use the FileRead tool to understand the file's contents and context
  43. 2. Verify the directory path is correct (only applicable when creating new files):
  44. - 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
  49. Special cases:
  50. - To create a new file: provide file_path and new_string, leave old_string empty
  51. - To delete content: provide file_path and old_string, leave new_string empty
  52. The tool will replace ONE occurrence of old_string with new_string in the specified file.
  53. 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
  58. 2. SINGLE INSTANCE: This tool can only change ONE instance at a time. If you need to change multiple instances:
  59. - Make separate calls to this tool for each instance
  60. - Each call must uniquely identify its specific instance using extensive context
  61. 3. VERIFICATION: Before using this tool:
  62. - Check how many instances of the target text exist in the file
  63. - If multiple instances exist, gather enough context to uniquely identify each one
  64. - Plan separate tool calls for each instance
  65. WARNING: If you do not follow these requirements:
  66. - The tool will fail if old_string matches multiple locations
  67. - The tool will fail if old_string doesn't match exactly (including whitespace)
  68. - You may change the wrong instance if you don't include enough context
  69. When making edits:
  70. - Ensure the edit results in idiomatic, correct code
  71. - Do not leave the code in a broken state
  72. - Always use absolute file paths (starting with /)
  73. 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.`
  74. )
  75. func NewEditTool(lspClients map[string]*lsp.Client, permissions permission.Service, files history.Service) BaseTool {
  76. return &editTool{
  77. lspClients: lspClients,
  78. permissions: permissions,
  79. files: files,
  80. }
  81. }
  82. func (e *editTool) Info() ToolInfo {
  83. return ToolInfo{
  84. Name: EditToolName,
  85. Description: editDescription,
  86. Parameters: map[string]any{
  87. "file_path": map[string]any{
  88. "type": "string",
  89. "description": "The absolute path to the file to modify",
  90. },
  91. "old_string": map[string]any{
  92. "type": "string",
  93. "description": "The text to replace",
  94. },
  95. "new_string": map[string]any{
  96. "type": "string",
  97. "description": "The text to replace it with",
  98. },
  99. },
  100. Required: []string{"file_path", "old_string", "new_string"},
  101. }
  102. }
  103. func (e *editTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
  104. var params EditParams
  105. if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
  106. return NewTextErrorResponse("invalid parameters"), nil
  107. }
  108. if params.FilePath == "" {
  109. return NewTextErrorResponse("file_path is required"), nil
  110. }
  111. if !filepath.IsAbs(params.FilePath) {
  112. wd := config.WorkingDirectory()
  113. params.FilePath = filepath.Join(wd, params.FilePath)
  114. }
  115. var response ToolResponse
  116. var err error
  117. if params.OldString == "" {
  118. response, err = e.createNewFile(ctx, params.FilePath, params.NewString)
  119. if err != nil {
  120. return response, err
  121. }
  122. }
  123. if params.NewString == "" {
  124. response, err = e.deleteContent(ctx, params.FilePath, params.OldString)
  125. if err != nil {
  126. return response, err
  127. }
  128. }
  129. response, err = e.replaceContent(ctx, params.FilePath, params.OldString, params.NewString)
  130. if err != nil {
  131. return response, err
  132. }
  133. if response.IsError {
  134. // Return early if there was an error during content replacement
  135. // This prevents unnecessary LSP diagnostics processing
  136. return response, nil
  137. }
  138. waitForLspDiagnostics(ctx, params.FilePath, e.lspClients)
  139. text := fmt.Sprintf("<result>\n%s\n</result>\n", response.Content)
  140. text += getDiagnostics(params.FilePath, e.lspClients)
  141. response.Content = text
  142. return response, nil
  143. }
  144. func (e *editTool) createNewFile(ctx context.Context, filePath, content string) (ToolResponse, error) {
  145. fileInfo, err := os.Stat(filePath)
  146. if err == nil {
  147. if fileInfo.IsDir() {
  148. return NewTextErrorResponse(fmt.Sprintf("path is a directory, not a file: %s", filePath)), nil
  149. }
  150. return NewTextErrorResponse(fmt.Sprintf("file already exists: %s", filePath)), nil
  151. } else if !os.IsNotExist(err) {
  152. return ToolResponse{}, fmt.Errorf("failed to access file: %w", err)
  153. }
  154. dir := filepath.Dir(filePath)
  155. if err = os.MkdirAll(dir, 0o755); err != nil {
  156. return ToolResponse{}, fmt.Errorf("failed to create parent directories: %w", err)
  157. }
  158. sessionID, messageID := GetContextValues(ctx)
  159. if sessionID == "" || messageID == "" {
  160. return ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a new file")
  161. }
  162. _, additions, removals := diff.GenerateDiff(
  163. "",
  164. content,
  165. filePath,
  166. )
  167. rootDir := config.WorkingDirectory()
  168. permissionPath := filepath.Dir(filePath)
  169. if strings.HasPrefix(filePath, rootDir) {
  170. permissionPath = rootDir
  171. }
  172. p := e.permissions.Request(
  173. permission.CreatePermissionRequest{
  174. SessionID: sessionID,
  175. Path: permissionPath,
  176. ToolName: EditToolName,
  177. Action: "write",
  178. Description: fmt.Sprintf("Create file %s", filePath),
  179. Params: EditPermissionsParams{
  180. FilePath: filePath,
  181. OldContent: "",
  182. NewContent: content,
  183. },
  184. },
  185. )
  186. if !p {
  187. return ToolResponse{}, permission.ErrorPermissionDenied
  188. }
  189. err = os.WriteFile(filePath, []byte(content), 0o644)
  190. if err != nil {
  191. return ToolResponse{}, fmt.Errorf("failed to write file: %w", err)
  192. }
  193. // File can't be in the history so we create a new file history
  194. _, err = e.files.Create(ctx, sessionID, filePath, "")
  195. if err != nil {
  196. // Log error but don't fail the operation
  197. return ToolResponse{}, fmt.Errorf("error creating file history: %w", err)
  198. }
  199. // Add the new content to the file history
  200. _, err = e.files.CreateVersion(ctx, sessionID, filePath, content)
  201. if err != nil {
  202. // Log error but don't fail the operation
  203. logging.Debug("Error creating file history version", "error", err)
  204. }
  205. recordFileWrite(filePath)
  206. recordFileRead(filePath)
  207. return WithResponseMetadata(
  208. NewTextResponse("File created: "+filePath),
  209. EditResponseMetadata{
  210. OldContent: "",
  211. NewContent: content,
  212. Additions: additions,
  213. Removals: removals,
  214. },
  215. ), nil
  216. }
  217. func (e *editTool) deleteContent(ctx context.Context, filePath, oldString string) (ToolResponse, error) {
  218. fileInfo, err := os.Stat(filePath)
  219. if err != nil {
  220. if os.IsNotExist(err) {
  221. return NewTextErrorResponse(fmt.Sprintf("file not found: %s", filePath)), nil
  222. }
  223. return ToolResponse{}, fmt.Errorf("failed to access file: %w", err)
  224. }
  225. if fileInfo.IsDir() {
  226. return NewTextErrorResponse(fmt.Sprintf("path is a directory, not a file: %s", filePath)), nil
  227. }
  228. if getLastReadTime(filePath).IsZero() {
  229. return NewTextErrorResponse("you must read the file before editing it. Use the View tool first"), nil
  230. }
  231. modTime := fileInfo.ModTime()
  232. lastRead := getLastReadTime(filePath)
  233. if modTime.After(lastRead) {
  234. return NewTextErrorResponse(
  235. fmt.Sprintf("file %s has been modified since it was last read (mod time: %s, last read: %s)",
  236. filePath, modTime.Format(time.RFC3339), lastRead.Format(time.RFC3339),
  237. )), nil
  238. }
  239. content, err := os.ReadFile(filePath)
  240. if err != nil {
  241. return ToolResponse{}, fmt.Errorf("failed to read file: %w", err)
  242. }
  243. oldContent := string(content)
  244. index := strings.Index(oldContent, oldString)
  245. if index == -1 {
  246. return NewTextErrorResponse("old_string not found in file. Make sure it matches exactly, including whitespace and line breaks"), nil
  247. }
  248. lastIndex := strings.LastIndex(oldContent, oldString)
  249. if index != lastIndex {
  250. return NewTextErrorResponse("old_string appears multiple times in the file. Please provide more context to ensure a unique match"), nil
  251. }
  252. newContent := oldContent[:index] + oldContent[index+len(oldString):]
  253. sessionID, messageID := GetContextValues(ctx)
  254. if sessionID == "" || messageID == "" {
  255. return ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a new file")
  256. }
  257. _, additions, removals := diff.GenerateDiff(
  258. oldContent,
  259. newContent,
  260. filePath,
  261. )
  262. rootDir := config.WorkingDirectory()
  263. permissionPath := filepath.Dir(filePath)
  264. if strings.HasPrefix(filePath, rootDir) {
  265. permissionPath = rootDir
  266. }
  267. p := e.permissions.Request(
  268. permission.CreatePermissionRequest{
  269. SessionID: sessionID,
  270. Path: permissionPath,
  271. ToolName: EditToolName,
  272. Action: "write",
  273. Description: fmt.Sprintf("Delete content from file %s", filePath),
  274. Params: EditPermissionsParams{
  275. FilePath: filePath,
  276. OldContent: oldContent,
  277. NewContent: newContent,
  278. },
  279. },
  280. )
  281. if !p {
  282. return ToolResponse{}, permission.ErrorPermissionDenied
  283. }
  284. err = os.WriteFile(filePath, []byte(newContent), 0o644)
  285. if err != nil {
  286. return ToolResponse{}, fmt.Errorf("failed to write file: %w", err)
  287. }
  288. // Check if file exists in history
  289. file, err := e.files.GetByPathAndSession(ctx, filePath, sessionID)
  290. if err != nil {
  291. _, err = e.files.Create(ctx, sessionID, filePath, oldContent)
  292. if err != nil {
  293. // Log error but don't fail the operation
  294. return ToolResponse{}, fmt.Errorf("error creating file history: %w", err)
  295. }
  296. }
  297. if file.Content != oldContent {
  298. // User Manually changed the content store an intermediate version
  299. _, err = e.files.CreateVersion(ctx, sessionID, filePath, oldContent)
  300. if err != nil {
  301. logging.Debug("Error creating file history version", "error", err)
  302. }
  303. }
  304. // Store the new version
  305. _, err = e.files.CreateVersion(ctx, sessionID, filePath, "")
  306. if err != nil {
  307. logging.Debug("Error creating file history version", "error", err)
  308. }
  309. recordFileWrite(filePath)
  310. recordFileRead(filePath)
  311. return WithResponseMetadata(
  312. NewTextResponse("Content deleted from file: "+filePath),
  313. EditResponseMetadata{
  314. OldContent: oldContent,
  315. NewContent: newContent,
  316. Additions: additions,
  317. Removals: removals,
  318. },
  319. ), nil
  320. }
  321. func (e *editTool) replaceContent(ctx context.Context, filePath, oldString, newString string) (ToolResponse, error) {
  322. fileInfo, err := os.Stat(filePath)
  323. if err != nil {
  324. if os.IsNotExist(err) {
  325. return NewTextErrorResponse(fmt.Sprintf("file not found: %s", filePath)), nil
  326. }
  327. return ToolResponse{}, fmt.Errorf("failed to access file: %w", err)
  328. }
  329. if fileInfo.IsDir() {
  330. return NewTextErrorResponse(fmt.Sprintf("path is a directory, not a file: %s", filePath)), nil
  331. }
  332. if getLastReadTime(filePath).IsZero() {
  333. return NewTextErrorResponse("you must read the file before editing it. Use the View tool first"), nil
  334. }
  335. modTime := fileInfo.ModTime()
  336. lastRead := getLastReadTime(filePath)
  337. if modTime.After(lastRead) {
  338. return NewTextErrorResponse(
  339. fmt.Sprintf("file %s has been modified since it was last read (mod time: %s, last read: %s)",
  340. filePath, modTime.Format(time.RFC3339), lastRead.Format(time.RFC3339),
  341. )), nil
  342. }
  343. content, err := os.ReadFile(filePath)
  344. if err != nil {
  345. return ToolResponse{}, fmt.Errorf("failed to read file: %w", err)
  346. }
  347. oldContent := string(content)
  348. index := strings.Index(oldContent, oldString)
  349. if index == -1 {
  350. return NewTextErrorResponse("old_string not found in file. Make sure it matches exactly, including whitespace and line breaks"), nil
  351. }
  352. lastIndex := strings.LastIndex(oldContent, oldString)
  353. if index != lastIndex {
  354. return NewTextErrorResponse("old_string appears multiple times in the file. Please provide more context to ensure a unique match"), nil
  355. }
  356. newContent := oldContent[:index] + newString + oldContent[index+len(oldString):]
  357. if oldContent == newContent {
  358. return NewTextErrorResponse("new content is the same as old content. No changes made."), nil
  359. }
  360. sessionID, messageID := GetContextValues(ctx)
  361. if sessionID == "" || messageID == "" {
  362. return ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a new file")
  363. }
  364. _, additions, removals := diff.GenerateDiff(
  365. oldContent,
  366. newContent,
  367. filePath,
  368. )
  369. rootDir := config.WorkingDirectory()
  370. permissionPath := filepath.Dir(filePath)
  371. if strings.HasPrefix(filePath, rootDir) {
  372. permissionPath = rootDir
  373. }
  374. p := e.permissions.Request(
  375. permission.CreatePermissionRequest{
  376. SessionID: sessionID,
  377. Path: permissionPath,
  378. ToolName: EditToolName,
  379. Action: "write",
  380. Description: fmt.Sprintf("Replace content in file %s", filePath),
  381. Params: EditPermissionsParams{
  382. FilePath: filePath,
  383. OldContent: oldContent,
  384. NewContent: newContent,
  385. },
  386. },
  387. )
  388. if !p {
  389. return ToolResponse{}, permission.ErrorPermissionDenied
  390. }
  391. err = os.WriteFile(filePath, []byte(newContent), 0o644)
  392. if err != nil {
  393. return ToolResponse{}, fmt.Errorf("failed to write file: %w", err)
  394. }
  395. // Check if file exists in history
  396. file, err := e.files.GetByPathAndSession(ctx, filePath, sessionID)
  397. if err != nil {
  398. _, err = e.files.Create(ctx, sessionID, filePath, oldContent)
  399. if err != nil {
  400. // Log error but don't fail the operation
  401. return ToolResponse{}, fmt.Errorf("error creating file history: %w", err)
  402. }
  403. }
  404. if file.Content != oldContent {
  405. // User Manually changed the content store an intermediate version
  406. _, err = e.files.CreateVersion(ctx, sessionID, filePath, oldContent)
  407. if err != nil {
  408. logging.Debug("Error creating file history version", "error", err)
  409. }
  410. }
  411. // Store the new version
  412. _, err = e.files.CreateVersion(ctx, sessionID, filePath, newContent)
  413. if err != nil {
  414. logging.Debug("Error creating file history version", "error", err)
  415. }
  416. recordFileWrite(filePath)
  417. recordFileRead(filePath)
  418. return WithResponseMetadata(
  419. NewTextResponse("Content replaced in file: "+filePath),
  420. EditResponseMetadata{
  421. OldContent: oldContent,
  422. NewContent: newContent,
  423. Additions: additions,
  424. Removals: removals,
  425. }), nil
  426. }