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
|
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"unicode/utf8"
)
func inDir(t *testing.T) string {
t.Helper()
d := t.TempDir()
wd, _ := os.Getwd()
if err := os.Chdir(d); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.Chdir(wd) })
return d
}
func TestRead(t *testing.T) {
inDir(t)
os.WriteFile("f", []byte("a\nb\nc\n"), 0644)
got, _ := toolRead(map[string]any{"path": "f"})
if want := " 1| a\n 2| b\n 3| c\n"; got != want {
t.Errorf("full: got %q want %q", got, want)
}
got, _ = toolRead(map[string]any{"path": "f", "offset": 1.0, "limit": 1.0})
if want := " 2| b\n"; got != want {
t.Errorf("window: got %q want %q", got, want)
}
// stringly-typed args, as small local models emit them
got, _ = toolRead(map[string]any{"path": "f", "offset": "1", "limit": "1"})
if want := " 2| b\n"; got != want {
t.Errorf("string args: got %q want %q", got, want)
}
// no trailing newline on the final line
os.WriteFile("g", []byte("a\nb"), 0644)
got, _ = toolRead(map[string]any{"path": "g"})
if want := " 1| a\n 2| b"; got != want {
t.Errorf("no-trailing-nl: got %q want %q", got, want)
}
// empty file -> no lines
os.WriteFile("e", nil, 0644)
if got, _ = toolRead(map[string]any{"path": "e"}); got != "" {
t.Errorf("empty: got %q", got)
}
if _, err := toolRead(map[string]any{"path": "nope"}); err == nil {
t.Error("missing file should error")
}
}
func TestEdit(t *testing.T) {
inDir(t)
os.WriteFile("f", []byte("x y x"), 0644)
got, err := toolEdit(map[string]any{"path": "f", "old": "x", "new": "z"})
if err != nil {
t.Fatalf("must be a result, not an error: %v", err)
}
if want := "error: old_string appears 2 times, must be unique (use all=true)"; got != want {
t.Errorf("got %q want %q", got, want)
}
if b, _ := os.ReadFile("f"); string(b) != "x y x" {
t.Errorf("file was modified: %q", b)
}
if got, _ = toolEdit(map[string]any{"path": "f", "old": "x", "new": "z", "all": true}); got != "ok" {
t.Errorf("all=true: got %q", got)
}
if b, _ := os.ReadFile("f"); string(b) != "z y z" {
t.Errorf("all=true result: %q", b)
}
if got, _ = toolEdit(map[string]any{"path": "f", "old": "q", "new": "r"}); got != "error: old_string not found" {
t.Errorf("not found: got %q", got)
}
}
func TestGlob(t *testing.T) {
inDir(t)
os.MkdirAll("sub", 0755)
os.MkdirAll(".hidden", 0755)
os.WriteFile("old.go", []byte("package p"), 0644)
os.WriteFile("sub/new.go", []byte("package p"), 0644)
os.WriteFile(".hidden/x.go", []byte("package p"), 0644)
os.WriteFile("notgo.txt", nil, 0644)
now := time.Now()
os.Chtimes("old.go", now.Add(-time.Hour), now.Add(-time.Hour))
os.Chtimes("sub/new.go", now, now)
got, _ := toolGlob(map[string]any{"pat": "**/*.go"})
if want := "sub/new.go\nold.go"; got != want {
t.Errorf("newest-first: got %q want %q", got, want)
}
if strings.Contains(got, ".hidden") {
t.Errorf("dot-directory not skipped: %q", got)
}
if got, _ = toolGlob(map[string]any{"pat": "**/*.rs"}); got != "none" {
t.Errorf("no matches: got %q", got)
}
}
func TestGrepCapsAt50(t *testing.T) {
inDir(t)
for i := 0; i < 8; i++ {
var b strings.Builder
for j := 0; j < 10; j++ {
fmt.Fprintf(&b, "needle %d\n", j)
}
os.WriteFile(fmt.Sprintf("f%d.txt", i), []byte(b.String()), 0644)
}
got, _ := toolGrep(map[string]any{"pat": "needle"})
if n := len(strings.Split(got, "\n")); n != 50 {
t.Errorf("got %d lines, want 50", n)
}
if got, _ = toolGrep(map[string]any{"pat": "haystack"}); got != "none" {
t.Errorf("no hits: got %q", got)
}
if _, err := toolGrep(map[string]any{"pat": "("}); err == nil {
t.Error("bad regex should error")
}
// RE2: backreferences do not compile
if _, err := toolGrep(map[string]any{"pat": `(a)\1`}); err == nil {
t.Error("backreference should error")
}
}
func TestBash(t *testing.T) {
if got, _ := toolBash(map[string]any{"cmd": "true"}); got != "(empty)" {
t.Errorf("true: got %q want (empty)", got)
}
got, _ := toolBash(map[string]any{"cmd": "echo out; echo err 1>&2"})
if !strings.Contains(got, "out") || !strings.Contains(got, "err") {
t.Errorf("stdout+stderr: got %q", got)
}
if got, _ = toolBash(map[string]any{"cmd": "cd /tmp"}); got != "(empty)" {
t.Errorf("cd: got %q", got)
}
}
func TestBashTimeout(t *testing.T) {
if testing.Short() {
t.Skip("30s")
}
start := time.Now()
got, _ := toolBash(map[string]any{"cmd": "echo before; sleep 60"})
elapsed := time.Since(start)
if !strings.HasSuffix(got, "(timed out after 30s)") {
t.Errorf("got %q", got)
}
if !strings.HasPrefix(got, "before") {
t.Errorf("drained output lost: %q", got)
}
if elapsed < 29*time.Second || elapsed > 35*time.Second {
t.Errorf("elapsed %v, want ~30s", elapsed)
}
}
func TestUnknownTool(t *testing.T) {
if got := runTool("nope", json.RawMessage(`{}`)); got != `error: unknown tool "nope"` {
t.Errorf("got %q", got)
}
}
// Schemas carry "type" and nothing else -- a maxLength >~2000
// makes gpt-oss-120b fail every tool call with "failed to parse grammar".
func TestSchemas(t *testing.T) {
for i, s := range schemas {
var parsed struct {
Name string `json:"name"`
Schema struct {
Properties map[string]map[string]any `json:"properties"`
Required []string `json:"required"`
} `json:"input_schema"`
}
if err := json.Unmarshal(s, &parsed); err != nil {
t.Fatalf("tool %s: %v", tools[i].name, err)
}
// The invariant: every property carries "type" and nothing else.
for prop, keys := range parsed.Schema.Properties {
if len(keys) != 1 {
t.Errorf("tool %s prop %s: %d schema keys, want only \"type\"", parsed.Name, prop, len(keys))
}
if _, ok := keys["type"]; !ok {
t.Errorf("tool %s prop %s: missing \"type\"", parsed.Name, prop)
}
}
if parsed.Schema.Required == nil {
t.Errorf("tool %s: required is null, must be an array", parsed.Name)
}
if parsed.Name != tools[i].name {
t.Errorf("schema %d: name %q want %q", i, parsed.Name, tools[i].name)
}
}
// declaration order, not map order
if want := `"properties":{"path":{"type":"string"},"old":{"type":"string"},"new":{"type":"string"},"all":{"type":"boolean"}}`; !strings.Contains(string(schemas[2]), want) {
t.Errorf("edit schema property order wrong:\n%s", schemas[2])
}
if want := `"required":["path","old","new"]`; !strings.Contains(string(schemas[2]), want) {
t.Errorf("edit required wrong:\n%s", schemas[2])
}
if want := `"offset":{"type":"integer"}`; !strings.Contains(string(schemas[0]), want) {
t.Errorf("optional marker should be stripped from the type:\n%s", schemas[0])
}
}
func TestDisplay(t *testing.T) {
if got := renderMarkdown("a **b** c"); got != "a "+bold+"b"+reset+" c" {
t.Errorf("bold: got %q", got)
}
if got := renderMarkdown("**a\nb**"); got != bold+"a\nb"+reset {
t.Errorf("dotall: got %q", got)
}
if got := capitalize("read"); got != "Read" {
t.Errorf("got %q", got)
}
// truncation by code points, never bytes
if got := truncate(strings.Repeat("é", 60), 50); len([]rune(got)) != 50 {
t.Errorf("got %d runes", len([]rune(got)))
}
// first declared param present in the input
in := json.RawMessage(`{"limit":5,"path":"/tmp/x"}`)
if got := argPreview("read", in); got != "/tmp/x" {
t.Errorf("preview: got %q", got)
}
if got := argPreview("read", json.RawMessage(`{"limit":5}`)); got != "5" {
t.Errorf("non-string preview: got %q", got)
}
if got := argPreview("nope", in); got != "" {
t.Errorf("unknown tool preview: got %q", got)
}
}
func TestGlobEngine(t *testing.T) {
d := inDir(t)
os.MkdirAll("a/b", 0755)
os.WriteFile("a/b/c.txt", nil, 0644)
os.WriteFile("a/top.txt", nil, 0644)
// ** matches zero segments
if got := globExpand("a/**/top.txt"); len(got) != 1 || got[0] != "a/top.txt" {
t.Errorf("zero-segment **: got %v", got)
}
// final segment emits directories too
got := globExpand("a/*")
if len(got) != 2 {
t.Errorf("final segment should emit dir and file: got %v", got)
}
// absolute patterns stay absolute
if got := globExpand(filepath.Join(d, "a", "*.txt")); len(got) != 1 || !strings.HasPrefix(got[0], "/") {
t.Errorf("absolute: got %v", got)
}
// unreadable directory is skipped silently
os.MkdirAll("locked", 0000)
defer os.Chmod("locked", 0755)
if got := globExpand("locked/*"); len(got) != 0 {
t.Errorf("unreadable dir: got %v", got)
}
}
// Two tool_use blocks in one assistant turn produce two
// result lines and exactly ONE follow-up request whose last message is a user
// message carrying both tool_result entries.
func TestAgentLoopBatchesToolResults(t *testing.T) {
inDir(t)
os.WriteFile("a.txt", []byte("A\n"), 0644)
os.WriteFile("b.txt", []byte("B\n"), 0644)
var bodies []map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
json.NewDecoder(r.Body).Decode(&body)
bodies = append(bodies, body)
if len(bodies) == 1 {
io.WriteString(w, `{"content":[
{"type":"thinking","thinking":"secret","signature":""},
{"type":"tool_use","id":"t1","name":"read","input":{"path":"a.txt"}},
{"type":"tool_use","id":"t2","name":"read","input":{"path":"b.txt"}}]}`)
return
}
io.WriteString(w, `{"content":[{"type":"text","text":"done"}]}`)
}))
defer srv.Close()
old := apiURL
apiURL = srv.URL
defer func() { apiURL = old }()
var messages []message
messages = append(messages, message{"user", "read both"})
if err := agentLoop(&messages); err != nil {
t.Fatal(err)
}
if len(bodies) != 2 {
t.Fatalf("made %d requests, want exactly 2", len(bodies))
}
// user, assistant(3 blocks), user(2 tool_results), assistant(text)
if len(messages) != 4 {
t.Fatalf("history has %d messages, want 4: %+v", len(messages), messages)
}
last := bodies[1]["messages"].([]any)
tail := last[len(last)-1].(map[string]any)
if tail["role"] != "user" {
t.Errorf("follow-up tail role = %v, want user", tail["role"])
}
results, ok := tail["content"].([]any)
if !ok || len(results) != 2 {
t.Fatalf("follow-up tail content = %v, want 2 tool_results", tail["content"])
}
for i, want := range []string{" 1| A\n", " 1| B\n"} {
r := results[i].(map[string]any)
if r["type"] != "tool_result" || r["content"] != want {
t.Errorf("result %d = %+v, want tool_result %q", i, r, want)
}
}
if got := results[0].(map[string]any)["tool_use_id"]; got != "t1" {
t.Errorf("tool_use_id = %v, want t1", got)
}
// The thinking block is never displayed, but IS replayed verbatim.
asst := last[1].(map[string]any)
blocks := asst["content"].([]any)
if len(blocks) != 3 {
t.Fatalf("assistant replayed %d blocks, want 3", len(blocks))
}
if b0 := blocks[0].(map[string]any); b0["type"] != "thinking" || b0["thinking"] != "secret" {
t.Errorf("thinking block not round-tripped verbatim: %+v", b0)
}
}
func TestAPIErrorTruncatesTo500(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500)
io.WriteString(w, strings.Repeat("é", 900))
}))
defer srv.Close()
old := apiURL
apiURL = srv.URL
defer func() { apiURL = old }()
_, err := callAPI(nil)
if err == nil {
t.Fatal("want error")
}
body := strings.TrimPrefix(err.Error(), "HTTP 500: ")
if n := utf8.RuneCountInString(body); n != 500 {
t.Errorf("body is %d code points, want 500", n)
}
}
|