edit.go 15 KB

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