1// Package tools implements zut's built-in tools: read, write, edit, bash,
2// create_worktree, grep, lsp, web search, and autonomous goal updates.
3package tools
4
5import (
6 "bytes"
7 "context"
8 "encoding/json"
9 "fmt"
10 "io"
11 "os"
12 "path/filepath"
13 "strings"
14
15 "github.com/bnema/zut/packages/core"
16 "github.com/bnema/zut/packages/provider"
17)
18
19const (
20 maxReadLines = 2000
21 maxReadBytes = 50 * 1024
22)
23
24// ReadTool reads file contents from disk.
25type ReadTool struct {
26 CWD string
27 Sandbox *Sandbox // when jailed, confines reads to the sandbox root
28}
29
30type readArgs struct {
31 Path string `json:"path"`
32 Offset int `json:"offset,omitempty"`
33 Limit int `json:"limit,omitempty"`
34}
35
36const readSchema = `{"type":"object","properties":{"path":{"type":"string"},"offset":{"type":"integer"},"limit":{"type":"integer"}},"required":["path"]}`
37
38func (t *ReadTool) Name() string { return "read" }
39func (t *ReadTool) Description() string {
40 return "Read a file. Images (png/jpg/gif/webp) return inline."
41}
42func (t *ReadTool) Schema() json.RawMessage { return json.RawMessage(readSchema) }
43
44func (t *ReadTool) Execute(ctx context.Context, raw json.RawMessage, progress func(string)) (core.ToolResult, error) {
45 var a readArgs
46 if err := json.Unmarshal(raw, &a); err != nil {
47 return core.ToolResult{}, fmt.Errorf("invalid args: %w", err)
48 }
49 if a.Path == "" {
50 return core.ToolResult{}, fmt.Errorf("path is required")
51 }
52 path := resolvePath(t.CWD, a.Path)
53 if err := t.Sandbox.CheckReadPath(path); err != nil {
54 return core.ToolResult{}, err
55 }
56 // What the model sees in errors: relative to the sandbox root when
57 // jailed, so absolute paths stay out of the context window.
58 shown := t.Sandbox.DisplayPath(path, a.Path)
59
60 info, err := os.Stat(path)
61 if err != nil {
62 return core.ToolResult{}, err
63 }
64 if info.IsDir() {
65 return core.ToolResult{}, fmt.Errorf("%s is a directory", shown)
66 }
67
68 // Image handling.
69 if mime := imageMIME(path); mime != "" {
70 data, err := os.ReadFile(path)
71 if err != nil {
72 return core.ToolResult{}, err
73 }
74 // The extension is only a hint. Files are routinely mislabeled
75 // (a .png that is actually JPEG bytes, a renamed download, an
76 // editor that re-encoded on save). Anthropic and other providers
77 // sniff the real bytes and reject the whole request when the
78 // declared media type disagrees, which would break the session.
79 // Always derive the MIME from the actual content; fall back to
80 // the extension-based guess only when the bytes are unrecognized.
81 if sniffed := sniffImageMIME(data); sniffed != "" {
82 mime = sniffed
83 }
84 return core.ToolResult{
85 Content: []provider.Content{provider.ImageBlock{MimeType: mime, Data: data}},
86 }, nil
87 }
88
89 f, err := os.Open(path)
90 if err != nil {
91 return core.ToolResult{}, err
92 }
93 defer f.Close()
94
95 // Read up to maxReadBytes and also line-limit.
96 limited := io.LimitReader(f, int64(maxReadBytes)+1)
97 data, err := io.ReadAll(limited)
98 if err != nil {
99 return core.ToolResult{}, err
100 }
101 truncBytes := len(data) > maxReadBytes
102 if truncBytes {
103 data = data[:maxReadBytes]
104 }
105
106 if looksBinary(data) {
107 return core.ToolResult{}, fmt.Errorf("%s looks binary; refusing to read as text", a.Path)
108 }
109
110 lines := strings.Split(string(data), "\n")
111 // Trim trailing empty line from final \n.
112 if n := len(lines); n > 0 && lines[n-1] == "" {
113 lines = lines[:n-1]
114 }
115
116 start := 0
117 if a.Offset > 0 {
118 start = a.Offset - 1
119 if start > len(lines) {
120 start = len(lines)
121 }
122 }
123 end := len(lines)
124 if a.Limit > 0 && start+a.Limit < end {
125 end = start + a.Limit
126 }
127 selected := lines[start:end]
128
129 truncLines := false
130 if len(selected) > maxReadLines {
131 selected = selected[:maxReadLines]
132 truncLines = true
133 }
134
135 // Raw file contents go to the model. We deliberately DON'T
136 // prepend line numbers here: they'd inflate the token count by
137 // ~15-20% on typical source files (7 bytes per line, every
138 // line, every time the file gets re-sent as context on later
139 // turns) and the model doesn't need them — edit goes through
140 // exact-match text replacement, not line ranges.
141 //
142 // The TUI renders its own gutter using the start offset stored
143 // in Details, so the on-screen view still looks like cat -n.
144 var sb strings.Builder
145 for _, line := range selected {
146 sb.WriteString(line)
147 sb.WriteByte('\n')
148 }
149 if truncLines || truncBytes {
150 sb.WriteString("\n")
151 }
152 if truncLines {
153 fmt.Fprintf(&sb, "... [truncated at %d lines]\n", maxReadLines)
154 }
155 if truncBytes {
156 fmt.Fprintf(&sb, "... [truncated at %d bytes]\n", maxReadBytes)
157 }
158
159 return core.ToolResult{
160 Content: []provider.Content{provider.TextBlock{Text: sb.String()}},
161 Details: map[string]any{
162 "path": path,
163 "start_line": start + 1, // 1-indexed; TUI draws the gutter
164 "lines_truncated": truncLines,
165 "bytes_truncated": truncBytes,
166 "total_lines": len(lines),
167 },
168 }, nil
169}
170
171func resolvePath(cwd, p string) string {
172 if filepath.IsAbs(p) {
173 return p
174 }
175 if cwd == "" {
176 cwd, _ = os.Getwd()
177 }
178 return filepath.Join(cwd, p)
179}
180
181func imageMIME(path string) string {
182 switch strings.ToLower(filepath.Ext(path)) {
183 case ".png":
184 return "image/png"
185 case ".jpg", ".jpeg":
186 return "image/jpeg"
187 case ".gif":
188 return "image/gif"
189 case ".webp":
190 return "image/webp"
191 }
192 return ""
193}
194
195// sniffImageMIME inspects the leading bytes of an image file and
196// returns the real media type, independent of the file's extension.
197// Providers validate the declared media type against the actual bytes
198// and 400 the whole request on a mismatch, so the extension can never
199// be trusted. Returns "" when the format is not one zut ships images
200// for, leaving the caller's extension-based guess in place.
201func sniffImageMIME(data []byte) string {
202 switch {
203 case len(data) >= 8 && bytes.Equal(data[:8], []byte{0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A}):
204 return "image/png"
205 case len(data) >= 3 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF:
206 return "image/jpeg"
207 case len(data) >= 6 && (bytes.Equal(data[:6], []byte("GIF87a")) || bytes.Equal(data[:6], []byte("GIF89a"))):
208 return "image/gif"
209 case len(data) >= 12 && bytes.Equal(data[:4], []byte("RIFF")) && bytes.Equal(data[8:12], []byte("WEBP")):
210 return "image/webp"
211 }
212 return ""
213}
214
215// looksBinary returns true if the buffer contains a NUL byte in its first 8 KiB.
216func looksBinary(b []byte) bool {
217 n := len(b)
218 if n > 8192 {
219 n = 8192
220 }
221 for i := 0; i < n; i++ {
222 if b[i] == 0 {
223 return true
224 }
225 }
226 return false
227}