1package tools
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "os"
9 "strings"
10
11 "github.com/patriceckhart/zot/internal/core"
12 "github.com/patriceckhart/zot/internal/provider"
13)
14
15// EditTool applies one or more exact-match replacements to a file.
16type EditTool struct {
17 CWD string
18 Sandbox *Sandbox
19}
20
21type editOp struct {
22 OldText string `json:"oldText"`
23 NewText string `json:"newText"`
24}
25
26type editArgs struct {
27 Path string `json:"path"`
28 Edits []editOp `json:"edits"`
29}
30
31const editSchema = `{"type":"object","properties":{"path":{"type":"string"},"edits":{"type":"array","items":{"type":"object","properties":{"oldText":{"type":"string"},"newText":{"type":"string"}},"required":["oldText","newText"]}}},"required":["path","edits"]}`
32
33func (t *EditTool) Name() string { return "edit" }
34func (t *EditTool) Description() string {
35 return "Edit a file via exact-match replacements. Each oldText must be unique in the file."
36}
37func (t *EditTool) Schema() json.RawMessage { return json.RawMessage(editSchema) }
38
39func (t *EditTool) Execute(ctx context.Context, raw json.RawMessage, progress func(string)) (core.ToolResult, error) {
40 var a editArgs
41 if err := json.Unmarshal(raw, &a); err != nil {
42 return core.ToolResult{}, fmt.Errorf("invalid args: %w", err)
43 }
44 if a.Path == "" {
45 return core.ToolResult{}, fmt.Errorf("path is required")
46 }
47 if len(a.Edits) == 0 {
48 return core.ToolResult{}, fmt.Errorf("at least one edit is required")
49 }
50 path := resolvePath(t.CWD, a.Path)
51 if err := t.Sandbox.CheckPath(path); err != nil {
52 return core.ToolResult{}, err
53 }
54
55 orig, err := os.ReadFile(path)
56 if err != nil {
57 return core.ToolResult{}, err
58 }
59
60 // Detect BOM and line endings.
61 var bom []byte
62 if bytes.HasPrefix(orig, []byte{0xEF, 0xBB, 0xBF}) {
63 bom = orig[:3]
64 orig = orig[3:]
65 }
66 nl := detectLineEnding(orig)
67 // Normalize to \n for matching.
68 body := string(bytes.ReplaceAll(orig, []byte("\r\n"), []byte("\n")))
69
70 // Validate all edits first (against original content, not sequentially).
71 for i, e := range a.Edits {
72 if e.OldText == "" {
73 return core.ToolResult{}, fmt.Errorf("edit %d: oldText must not be empty", i+1)
74 }
75 if e.OldText == e.NewText {
76 return core.ToolResult{}, fmt.Errorf("edit %d: oldText equals newText", i+1)
77 }
78 count := strings.Count(body, e.OldText)
79 if count == 0 {
80 return core.ToolResult{}, fmt.Errorf("edit %d: oldText not found in %s", i+1, a.Path)
81 }
82 if count > 1 {
83 return core.ToolResult{}, fmt.Errorf("edit %d: oldText matches %d times (must be unique) in %s", i+1, count, a.Path)
84 }
85 }
86
87 // Apply atomically (sorted by position so offsets stay valid as we splice).
88 type span struct {
89 start, end int
90 replacement string
91 }
92 spans := make([]span, 0, len(a.Edits))
93 for _, e := range a.Edits {
94 idx := strings.Index(body, e.OldText)
95 spans = append(spans, span{start: idx, end: idx + len(e.OldText), replacement: e.NewText})
96 }
97 // Check for overlaps.
98 for i := 0; i < len(spans); i++ {
99 for j := i + 1; j < len(spans); j++ {
100 if spans[i].start < spans[j].end && spans[j].start < spans[i].end {
101 return core.ToolResult{}, fmt.Errorf("edits overlap; merge them into one edit")
102 }
103 }
104 }
105 // Sort ascending.
106 for i := 1; i < len(spans); i++ {
107 for j := i; j > 0 && spans[j-1].start > spans[j].start; j-- {
108 spans[j-1], spans[j] = spans[j], spans[j-1]
109 }
110 }
111 var out strings.Builder
112 prev := 0
113 for _, s := range spans {
114 out.WriteString(body[prev:s.start])
115 out.WriteString(s.replacement)
116 prev = s.end
117 }
118 out.WriteString(body[prev:])
119 newBody := out.String()
120
121 // Restore line endings.
122 if nl == "\r\n" {
123 newBody = strings.ReplaceAll(newBody, "\n", "\r\n")
124 }
125 final := append([]byte{}, bom...)
126 final = append(final, []byte(newBody)...)
127
128 if err := os.WriteFile(path, final, 0o644); err != nil {
129 return core.ToolResult{}, err
130 }
131
132 diff := unifiedDiff(a.Path, string(orig), strings.ReplaceAll(newBody, "\r\n", "\n"))
133 msg := fmt.Sprintf("applied %d edit(s) to %s", len(a.Edits), a.Path)
134 return core.ToolResult{
135 Content: []provider.Content{provider.TextBlock{Text: msg + "\n" + diff}},
136 Details: map[string]any{"path": path, "edits": len(a.Edits), "diff": diff},
137 }, nil
138}
139
140func detectLineEnding(b []byte) string {
141 if bytes.Contains(b, []byte("\r\n")) {
142 return "\r\n"
143 }
144 return "\n"
145}
146
147// unifiedDiff is a minimal unified diff good enough for tool output.
148func unifiedDiff(name, a, b string) string {
149 if a == b {
150 return ""
151 }
152 aLines := strings.Split(a, "\n")
153 bLines := strings.Split(b, "\n")
154 // Use simple LCS-based diff.
155 ops := diffLines(aLines, bLines)
156 var sb strings.Builder
157 fmt.Fprintf(&sb, "--- %s\n+++ %s\n", name, name)
158 for _, op := range ops {
159 switch op.kind {
160 case ' ':
161 fmt.Fprintf(&sb, " %s\n", op.line)
162 case '-':
163 fmt.Fprintf(&sb, "-%s\n", op.line)
164 case '+':
165 fmt.Fprintf(&sb, "+%s\n", op.line)
166 }
167 }
168 return sb.String()
169}
170
171type diffOp struct {
172 kind byte
173 line string
174}
175
176func diffLines(a, b []string) []diffOp {
177 // LCS table.
178 m, n := len(a), len(b)
179 dp := make([][]int, m+1)
180 for i := range dp {
181 dp[i] = make([]int, n+1)
182 }
183 for i := 0; i < m; i++ {
184 for j := 0; j < n; j++ {
185 if a[i] == b[j] {
186 dp[i+1][j+1] = dp[i][j] + 1
187 } else if dp[i+1][j] >= dp[i][j+1] {
188 dp[i+1][j+1] = dp[i+1][j]
189 } else {
190 dp[i+1][j+1] = dp[i][j+1]
191 }
192 }
193 }
194 // Backtrack.
195 var ops []diffOp
196 i, j := m, n
197 for i > 0 && j > 0 {
198 if a[i-1] == b[j-1] {
199 ops = append([]diffOp{{' ', a[i-1]}}, ops...)
200 i--
201 j--
202 } else if dp[i][j-1] >= dp[i-1][j] {
203 ops = append([]diffOp{{'+', b[j-1]}}, ops...)
204 j--
205 } else {
206 ops = append([]diffOp{{'-', a[i-1]}}, ops...)
207 i--
208 }
209 }
210 for i > 0 {
211 ops = append([]diffOp{{'-', a[i-1]}}, ops...)
212 i--
213 }
214 for j > 0 {
215 ops = append([]diffOp{{'+', b[j-1]}}, ops...)
216 j--
217 }
218 return ops
219}