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