patch.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. package tools
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "time"
  9. "github.com/sst/opencode/internal/config"
  10. "github.com/sst/opencode/internal/diff"
  11. "github.com/sst/opencode/internal/history"
  12. "github.com/sst/opencode/internal/lsp"
  13. "github.com/sst/opencode/internal/permission"
  14. "log/slog"
  15. )
  16. type PatchParams struct {
  17. PatchText string `json:"patch_text"`
  18. }
  19. type PatchResponseMetadata struct {
  20. FilesChanged []string `json:"files_changed"`
  21. Additions int `json:"additions"`
  22. Removals int `json:"removals"`
  23. }
  24. type patchTool struct {
  25. lspClients map[string]*lsp.Client
  26. permissions permission.Service
  27. files history.Service
  28. }
  29. const (
  30. PatchToolName = "patch"
  31. patchDescription = `Applies a patch to multiple files in one operation. This tool is useful for making coordinated changes across multiple files.
  32. The patch text must follow this format:
  33. *** Begin Patch
  34. *** Update File: /path/to/file
  35. @@ Context line (unique within the file)
  36. Line to keep
  37. -Line to remove
  38. +Line to add
  39. Line to keep
  40. *** Add File: /path/to/new/file
  41. +Content of the new file
  42. +More content
  43. *** Delete File: /path/to/file/to/delete
  44. *** End Patch
  45. Before using this tool:
  46. 1. Use the FileRead tool to understand the files' contents and context
  47. 2. Verify all file paths are correct (use the LS tool)
  48. CRITICAL REQUIREMENTS FOR USING THIS TOOL:
  49. 1. UNIQUENESS: Context lines MUST uniquely identify the specific sections you want to change
  50. 2. PRECISION: All whitespace, indentation, and surrounding code must match exactly
  51. 3. VALIDATION: Ensure edits result in idiomatic, correct code
  52. 4. PATHS: Always use absolute file paths (starting with /)
  53. The tool will apply all changes in a single atomic operation.`
  54. )
  55. func NewPatchTool(lspClients map[string]*lsp.Client, permissions permission.Service, files history.Service) BaseTool {
  56. return &patchTool{
  57. lspClients: lspClients,
  58. permissions: permissions,
  59. files: files,
  60. }
  61. }
  62. func (p *patchTool) Info() ToolInfo {
  63. return ToolInfo{
  64. Name: PatchToolName,
  65. Description: patchDescription,
  66. Parameters: map[string]any{
  67. "patch_text": map[string]any{
  68. "type": "string",
  69. "description": "The full patch text that describes all changes to be made",
  70. },
  71. },
  72. Required: []string{"patch_text"},
  73. }
  74. }
  75. func (p *patchTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
  76. var params PatchParams
  77. if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
  78. return NewTextErrorResponse("invalid parameters"), nil
  79. }
  80. if params.PatchText == "" {
  81. return NewTextErrorResponse("patch_text is required"), nil
  82. }
  83. // Identify all files needed for the patch and verify they've been read
  84. filesToRead := diff.IdentifyFilesNeeded(params.PatchText)
  85. for _, filePath := range filesToRead {
  86. absPath := filePath
  87. if !filepath.IsAbs(absPath) {
  88. wd := config.WorkingDirectory()
  89. absPath = filepath.Join(wd, absPath)
  90. }
  91. if getLastReadTime(absPath).IsZero() {
  92. return NewTextErrorResponse(fmt.Sprintf("you must read the file %s before patching it. Use the FileRead tool first", filePath)), nil
  93. }
  94. fileInfo, err := os.Stat(absPath)
  95. if err != nil {
  96. if os.IsNotExist(err) {
  97. return NewTextErrorResponse(fmt.Sprintf("file not found: %s", absPath)), nil
  98. }
  99. return ToolResponse{}, fmt.Errorf("failed to access file: %w", err)
  100. }
  101. if fileInfo.IsDir() {
  102. return NewTextErrorResponse(fmt.Sprintf("path is a directory, not a file: %s", absPath)), nil
  103. }
  104. modTime := fileInfo.ModTime()
  105. lastRead := getLastReadTime(absPath)
  106. if modTime.After(lastRead) {
  107. return NewTextErrorResponse(
  108. fmt.Sprintf("file %s has been modified since it was last read (mod time: %s, last read: %s)",
  109. absPath, modTime.Format(time.RFC3339), lastRead.Format(time.RFC3339),
  110. )), nil
  111. }
  112. }
  113. // Check for new files to ensure they don't already exist
  114. filesToAdd := diff.IdentifyFilesAdded(params.PatchText)
  115. for _, filePath := range filesToAdd {
  116. absPath := filePath
  117. if !filepath.IsAbs(absPath) {
  118. wd := config.WorkingDirectory()
  119. absPath = filepath.Join(wd, absPath)
  120. }
  121. _, err := os.Stat(absPath)
  122. if err == nil {
  123. return NewTextErrorResponse(fmt.Sprintf("file already exists and cannot be added: %s", absPath)), nil
  124. } else if !os.IsNotExist(err) {
  125. return ToolResponse{}, fmt.Errorf("failed to check file: %w", err)
  126. }
  127. }
  128. // Load all required files
  129. currentFiles := make(map[string]string)
  130. for _, filePath := range filesToRead {
  131. absPath := filePath
  132. if !filepath.IsAbs(absPath) {
  133. wd := config.WorkingDirectory()
  134. absPath = filepath.Join(wd, absPath)
  135. }
  136. content, err := os.ReadFile(absPath)
  137. if err != nil {
  138. return ToolResponse{}, fmt.Errorf("failed to read file %s: %w", absPath, err)
  139. }
  140. currentFiles[filePath] = string(content)
  141. }
  142. // Process the patch
  143. patch, fuzz, err := diff.TextToPatch(params.PatchText, currentFiles)
  144. if err != nil {
  145. return NewTextErrorResponse(fmt.Sprintf("failed to parse patch: %s", err)), nil
  146. }
  147. if fuzz > 3 {
  148. return NewTextErrorResponse(fmt.Sprintf("patch contains fuzzy matches (fuzz level: %d). Please make your context lines more precise", fuzz)), nil
  149. }
  150. // Convert patch to commit
  151. commit, err := diff.PatchToCommit(patch, currentFiles)
  152. if err != nil {
  153. return NewTextErrorResponse(fmt.Sprintf("failed to create commit from patch: %s", err)), nil
  154. }
  155. // Get session ID and message ID
  156. sessionID, messageID := GetContextValues(ctx)
  157. if sessionID == "" || messageID == "" {
  158. return ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a patch")
  159. }
  160. // Request permission for all changes
  161. for path, change := range commit.Changes {
  162. switch change.Type {
  163. case diff.ActionAdd:
  164. dir := filepath.Dir(path)
  165. patchDiff, _, _ := diff.GenerateDiff("", *change.NewContent, path)
  166. p := p.permissions.Request(
  167. ctx,
  168. permission.CreatePermissionRequest{
  169. SessionID: sessionID,
  170. Path: dir,
  171. ToolName: PatchToolName,
  172. Action: "create",
  173. Description: fmt.Sprintf("Create file %s", path),
  174. Params: EditPermissionsParams{
  175. FilePath: path,
  176. Diff: patchDiff,
  177. },
  178. },
  179. )
  180. if !p {
  181. return ToolResponse{}, permission.ErrorPermissionDenied
  182. }
  183. case diff.ActionUpdate:
  184. currentContent := ""
  185. if change.OldContent != nil {
  186. currentContent = *change.OldContent
  187. }
  188. newContent := ""
  189. if change.NewContent != nil {
  190. newContent = *change.NewContent
  191. }
  192. patchDiff, _, _ := diff.GenerateDiff(currentContent, newContent, path)
  193. dir := filepath.Dir(path)
  194. p := p.permissions.Request(
  195. ctx,
  196. permission.CreatePermissionRequest{
  197. SessionID: sessionID,
  198. Path: dir,
  199. ToolName: PatchToolName,
  200. Action: "update",
  201. Description: fmt.Sprintf("Update file %s", path),
  202. Params: EditPermissionsParams{
  203. FilePath: path,
  204. Diff: patchDiff,
  205. },
  206. },
  207. )
  208. if !p {
  209. return ToolResponse{}, permission.ErrorPermissionDenied
  210. }
  211. case diff.ActionDelete:
  212. dir := filepath.Dir(path)
  213. patchDiff, _, _ := diff.GenerateDiff(*change.OldContent, "", path)
  214. p := p.permissions.Request(
  215. ctx,
  216. permission.CreatePermissionRequest{
  217. SessionID: sessionID,
  218. Path: dir,
  219. ToolName: PatchToolName,
  220. Action: "delete",
  221. Description: fmt.Sprintf("Delete file %s", path),
  222. Params: EditPermissionsParams{
  223. FilePath: path,
  224. Diff: patchDiff,
  225. },
  226. },
  227. )
  228. if !p {
  229. return ToolResponse{}, permission.ErrorPermissionDenied
  230. }
  231. }
  232. }
  233. // Apply the changes to the filesystem
  234. err = diff.ApplyCommit(commit, func(path string, content string) error {
  235. absPath := path
  236. if !filepath.IsAbs(absPath) {
  237. wd := config.WorkingDirectory()
  238. absPath = filepath.Join(wd, absPath)
  239. }
  240. // Create parent directories if needed
  241. dir := filepath.Dir(absPath)
  242. if err := os.MkdirAll(dir, 0o755); err != nil {
  243. return fmt.Errorf("failed to create parent directories for %s: %w", absPath, err)
  244. }
  245. return os.WriteFile(absPath, []byte(content), 0o644)
  246. }, func(path string) error {
  247. absPath := path
  248. if !filepath.IsAbs(absPath) {
  249. wd := config.WorkingDirectory()
  250. absPath = filepath.Join(wd, absPath)
  251. }
  252. return os.Remove(absPath)
  253. })
  254. if err != nil {
  255. return NewTextErrorResponse(fmt.Sprintf("failed to apply patch: %s", err)), nil
  256. }
  257. // Update file history for all modified files
  258. changedFiles := []string{}
  259. totalAdditions := 0
  260. totalRemovals := 0
  261. for path, change := range commit.Changes {
  262. absPath := path
  263. if !filepath.IsAbs(absPath) {
  264. wd := config.WorkingDirectory()
  265. absPath = filepath.Join(wd, absPath)
  266. }
  267. changedFiles = append(changedFiles, absPath)
  268. oldContent := ""
  269. if change.OldContent != nil {
  270. oldContent = *change.OldContent
  271. }
  272. newContent := ""
  273. if change.NewContent != nil {
  274. newContent = *change.NewContent
  275. }
  276. // Calculate diff statistics
  277. _, additions, removals := diff.GenerateDiff(oldContent, newContent, path)
  278. totalAdditions += additions
  279. totalRemovals += removals
  280. // Update history
  281. file, err := p.files.GetLatestByPathAndSession(ctx, absPath, sessionID)
  282. if err != nil && change.Type != diff.ActionAdd {
  283. // If not adding a file, create history entry for existing file
  284. _, err = p.files.Create(ctx, sessionID, absPath, oldContent)
  285. if err != nil {
  286. slog.Debug("Error creating file history", "error", err)
  287. }
  288. }
  289. if err == nil && change.Type != diff.ActionAdd && file.Content != oldContent {
  290. // User manually changed content, store intermediate version
  291. _, err = p.files.CreateVersion(ctx, sessionID, absPath, oldContent)
  292. if err != nil {
  293. slog.Debug("Error creating file history version", "error", err)
  294. }
  295. }
  296. // Store new version
  297. if change.Type == diff.ActionDelete {
  298. _, err = p.files.CreateVersion(ctx, sessionID, absPath, "")
  299. } else {
  300. _, err = p.files.CreateVersion(ctx, sessionID, absPath, newContent)
  301. }
  302. if err != nil {
  303. slog.Debug("Error creating file history version", "error", err)
  304. }
  305. // Record file operations
  306. recordFileWrite(absPath)
  307. recordFileRead(absPath)
  308. }
  309. // Run LSP diagnostics on all changed files
  310. for _, filePath := range changedFiles {
  311. waitForLspDiagnostics(ctx, filePath, p.lspClients)
  312. }
  313. result := fmt.Sprintf("Patch applied successfully. %d files changed, %d additions, %d removals",
  314. len(changedFiles), totalAdditions, totalRemovals)
  315. diagnosticsText := ""
  316. for _, filePath := range changedFiles {
  317. diagnosticsText += getDiagnostics(filePath, p.lspClients)
  318. }
  319. if diagnosticsText != "" {
  320. result += "\n\nDiagnostics:\n" + diagnosticsText
  321. }
  322. return WithResponseMetadata(
  323. NewTextResponse(result),
  324. PatchResponseMetadata{
  325. FilesChanged: changedFiles,
  326. Additions: totalAdditions,
  327. Removals: totalRemovals,
  328. }), nil
  329. }