-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.go
More file actions
330 lines (300 loc) · 8.95 KB
/
tools.go
File metadata and controls
330 lines (300 loc) · 8.95 KB
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
package iteragent
import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
var protectedPaths []string
var dangerousPatterns = []string{
"rm -rf",
"git push --force",
"git push -f",
"--force-with-lease",
"chmod -R 777",
"> /etc/",
"curl .* | sh",
"wget .* | sh",
}
func SetProtectedPaths(paths []string) {
protectedPaths = paths
}
func GetProtectedPaths() []string {
return protectedPaths
}
func isPathProtected(path string) bool {
for _, p := range protectedPaths {
if strings.HasPrefix(path, p) {
return true
}
}
return false
}
func isCommandDangerous(cmd string) bool {
for _, pattern := range dangerousPatterns {
if strings.Contains(cmd, pattern) {
return true
}
}
return false
}
// safeJoin joins repoPath with the user-supplied relative path and ensures the
// result stays within repoPath, preventing path traversal attacks.
func safeJoin(repoPath, rel string) (string, error) {
joined := filepath.Join(repoPath, rel)
absRepo, err := filepath.Abs(repoPath)
if err != nil {
return "", fmt.Errorf("invalid repo path: %w", err)
}
absJoined, err := filepath.Abs(joined)
if err != nil {
return "", fmt.Errorf("invalid path: %w", err)
}
if !strings.HasPrefix(absJoined, absRepo+string(filepath.Separator)) && absJoined != absRepo {
return "", fmt.Errorf("path %q is outside the repository", rel)
}
return absJoined, nil
}
// DefaultTools returns all built-in tools available to the agent.
func DefaultTools(repoPath string) []Tool {
return []Tool{
BashTool(repoPath),
ReadFileTool(repoPath),
WriteFileTool(repoPath),
EditFileTool(repoPath),
ListFilesTool(repoPath),
SearchTool(repoPath),
GitDiffTool(repoPath),
GitCommitTool(repoPath),
GitRevertTool(repoPath),
RunTestsTool(repoPath),
}
}
func BashTool(repoPath string) Tool {
return Tool{
Name: "bash",
Description: "Run a shell command in the repo directory.\nArgs: {\"cmd\": \"go build ./...\"}",
Execute: func(ctx context.Context, args map[string]string) (string, error) {
cmd := args["cmd"]
if cmd == "" {
return "", fmt.Errorf("cmd is required")
}
if isCommandDangerous(cmd) {
return "", fmt.Errorf("command contains dangerous pattern: %s", cmd)
}
ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
defer cancel()
c := exec.CommandContext(ctx, "bash", "-c", cmd)
c.Dir = repoPath
var out bytes.Buffer
c.Stdout = &out
c.Stderr = &out
err := c.Run()
return out.String(), err
},
}
}
func ReadFileTool(repoPath string) Tool {
return Tool{
Name: "read_file",
Description: "Read a file from the repo.\nArgs: {\"path\": \"internal/agent/agent.go\"}",
Execute: func(ctx context.Context, args map[string]string) (string, error) {
path, err := safeJoin(repoPath, args["path"])
if err != nil {
return "", err
}
data, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("read %s: %w", args["path"], err)
}
return string(data), nil
},
}
}
func WriteFileTool(repoPath string) Tool {
return Tool{
Name: "write_file",
Description: "Write or overwrite a file in the repo.\nArgs: {\"path\": \"internal/agent/agent.go\", \"content\": \"...\"}",
Execute: func(ctx context.Context, args map[string]string) (string, error) {
path, err := safeJoin(repoPath, args["path"])
if err != nil {
return "", err
}
if isPathProtected(path) {
return "", fmt.Errorf("write to %s is protected", args["path"])
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return "", err
}
if err := os.WriteFile(path, []byte(args["content"]), 0o644); err != nil {
return "", fmt.Errorf("write %s: %w", args["path"], err)
}
return fmt.Sprintf("wrote %s (%d bytes)", args["path"], len(args["content"])), nil
},
}
}
func EditFileTool(repoPath string) Tool {
return Tool{
Name: "edit_file",
Description: "Edit a file by replacing oldString with newString.\nArgs: {\"path\": \"file.go\", \"oldString\": \"old\", \"newString\": \"new\"}",
Execute: func(ctx context.Context, args map[string]string) (string, error) {
path, err := safeJoin(repoPath, args["path"])
if err != nil {
return "", err
}
if isPathProtected(path) {
return "", fmt.Errorf("edit %s is protected", args["path"])
}
oldStr := args["oldString"]
newStr := args["newString"]
if oldStr == "" {
return "", fmt.Errorf("oldString is required")
}
data, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("read %s: %w", args["path"], err)
}
content := string(data)
if !strings.Contains(content, oldStr) {
return "", fmt.Errorf("oldString not found in file")
}
newContent := strings.Replace(content, oldStr, newStr, 1)
if err := os.WriteFile(path, []byte(newContent), 0o644); err != nil {
return "", fmt.Errorf("write %s: %w", args["path"], err)
}
return fmt.Sprintf("edited %s", args["path"]), nil
},
}
}
func ListFilesTool(repoPath string) Tool {
return Tool{
Name: "list_files",
Description: "List all files in the repo.\nArgs: {}",
Execute: func(ctx context.Context, args map[string]string) (string, error) {
var files []string
err := filepath.Walk(repoPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
if info.IsDir() && (info.Name() == ".git" || info.Name() == "vendor" || info.Name() == "node_modules") {
return filepath.SkipDir
}
rel, _ := filepath.Rel(repoPath, path)
files = append(files, rel)
return nil
})
return strings.Join(files, "\n"), err
},
}
}
func SearchTool(repoPath string) Tool {
return Tool{
Name: "search",
Description: "Search for text in files.\nArgs: {\"pattern\": \"TODO\", \"path\": \".\"}",
Execute: func(ctx context.Context, args map[string]string) (string, error) {
pattern := args["pattern"]
if pattern == "" {
return "", fmt.Errorf("pattern is required")
}
path := repoPath
if args["path"] != "" {
var err error
path, err = safeJoin(repoPath, args["path"])
if err != nil {
return "", err
}
}
c := exec.CommandContext(ctx, "grep", "-r", "-n", pattern, path)
c.Dir = repoPath
out, err := c.CombinedOutput()
return string(out), err
},
}
}
func GitDiffTool(repoPath string) Tool {
return Tool{
Name: "git_diff",
Description: "Show current unstaged changes.\nArgs: {}",
Execute: func(ctx context.Context, args map[string]string) (string, error) {
c := exec.CommandContext(ctx, "git", "diff")
c.Dir = repoPath
out, err := c.Output()
return string(out), err
},
}
}
func GitCommitTool(repoPath string) Tool {
return Tool{
Name: "git_commit",
Description: "Stage all changes and commit.\nArgs: {\"message\": \"feat: improve error handling\"}",
Execute: func(ctx context.Context, args map[string]string) (string, error) {
msg := args["message"]
if msg == "" {
msg = fmt.Sprintf("iterate: auto-improvement session %s", time.Now().Format("2006-01-02"))
}
add := exec.CommandContext(ctx, "git", "add", "-A")
add.Dir = repoPath
if out, err := add.CombinedOutput(); err != nil {
return string(out), fmt.Errorf("git add: %w", err)
}
commit := exec.CommandContext(ctx, "git", "commit", "-m", msg)
commit.Dir = repoPath
commit.Env = append(os.Environ(),
"GIT_AUTHOR_NAME=iterate[bot]",
"GIT_AUTHOR_EMAIL=iterate@users.noreply.github.com",
"GIT_COMMITTER_NAME=iterate[bot]",
"GIT_COMMITTER_EMAIL=iterate@users.noreply.github.com",
)
out, err := commit.CombinedOutput()
return string(out), err
},
}
}
func GitRevertTool(repoPath string) Tool {
return Tool{
Name: "git_revert",
Description: "Discard all unstaged changes.\nArgs: {}",
Execute: func(ctx context.Context, args map[string]string) (string, error) {
c := exec.CommandContext(ctx, "git", "checkout", "--", ".")
c.Dir = repoPath
out, err := c.CombinedOutput()
return string(out), err
},
}
}
func RunTestsTool(repoPath string) Tool {
return Tool{
Name: "run_tests",
Description: "Run go build and go test.\nArgs: {}",
Execute: func(ctx context.Context, args map[string]string) (string, error) {
ctx, cancel := context.WithTimeout(ctx, 120*time.Second)
defer cancel()
var results strings.Builder
build := exec.CommandContext(ctx, "go", "build", "./...")
build.Dir = repoPath
out, err := build.CombinedOutput()
results.WriteString("=== go build ===\n")
results.Write(out)
if err != nil {
results.WriteString("\nBUILD FAILED\n")
return results.String(), fmt.Errorf("build failed")
}
results.WriteString("BUILD OK\n\n")
test := exec.CommandContext(ctx, "go", "test", "./...")
test.Dir = repoPath
out, err = test.CombinedOutput()
results.WriteString("=== go test ===\n")
results.Write(out)
if err != nil {
results.WriteString("\nTESTS FAILED\n")
return results.String(), fmt.Errorf("tests failed")
}
results.WriteString("ALL TESTS PASSED\n")
return results.String(), nil
},
}
}