diff --git a/internal/tools/builtin/edit.go b/internal/tools/builtin/edit.go index 4918bedd7..b6a18cee0 100644 --- a/internal/tools/builtin/edit.go +++ b/internal/tools/builtin/edit.go @@ -131,9 +131,6 @@ func makeEditExecutor(cwd string, mq *MutationQueue, rt *ReadTracker) Executor { return Result{Content: "at least one edit is required", IsError: true}, nil } - _, cancel := context.WithTimeout(ctx, DefaultToolTimeout) - defer cancel() - path := resolvePath(cwd, p.Path) if !isConfined(cwd, path) { @@ -147,63 +144,85 @@ func makeEditExecutor(cwd string, mq *MutationQueue, rt *ReadTracker) Executor { } } - // Check file size before reading to avoid OOM on large files. - info, err := os.Stat(path) + editCtx, cancel := context.WithTimeout(ctx, DefaultToolTimeout) + defer cancel() + + var result Result + err = runWithContext(editCtx, func() error { + result = performEdit(path, p, mq) + return nil + }) if err != nil { - return Result{Content: fmt.Sprintf("error stating file: %v", err), IsError: true}, nil - } - if info.Size() > maxReadBytes { - return Result{Content: fmt.Sprintf("file too large to edit (%s > %s)", FormatSize(int(info.Size())), FormatSize(maxReadBytes)), IsError: true}, nil - } - - release := mq.Acquire(path) - defer release() - - data, err := os.ReadFile(path) - if err != nil { - return Result{Content: fmt.Sprintf("error reading file: %v", err), IsError: true}, nil - } - - // Strip a UTF-8 BOM and normalise CRLF to LF before matching - the - // model never includes an invisible BOM or carriage returns in - // old_text. Both are restored on write. - raw := string(data) - bom := "" - if strings.HasPrefix(raw, utf8BOM) { - bom = utf8BOM - raw = strings.TrimPrefix(raw, utf8BOM) - } - hadCRLF := strings.Contains(raw, "\r\n") - content := strings.ReplaceAll(raw, "\r\n", "\n") - - newContent, err := applyEdits(content, p.Edits) - if err != nil { - errorKind := "invalid_arguments" - if strings.Contains(err.Error(), "old_text not found") { - errorKind = "stale_edit" + if errors.Is(err, context.DeadlineExceeded) { + return Result{Content: fmt.Sprintf("edit timed out after %v", DefaultToolTimeout), IsError: true}, nil } - return Result{ - Content: err.Error() + "; no edits were written; reread the smallest affected range before retrying", - IsError: true, - ErrorKind: errorKind, - }, nil - } - if newContent == content { - return Result{Content: fmt.Sprintf("no changes made to %s: the edits produced identical content", path), IsError: true}, nil + return Result{Content: fmt.Sprintf("edit failed: %v", err), IsError: true}, nil } - if hadCRLF { - newContent = strings.ReplaceAll(newContent, "\n", "\r\n") - } + return result, nil + } +} - if err := writeFileAtomic(path, []byte(bom+newContent), 0o644); err != nil { - return Result{Content: fmt.Sprintf("error writing file: %v", err), IsError: true}, nil - } +// performEdit loads, mutates, and writes path according to the edits in p. +// Every failure is returned as a Result with IsError set, never a non-nil +// error, so the executor keeps a single error envelope. +func performEdit(path string, p EditParams, mq *MutationQueue) Result { + // Check file size before reading to avoid OOM on large files. + info, err := os.Stat(path) + if err != nil { + return Result{Content: fmt.Sprintf("error stating file: %v", err), IsError: true} + } + if info.Size() > maxReadBytes { + return Result{Content: fmt.Sprintf("file too large to edit (%s > %s)", FormatSize(int(info.Size())), FormatSize(maxReadBytes)), IsError: true} + } + release := mq.Acquire(path) + defer release() + + data, err := os.ReadFile(path) + if err != nil { + return Result{Content: fmt.Sprintf("error reading file: %v", err), IsError: true} + } + + // Strip a UTF-8 BOM and normalise CRLF to LF before matching - the + // model never includes an invisible BOM or carriage returns in + // old_text. Both are restored on write. + raw := string(data) + bom := "" + if strings.HasPrefix(raw, utf8BOM) { + bom = utf8BOM + raw = strings.TrimPrefix(raw, utf8BOM) + } + hadCRLF := strings.Contains(raw, "\r\n") + content := strings.ReplaceAll(raw, "\r\n", "\n") + + newContent, err := applyEdits(content, p.Edits) + if err != nil { + errorKind := "invalid_arguments" + if strings.Contains(err.Error(), "old_text not found") { + errorKind = "stale_edit" + } return Result{ - Content: fmt.Sprintf("applied %d edit(s) to %s", len(p.Edits), path), - Details: DiffDetails{Path: path, OldContent: content, NewContent: newContent}, - }, nil + Content: err.Error() + "; no edits were written; reread the smallest affected range before retrying", + IsError: true, + ErrorKind: errorKind, + } + } + if newContent == content { + return Result{Content: fmt.Sprintf("no changes made to %s: the edits produced identical content", path), IsError: true} + } + + if hadCRLF { + newContent = strings.ReplaceAll(newContent, "\n", "\r\n") + } + + if err := writeFileAtomic(path, []byte(bom+newContent), 0o644); err != nil { + return Result{Content: fmt.Sprintf("error writing file: %v", err), IsError: true} + } + + return Result{ + Content: fmt.Sprintf("applied %d edit(s) to %s", len(p.Edits), path), + Details: DiffDetails{Path: path, OldContent: content, NewContent: newContent}, } } diff --git a/internal/tools/builtin/edit_test.go b/internal/tools/builtin/edit_test.go index 4058ded0c..a5d59daf4 100644 --- a/internal/tools/builtin/edit_test.go +++ b/internal/tools/builtin/edit_test.go @@ -7,6 +7,7 @@ import ( "path/filepath" "strings" "testing" + "time" ) func TestApplyEdits(t *testing.T) { @@ -329,3 +330,36 @@ func TestEdit_NotFoundWithNoPlausibleMatchStaysGeneric(t *testing.T) { t.Fatalf("expected the generic error, got:\n%s", res.Content) } } + +// TestEditToolHonoursDeadlineOnExpiredContext pins the DefaultToolTimeout +// contract: when the caller's context is already expired, edit must not +// ignore that deadline and mutate the file anyway. +func TestEditToolHonoursDeadlineOnExpiredContext(t *testing.T) { + tmp := t.TempDir() + path := filepath.Join(tmp, "f.txt") + if err := os.WriteFile(path, []byte("hello\n"), 0o644); err != nil { + t.Fatal(err) + } + + ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) + defer cancel() + + tool := NewEditTool(tmp, NewMutationQueue(), nil) + res, err := tool.Execute(ctx, json.RawMessage( + `{"path":"f.txt","edits":[{"old_text":"hello","new_text":"hi"}]}`, + ), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !res.IsError { + t.Fatalf("edit on an expired context must not succeed; got content %q", res.Content) + } + + after, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if string(after) != "hello\n" { + t.Fatalf("file was mutated despite the expired context: %q", after) + } +} diff --git a/internal/tools/builtin/read.go b/internal/tools/builtin/read.go index 94f51788d..a7e9f0513 100644 --- a/internal/tools/builtin/read.go +++ b/internal/tools/builtin/read.go @@ -15,6 +15,7 @@ package builtin import ( "context" "encoding/json" + "errors" "fmt" "io/fs" "os" @@ -222,28 +223,42 @@ func makeReadExecutor(cwd string, rt *ReadTracker) Executor { return *terminal, nil } - _, cancel := context.WithTimeout(ctx, DefaultToolTimeout) - defer cancel() - path := resolvePath(cwd, p.Path) if !isReadConfined(cwd, path) { return Result{Content: "path escapes working directory", IsError: true, ErrorKind: "sandbox_escape"}, nil } - info, err := os.Stat(path) - if err != nil { - msg := fmt.Sprintf("error stating file: %v", err) - if hint := suggestPaths(cwd, path); hint != "" { - msg += "\n" + hint + readCtx, cancel := context.WithTimeout(ctx, DefaultToolTimeout) + defer cancel() + + var result Result + err = runWithContext(readCtx, func() error { + info, statErr := os.Stat(path) + if statErr != nil { + msg := fmt.Sprintf("error stating file: %v", statErr) + if hint := suggestPaths(cwd, path); hint != "" { + msg += "\n" + hint + } + result = Result{Content: msg, IsError: true, ErrorKind: "not_found"} + return nil } - return Result{Content: msg, IsError: true, ErrorKind: "not_found"}, nil + + state, terminal := readFileContent(cwd, path, p, info, rt) + if terminal != nil { + result = *terminal + return nil + } + result = serveReadContent(cwd, path, p, info, state, rt) + return nil + }) + if err != nil { + if errors.Is(err, context.DeadlineExceeded) { + return Result{Content: fmt.Sprintf("read timed out after %v", DefaultToolTimeout), IsError: true}, nil + } + return Result{Content: fmt.Sprintf("read failed: %v", err), IsError: true}, nil } - state, terminal := readFileContent(cwd, path, p, info, rt) - if terminal != nil { - return *terminal, nil - } - return serveReadContent(cwd, path, p, info, state, rt), nil + return result, nil } } diff --git a/internal/tools/builtin/read_test.go b/internal/tools/builtin/read_test.go index 7cad3e74c..598325fa7 100644 --- a/internal/tools/builtin/read_test.go +++ b/internal/tools/builtin/read_test.go @@ -8,6 +8,7 @@ import ( "path/filepath" "strings" "testing" + "time" ) func execRead(t *testing.T, cwd, params string) Result { @@ -210,3 +211,23 @@ func TestReadTool_NotFoundListsExistingParentDir(t *testing.T) { t.Fatalf("expected the existing directory to be listed, got:\n%s", res.Content) } } + +// TestReadToolHonoursDeadlineOnExpiredContext pins the DefaultToolTimeout +// contract: when the caller's context is already expired, read must not +// ignore that deadline and read the file anyway. +func TestReadToolHonoursDeadlineOnExpiredContext(t *testing.T) { + tmp := t.TempDir() + writeReadTestFile(t, tmp, "f.txt", "alpha\nbeta\n") + + ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) + defer cancel() + + tool := NewReadTool(tmp, nil) + res, err := tool.Execute(ctx, json.RawMessage(`{"path":"f.txt"}`), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !res.IsError { + t.Fatalf("read on an expired context must not succeed; got content %q", res.Content) + } +}