edit.go 15 KB

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