edit.go 17 KB

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