xonecas.io
62159
Sy

symb / commit e56f387

fix: lint now passes

xonecas2026-02-14 e56f3879cd89aecc34cef9013077496d1f332145 parent bd472ec

25 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

cmd/symb/main.go+82−101
@@ -13,168 +13,149 @@ import (
1313 "github.com/xonecas/symb/internal/config"
1414 "github.com/xonecas/symb/internal/lsp"
1515 "github.com/xonecas/symb/internal/mcp"
16- "github.com/xonecas/symb/internal/mcp_tools"
16+ "github.com/xonecas/symb/internal/mcptools"
1717 "github.com/xonecas/symb/internal/provider"
1818 "github.com/xonecas/symb/internal/store"
1919 "github.com/xonecas/symb/internal/tui"
2020 )
2121
2222 func main() {
23- // Configure zerolog to write to file (TUI uses stdout)
2423 if err := setupFileLogging(); err != nil {
2524 fmt.Fprintf(os.Stderr, "Warning: failed to setup logging: %v\n", err)
2625 }
27- // Load configuration
28- configPath := filepath.Join(".", "config.toml")
29- cfg, err := config.Load(configPath)
26+
27+ cfg, err := config.Load(filepath.Join(".", "config.toml"))
3028 if err != nil {
3129 fmt.Printf("Error loading config: %v\n", err)
3230 os.Exit(1)
3331 }
3432
35- // Load credentials
3633 creds, err := config.LoadCredentials()
3734 if err != nil {
3835 fmt.Printf("Error loading credentials: %v\n", err)
3936 os.Exit(1)
4037 }
4138
42- // Create provider registry
43- registry := provider.NewRegistry()
39+ registry := buildRegistry(cfg, creds)
4440
45- // Register all providers from config
46- for name, providerCfg := range cfg.Providers {
47- var factory provider.ProviderFactory
41+ providerName, providerCfg := resolveProvider(cfg, registry)
42+
43+ prov, err := registry.Create(providerName, providerCfg.Model, providerCfg.Temperature)
44+ if err != nil {
45+ fmt.Printf("Error creating provider: %v\n", err)
46+ os.Exit(1)
47+ }
48+ defer prov.Close()
49+
50+ proxy, lspManager, showHandler, webCache := setupServices(cfg, creds)
51+ defer proxy.Close()
52+ defer lspManager.StopAll(context.Background())
53+ if webCache != nil {
54+ defer webCache.Close()
55+ }
56+
57+ tools, err := proxy.ListTools(context.Background())
58+ if err != nil {
59+ fmt.Printf("Warning: Failed to list tools: %v\n", err)
60+ tools = []mcp.Tool{}
61+ }
4862
63+ p := tea.NewProgram(
64+ tui.New(prov, proxy, tools, providerCfg.Model),
65+ tea.WithFilter(tui.MouseEventFilter),
66+ )
67+ showHandler.SetProgram(p)
68+ lspManager.SetCallback(func(absPath string, lines map[int]int) {
69+ p.Send(tui.LSPDiagnosticsMsg{FilePath: absPath, Lines: lines})
70+ })
71+
72+ if _, err := p.Run(); err != nil {
73+ fmt.Printf("Error running symb: %v\n", err)
74+ os.Exit(1)
75+ }
76+}
77+
78+func buildRegistry(cfg *config.Config, creds *config.Credentials) *provider.Registry {
79+ registry := provider.NewRegistry()
80+ for name, providerCfg := range cfg.Providers {
81+ var factory provider.Factory
4982 if providerCfg.APIKeyName != "" {
50- apiKey := creds.GetAPIKey(providerCfg.APIKeyName)
51- factory = provider.NewOpenCodeFactory(name, providerCfg.Endpoint, apiKey)
83+ factory = provider.NewOpenCodeFactory(name, providerCfg.Endpoint, creds.GetAPIKey(providerCfg.APIKeyName))
5284 } else {
5385 factory = provider.NewOllamaFactory(name, providerCfg.Endpoint)
5486 }
55-
5687 registry.RegisterFactory(name, factory)
5788 }
89+ return registry
90+}
5891
59- // Get default provider
60- providerName := cfg.DefaultProvider
61- if providerName == "" {
92+func resolveProvider(cfg *config.Config, registry *provider.Registry) (string, config.ProviderConfig) {
93+ name := cfg.DefaultProvider
94+ if name == "" {
6295 providers := registry.List()
6396 if len(providers) == 0 {
6497 fmt.Println("Error: No providers configured")
6598 os.Exit(1)
6699 }
67- providerName = providers[0]
100+ name = providers[0]
68101 }
69-
70- providerCfg, ok := cfg.Providers[providerName]
102+ pcfg, ok := cfg.Providers[name]
71103 if !ok {
72- fmt.Printf("Error: Provider %q not found\n", providerName)
104+ fmt.Printf("Error: Provider %q not found\n", name)
73105 os.Exit(1)
74106 }
107+ return name, pcfg
108+}
75109
76- // Create provider
77- prov, err := registry.Create(providerName, providerCfg.Model, providerCfg.Temperature)
78- if err != nil {
79- fmt.Printf("Error creating provider: %v\n", err)
80- os.Exit(1)
81- }
82- defer prov.Close()
83-
84- // Create MCP proxy
110+func setupServices(cfg *config.Config, creds *config.Credentials) (*mcp.Proxy, *lsp.Manager, *mcptools.ShowHandler, *store.Cache) {
85111 var mcpClient mcp.UpstreamClient
86112 if cfg.MCP.Upstream != "" {
87113 mcpClient = mcp.NewClient(cfg.MCP.Upstream)
88114 }
89-
90115 proxy := mcp.NewProxy(mcpClient)
91116 if err := proxy.Initialize(context.Background()); err != nil {
92117 fmt.Printf("Warning: MCP init failed: %v\n", err)
93118 }
94- defer proxy.Close()
95119
96- // Create LSP manager
97120 lspManager := lsp.NewManager()
98- defer lspManager.StopAll(context.Background())
121+ fileTracker := mcptools.NewFileReadTracker()
99122
100- // Register local tools
101- fileTracker := mcp_tools.NewFileReadTracker()
123+ readHandler := mcptools.NewReadHandler(fileTracker, lspManager)
124+ proxy.RegisterTool(mcptools.NewReadTool(), readHandler.Handle)
102125
103- readTool := mcp_tools.NewReadTool()
104- readHandler := mcp_tools.NewReadHandler(fileTracker, lspManager)
105- proxy.RegisterTool(readTool, readHandler.Handle)
126+ showHandler := mcptools.NewShowHandler()
127+ proxy.RegisterTool(mcptools.NewShowTool(), showHandler.Handle)
106128
107- showTool := mcp_tools.NewShowTool()
108- showHandler := mcp_tools.NewShowHandler()
109- proxy.RegisterTool(showTool, showHandler.Handle)
129+ proxy.RegisterTool(mcptools.NewGrepTool(), mcptools.MakeGrepHandler())
110130
111- grepTool := mcp_tools.NewGrepTool()
112- grepHandler := mcp_tools.MakeGrepHandler()
113- proxy.RegisterTool(grepTool, grepHandler)
131+ editHandler := mcptools.NewEditHandler(fileTracker, lspManager)
132+ proxy.RegisterTool(mcptools.NewEditTool(), editHandler.Handle)
114133
115- editTool := mcp_tools.NewEditTool()
116- editHandler := mcp_tools.NewEditHandler(fileTracker, lspManager)
117- proxy.RegisterTool(editTool, editHandler.Handle)
134+ webCache := openWebCache(cfg)
118135
119- // Open web cache (SQLite-backed, persisted across sessions).
120- // If data dir or db open fails, webCache stays nil — handlers degrade gracefully.
121- var webCache *store.Cache
122- if cacheDir, err := config.EnsureDataDir(); err != nil {
123- fmt.Printf("Warning: cache dir failed: %v\n", err)
124- } else {
125- cacheTTL := time.Duration(cfg.Cache.CacheTTLOrDefault()) * time.Hour
126- webCache, err = store.Open(filepath.Join(cacheDir, "cache.db"), cacheTTL)
127- if err != nil {
128- fmt.Printf("Warning: cache open failed: %v\n", err)
129- }
130- }
131- if webCache != nil {
132- defer webCache.Close()
133- }
134-
135- // Register git tools
136- gitStatusTool := mcp_tools.NewGitStatusTool()
137- proxy.RegisterTool(gitStatusTool, mcp_tools.MakeGitStatusHandler())
138-
139- gitDiffTool := mcp_tools.NewGitDiffTool()
140- proxy.RegisterTool(gitDiffTool, mcp_tools.MakeGitDiffHandler())
141-
142- // Register web tools
143- webFetchTool := mcp_tools.NewWebFetchTool()
144- webFetchHandler := mcp_tools.MakeWebFetchHandler(webCache)
145- proxy.RegisterTool(webFetchTool, webFetchHandler)
136+ proxy.RegisterTool(mcptools.NewGitStatusTool(), mcptools.MakeGitStatusHandler())
137+ proxy.RegisterTool(mcptools.NewGitDiffTool(), mcptools.MakeGitDiffHandler())
138+ proxy.RegisterTool(mcptools.NewWebFetchTool(), mcptools.MakeWebFetchHandler(webCache))
146139
147140 exaKey := creds.GetAPIKey("exa_ai")
148- webSearchTool := mcp_tools.NewWebSearchTool()
149- webSearchHandler := mcp_tools.MakeWebSearchHandler(webCache, exaKey, "")
150- proxy.RegisterTool(webSearchTool, webSearchHandler)
141+ proxy.RegisterTool(mcptools.NewWebSearchTool(), mcptools.MakeWebSearchHandler(webCache, exaKey, ""))
151142
152- // List all tools (local + upstream)
153- tools, err := proxy.ListTools(context.Background())
143+ return proxy, lspManager, showHandler, webCache
144+}
145+
146+func openWebCache(cfg *config.Config) *store.Cache {
147+ cacheDir, err := config.EnsureDataDir()
154148 if err != nil {
155- fmt.Printf("Warning: Failed to list tools: %v\n", err)
156- tools = []mcp.Tool{}
149+ fmt.Printf("Warning: cache dir failed: %v\n", err)
150+ return nil
157151 }
158-
159- // Create the BubbleTea program with model-specific prompt
160- p := tea.NewProgram(
161- tui.New(prov, proxy, tools, providerCfg.Model),
162- tea.WithFilter(tui.MouseEventFilter),
163- )
164-
165- // Set program reference for tools that need it
166- showHandler.SetProgram(p)
167-
168- // Wire LSP diagnostics callback to TUI
169- lspManager.SetCallback(func(absPath string, lines map[int]int) {
170- p.Send(tui.LSPDiagnosticsMsg{FilePath: absPath, Lines: lines})
171- })
172-
173- // Run the program
174- if _, err := p.Run(); err != nil {
175- fmt.Printf("Error running symb: %v\n", err)
176- os.Exit(1)
152+ cacheTTL := time.Duration(cfg.Cache.CacheTTLOrDefault()) * time.Hour
153+ cache, err := store.Open(filepath.Join(cacheDir, "cache.db"), cacheTTL)
154+ if err != nil {
155+ fmt.Printf("Warning: cache open failed: %v\n", err)
156+ return nil
177157 }
158+ return cache
178159 }
179160
180161 func setupFileLogging() error {
internal/constants/constants.go+1−1
@@ -57,4 +57,4 @@ package constants
5757 // - fruity, autumn, friendly, colorful, tango, algol, arduino
5858 // - base16-snazzy, borland, emacs, pygments, rainbow_dash
5959 // - and more...
60-const SyntaxTheme = "swapoff"
60+const SyntaxTheme = "modus-vivendi"
internal/filesearch/filesearch.go+57−56
@@ -56,7 +56,6 @@ func (s *Searcher) Search(ctx context.Context, opts Options) ([]Result, error) {
5656 }
5757 }
5858
59- // Compile regex pattern
6059 pattern := opts.Pattern
6160 if !opts.CaseSensitive {
6261 pattern = "(?i)" + pattern
@@ -68,80 +67,82 @@ func (s *Searcher) Search(ctx context.Context, opts Options) ([]Result, error) {
6867 }
6968
7069 var results []Result
71- err = filepath.WalkDir(opts.RootDir, func(path string, d os.DirEntry, err error) error {
72- if err != nil {
73- return nil // Skip errors
70+ err = filepath.WalkDir(opts.RootDir, func(path string, d os.DirEntry, walkErr error) error {
71+ if walkErr != nil {
72+ return nil
7473 }
75-
76- // Check context cancellation
7774 select {
7875 case <-ctx.Done():
7976 return ctx.Err()
8077 default:
8178 }
82-
83- relPath, err := filepath.Rel(opts.RootDir, path)
84- if err != nil {
85- return nil
86- }
87-
88- // Skip .git directory
89- if d.IsDir() && d.Name() == ".git" {
90- return filepath.SkipDir
91- }
92-
93- // Check gitignore
94- if s.gitignore.Matches(relPath, d.IsDir()) {
95- if d.IsDir() {
96- return filepath.SkipDir
97- }
98- return nil
99- }
100-
101- if d.IsDir() {
102- return nil
103- }
104-
105- // Check file size (skip large files)
106- info, err := d.Info()
107- if err != nil {
108- return nil
109- }
110- if info.Size() > 10*1024*1024 { // Skip files > 10MB
111- return nil
112- }
113-
114- if opts.ContentSearch {
115- // Search file contents
116- matches, err := s.searchFileContent(path, relPath, regex)
117- if err != nil {
118- return nil // Skip files we can't read
119- }
120- results = append(results, matches...)
121- } else {
122- // Search filename only
123- if regex.MatchString(filepath.Base(path)) || regex.MatchString(relPath) {
124- results = append(results, Result{
125- Path: relPath,
126- })
127- }
79+ if skip := s.shouldSkip(path, d, opts.RootDir); skip != nil {
80+ return *skip
12881 }
129-
130- // Check max results
82+ matches := s.matchEntry(path, opts.RootDir, regex, opts.ContentSearch)
83+ results = append(results, matches...)
13184 if opts.MaxResults > 0 && len(results) >= opts.MaxResults {
13285 return filepath.SkipAll
13386 }
134-
13587 return nil
13688 })
13789
13890 if err != nil && err != filepath.SkipAll {
13991 return nil, err
14092 }
141-
14293 return results, nil
14394 }
14495
96+const maxSearchFileSize = 10 * 1024 * 1024 // 10 MB
97+
98+// shouldSkip decides whether to skip a directory entry. Returns nil to proceed,
99+// or a pointer to the error to return from the walk callback.
100+func (s *Searcher) shouldSkip(path string, d os.DirEntry, rootDir string) *error {
101+ relPath, err := filepath.Rel(rootDir, path)
102+ if err != nil {
103+ skip := error(nil)
104+ return &skip
105+ }
106+ if d.IsDir() && d.Name() == ".git" {
107+ skip := filepath.SkipDir
108+ return &skip
109+ }
110+ if s.gitignore.Matches(relPath, d.IsDir()) {
111+ if d.IsDir() {
112+ skip := filepath.SkipDir
113+ return &skip
114+ }
115+ skip := error(nil)
116+ return &skip
117+ }
118+ if d.IsDir() {
119+ skip := error(nil)
120+ return &skip
121+ }
122+ info, err := d.Info()
123+ if err != nil || info.Size() > maxSearchFileSize {
124+ skip := error(nil)
125+ return &skip
126+ }
127+ return nil
128+}
129+
130+// matchEntry checks a single file against the search pattern.
131+func (s *Searcher) matchEntry(path, rootDir string, regex *regexp.Regexp, contentSearch bool) []Result {
132+ relPath, _ := filepath.Rel(rootDir, path)
133+ if contentSearch {
134+ matches, err := s.searchFileContent(path, relPath, regex)
135+ if err != nil {
136+ return nil
137+ }
138+ return matches
139+ }
140+ if regex.MatchString(filepath.Base(path)) || regex.MatchString(relPath) {
141+ return []Result{{Path: relPath}}
142+ }
143+ return nil
144+}
145+
145146 // searchFileContent searches a single file for pattern matches.
146147 func (s *Searcher) searchFileContent(absPath, relPath string, regex *regexp.Regexp) ([]Result, error) {
147148 file, err := os.Open(absPath)
internal/filesearch/gitignore.go+58−58
@@ -143,79 +143,79 @@ func parseGitignorePattern(pattern string) *gitignorePattern {
143143 func gitignoreGlobToRegex(pattern string) string {
144144 var result strings.Builder
145145
146- // Anchor patterns that start with /
147146 anchored := false
148147 if strings.HasPrefix(pattern, "/") {
149148 result.WriteString("^")
150149 pattern = pattern[1:]
151150 anchored = true
152151 } else {
153- // Match anywhere in path
154152 result.WriteString("(^|/)")
155153 }
156154
157- i := 0
158- for i < len(pattern) {
159- ch := pattern[i]
160- switch ch {
161- case '*':
162- if i+1 < len(pattern) && pattern[i+1] == '*' {
163- // ** matches any number of directories
164- if i+2 < len(pattern) && pattern[i+2] == '/' {
165- result.WriteString("(.*/)?")
166- i += 3
167- continue
168- }
169- result.WriteString(".*")
170- i += 2
171- } else {
172- // * matches anything except /
173- result.WriteString("[^/]*")
174- i++
175- }
176- case '?':
177- result.WriteString("[^/]")
178- i++
179- case '.', '+', '(', ')', '|', '^', '$', '@', '%':
180- // Escape regex special characters
181- result.WriteByte('\\')
182- result.WriteByte(ch)
183- i++
184- case '[':
185- // Character class - find the closing ]
186- j := i + 1
187- for j < len(pattern) && pattern[j] != ']' {
188- j++
189- }
190- if j < len(pattern) {
191- result.WriteString(pattern[i : j+1])
192- i = j + 1
193- } else {
194- result.WriteString("\\[")
195- i++
196- }
197- case '\\':
198- // Escape next character
199- if i+1 < len(pattern) {
200- result.WriteByte('\\')
201- result.WriteByte(pattern[i+1])
202- i += 2
203- } else {
204- result.WriteString("\\\\")
205- i++
206- }
207- default:
208- result.WriteByte(ch)
209- i++
210- }
155+ for i := 0; i < len(pattern); {
156+ i += convertGlobChar(&result, pattern, i)
211157 }
212158
213- // For anchored patterns, don't allow matching subdirectories
214159 if anchored {
215160 result.WriteString("$")
216161 } else {
217162 result.WriteString("(/.*)?$")
218163 }
219-
220164 return result.String()
221165 }
166+
167+// convertGlobChar writes the regex equivalent of pattern[i] into b and returns
168+// the number of characters consumed.
169+func convertGlobChar(b *strings.Builder, pattern string, i int) int {
170+ ch := pattern[i]
171+ switch ch {
172+ case '*':
173+ return convertGlobStar(b, pattern, i)
174+ case '?':
175+ b.WriteString("[^/]")
176+ return 1
177+ case '.', '+', '(', ')', '|', '^', '$', '@', '%':
178+ b.WriteByte('\\')
179+ b.WriteByte(ch)
180+ return 1
181+ case '[':
182+ return convertGlobCharClass(b, pattern, i)
183+ case '\\':
184+ if i+1 < len(pattern) {
185+ b.WriteByte('\\')
186+ b.WriteByte(pattern[i+1])
187+ return 2
188+ }
189+ b.WriteString("\\\\")
190+ return 1
191+ default:
192+ b.WriteByte(ch)
193+ return 1
194+ }
195+}
196+
197+func convertGlobStar(b *strings.Builder, pattern string, i int) int {
198+ if i+1 < len(pattern) && pattern[i+1] == '*' {
199+ if i+2 < len(pattern) && pattern[i+2] == '/' {
200+ b.WriteString("(.*/)?")
201+ return 3
202+ }
203+ b.WriteString(".*")
204+ return 2
205+ }
206+ b.WriteString("[^/]*")
207+ return 1
208+}
209+
210+func convertGlobCharClass(b *strings.Builder, pattern string, i int) int {
211+ j := i + 1
212+ for j < len(pattern) && pattern[j] != ']' {
213+ j++
214+ }
215+ if j < len(pattern) {
216+ b.WriteString(pattern[i : j+1])
217+ return j + 1 - i
218+ }
219+ b.WriteString("\\[")
220+ return 1
221+}
internal/mcptools/edit.go+28−37
@@ -1,4 +1,4 @@
1-package mcp_tools
1+package mcptools
22
33 import (
44 "context"
@@ -123,12 +123,31 @@ func (h *EditHandler) Handle(ctx context.Context, arguments json.RawMessage) (*m
123123 if err := json.Unmarshal(arguments, &args); err != nil {
124124 return toolError("Invalid arguments: %v", err), nil
125125 }
126-
127126 if args.File == "" {
128127 return toolError("File path cannot be empty"), nil
129128 }
129+ if err := validateEditOps(args); err != nil {
130+ return toolError("%v", err), nil
131+ }
132+
133+ absPath, err := validatePath(args.File)
134+ if err != nil {
135+ return toolError("%v", err), nil
136+ }
130137
131- // Count operations — exactly one must be set
138+ if args.Create != nil {
139+ return h.handleCreate(ctx, absPath, args.File, args.Create)
140+ }
141+
142+ if !h.tracker.WasRead(absPath) {
143+ return toolError("You must Read the file before editing it. Use Read on %s first — you need the line hashes.", args.File), nil
144+ }
145+
146+ return h.applyEdit(ctx, absPath, args)
147+}
148+
149+// validateEditOps ensures exactly one operation is specified.
150+func validateEditOps(args EditArgs) error {
132151 ops := 0
133152 if args.Replace != nil {
134153 ops++
@@ -143,36 +162,13 @@ func (h *EditHandler) Handle(ctx context.Context, arguments json.RawMessage) (*m
143162 ops++
144163 }
145164 if ops != 1 {
146- return toolError("Exactly one operation (replace, insert, delete, or create) must be specified"), nil
147- }
148-
149- // Security: validate path
150- absPath, err := filepath.Abs(args.File)
151- if err != nil {
152- return toolError("Invalid file path: %v", err), nil
153- }
154-
155- workingDir, err := os.Getwd()
156- if err != nil {
157- return toolError("Failed to get working directory: %v", err), nil
158- }
159-
160- relPath, err := filepath.Rel(workingDir, absPath)
161- if err != nil || strings.HasPrefix(relPath, "..") || filepath.IsAbs(relPath) {
162- return toolError("Access denied: path outside working directory"), nil
163- }
164-
165- // Dispatch to operation handler
166- if args.Create != nil {
167- return h.handleCreate(ctx, absPath, args.File, args.Create)
168- }
169-
170- // Enforce read-before-edit: file must have been Read first
171- if !h.tracker.WasRead(absPath) {
172- return toolError("You must Read the file before editing it. Use Read on %s first — you need the line hashes.", args.File), nil
165+ return fmt.Errorf("exactly one operation (replace, insert, delete, or create) must be specified")
173166 }
167+ return nil
168+}
174169
175- // All other ops require reading the existing file
170+// applyEdit reads the file, applies the edit operation, writes it back, and returns fresh hashes.
171+func (h *EditHandler) applyEdit(ctx context.Context, absPath string, args EditArgs) (*mcp.ToolResult, error) {
176172 content, err := os.ReadFile(absPath)
177173 if err != nil {
178174 return toolError("Failed to read file: %v", err), nil
@@ -188,7 +184,6 @@ func (h *EditHandler) Handle(ctx context.Context, arguments json.RawMessage) (*m
188184 case args.Delete != nil:
189185 result, err = applyDelete(lines, args.Delete)
190186 }
191-
192187 if err != nil {
193188 return toolError("%v", err), nil
194189 }
@@ -197,13 +192,9 @@ func (h *EditHandler) Handle(ctx context.Context, arguments json.RawMessage) (*m
197192 return toolError("Failed to write file: %v", err), nil
198193 }
199194
200- // Return hashline-tagged view of the updated file
201195 tagged := hashline.TagLines(result, 1)
202- taggedOutput := hashline.FormatTagged(tagged)
203-
204- text := fmt.Sprintf("Edited %s (%d lines):\n\n%s", args.File, len(tagged), taggedOutput)
196+ text := fmt.Sprintf("Edited %s (%d lines):\n\n%s", args.File, len(tagged), hashline.FormatTagged(tagged))
205197
206- // Closed-loop LSP diagnostics: notify and wait for errors/warnings.
207198 if h.lspManager != nil {
208199 diags := h.lspManager.NotifyAndWait(ctx, absPath, 5*time.Second)
209200 text += lsp.FormatDiagnostics(args.File, diags)
internal/mcptools/edit_test.go+3−3
@@ -1,4 +1,4 @@
1-package mcp_tools
1+package mcptools
22
33 import (
44 "context"
@@ -353,8 +353,8 @@ func TestEditRequiresReadFirst(t *testing.T) {
353353 if !isErr {
354354 t.Fatal("should fail when file was not read first")
355355 }
356- if !strings.Contains(text, "Open") {
357- t.Errorf("error should mention Open tool: %s", text)
356+ if !strings.Contains(text, "Read") {
357+ t.Errorf("error should mention Read tool: %s", text)
358358 }
359359
360360 // Now mark as read and retry — should succeed
internal/mcptools/filetrack.go+1−1
@@ -1,4 +1,4 @@
1-package mcp_tools
1+package mcptools
22
33 import "sync"
44
internal/mcptools/git.go+1−1
@@ -1,4 +1,4 @@
1-package mcp_tools
1+package mcptools
22
33 import (
44 "bytes"
internal/mcptools/git_test.go+1−1
@@ -1,4 +1,4 @@
1-package mcp_tools
1+package mcptools
22
33 import (
44 "context"
internal/mcptools/gitdiff.go+1−1
@@ -1,4 +1,4 @@
1-package mcp_tools
1+package mcptools
22
33 import (
44 "bytes"
internal/mcptools/grep.go+2−2
@@ -1,5 +1,5 @@
1-// Package mcp_tools provides local MCP tool implementations.
2-package mcp_tools
1+// Package mcptools provides local MCP tool implementations.
2+package mcptools
33
44 import (
55 "context"
internal/mcptools/open.go+47−88
@@ -1,4 +1,4 @@
1-package mcp_tools
1+package mcptools
22
33 import (
44 "context"
@@ -57,111 +57,34 @@ func NewReadHandler(tracker *FileReadTracker, lspManager *lsp.Manager) *ReadHand
5757 }
5858
5959 // Handle implements the mcp.ToolHandler interface.
60-func (h *ReadHandler) Handle(ctx context.Context, arguments json.RawMessage) (*mcp.ToolResult, error) {
60+func (h *ReadHandler) Handle(_ context.Context, arguments json.RawMessage) (*mcp.ToolResult, error) {
6161 var args ReadArgs
6262 if err := json.Unmarshal(arguments, &args); err != nil {
63- return &mcp.ToolResult{
64- Content: []mcp.ContentBlock{{Type: "text", Text: fmt.Sprintf("Invalid arguments: %v", err)}},
65- IsError: true,
66- }, nil
63+ return toolError("Invalid arguments: %v", err), nil
6764 }
68-
6965 if args.File == "" {
70- return &mcp.ToolResult{
71- Content: []mcp.ContentBlock{{Type: "text", Text: "File path cannot be empty"}},
72- IsError: true,
73- }, nil
74- }
75-
76- // Security: Convert to absolute path and validate
77- absPath, err := filepath.Abs(args.File)
78- if err != nil {
79- return &mcp.ToolResult{
80- Content: []mcp.ContentBlock{{Type: "text", Text: fmt.Sprintf("Invalid file path: %v", err)}},
81- IsError: true,
82- }, nil
66+ return toolError("File path cannot be empty"), nil
8367 }
8468
85- // Get current working directory for validation
86- workingDir, err := os.Getwd()
69+ absPath, err := validatePath(args.File)
8770 if err != nil {
88- return &mcp.ToolResult{
89- Content: []mcp.ContentBlock{{Type: "text", Text: fmt.Sprintf("Failed to get working directory: %v", err)}},
90- IsError: true,
91- }, nil
71+ return toolError("%v", err), nil
9272 }
9373
94- // Security: Prevent path traversal - only allow files within or below working directory
95- relPath, err := filepath.Rel(workingDir, absPath)
96- if err != nil || strings.HasPrefix(relPath, "..") || filepath.IsAbs(relPath) {
97- return &mcp.ToolResult{
98- Content: []mcp.ContentBlock{{Type: "text", Text: "Access denied: path outside working directory"}},
99- IsError: true,
100- }, nil
101- }
102-
103- // Read file content
10474 content, err := os.ReadFile(absPath)
10575 if err != nil {
106- return &mcp.ToolResult{
107- Content: []mcp.ContentBlock{{Type: "text", Text: fmt.Sprintf("Failed to read file: %v", err)}},
108- IsError: true,
109- }, nil
76+ return toolError("Failed to read file: %v", err), nil
11077 }
11178
112- // Record that this file was read (enables editing)
11379 h.tracker.MarkRead(absPath)
114-
115- // Warm up LSP for this file (fire-and-forget).
116- // Use Background context since this outlives the tool-call context.
11780 if h.lspManager != nil {
11881 go h.lspManager.TouchFile(context.Background(), absPath)
11982 }
12083
12184 lines := strings.Split(string(content), "\n")
122-
123- // Extract line range if specified
124- var selectedContent string
125- if args.Start > 0 || args.End > 0 {
126- start := args.Start
127- end := args.End
128-
129- // Default start to 1 if not specified
130- if start <= 0 {
131- start = 1
132- }
133-
134- // Validate start is in range
135- if start < 1 || start > len(lines) {
136- return &mcp.ToolResult{
137- Content: []mcp.ContentBlock{{Type: "text", Text: fmt.Sprintf("Start line %d out of range (file has %d lines)", start, len(lines))}},
138- IsError: true,
139- }, nil
140- }
141-
142- // Default end to end of file if not specified or out of range
143- if end <= 0 || end > len(lines) {
144- end = len(lines)
145- }
146-
147- // Validate range
148- if start > end {
149- return &mcp.ToolResult{
150- Content: []mcp.ContentBlock{{Type: "text", Text: fmt.Sprintf("Invalid range: start (%d) > end (%d)", start, end)}},
151- IsError: true,
152- }, nil
153- }
154-
155- // Extract range (convert to 0-indexed)
156- selectedContent = strings.Join(lines[start-1:end], "\n")
157- } else {
158- selectedContent = string(content)
159- }
160-
161- // Return hashline-tagged content to the LLM
162- startLine := 1
163- if args.Start > 0 {
164- startLine = args.Start
85+ selectedContent, startLine, err := extractRange(lines, string(content), args.Start, args.End)
86+ if err != nil {
87+ return toolError("%v", err), nil
16588 }
16689
16790 tagged := hashline.TagLines(selectedContent, startLine)
@@ -178,10 +101,46 @@ func (h *ReadHandler) Handle(ctx context.Context, arguments json.RawMessage) (*m
178101
179102 return &mcp.ToolResult{
180103 Content: []mcp.ContentBlock{{Type: "text", Text: fmt.Sprintf("Read %s%s (%d lines):\n\n%s", args.File, rangeInfo, len(tagged), taggedOutput)}},
181- IsError: false,
182104 }, nil
183105 }
184106
107+// validatePath resolves a file path, ensuring it's within the working directory.
108+func validatePath(file string) (string, error) {
109+ absPath, err := filepath.Abs(file)
110+ if err != nil {
111+ return "", fmt.Errorf("invalid file path: %w", err)
112+ }
113+ workingDir, err := os.Getwd()
114+ if err != nil {
115+ return "", fmt.Errorf("failed to get working directory: %w", err)
116+ }
117+ relPath, err := filepath.Rel(workingDir, absPath)
118+ if err != nil || strings.HasPrefix(relPath, "..") || filepath.IsAbs(relPath) {
119+ return "", fmt.Errorf("access denied: path outside working directory")
120+ }
121+ return absPath, nil
122+}
123+
124+// extractRange returns the selected content and start line number for a line range.
125+func extractRange(lines []string, full string, start, end int) (string, int, error) {
126+ if start <= 0 && end <= 0 {
127+ return full, 1, nil
128+ }
129+ if start <= 0 {
130+ start = 1
131+ }
132+ if start < 1 || start > len(lines) {
133+ return "", 0, fmt.Errorf("start line %d out of range (file has %d lines)", start, len(lines))
134+ }
135+ if end <= 0 || end > len(lines) {
136+ end = len(lines)
137+ }
138+ if start > end {
139+ return "", 0, fmt.Errorf("invalid range: start (%d) > end (%d)", start, end)
140+ }
141+ return strings.Join(lines[start-1:end], "\n"), start, nil
142+}
143+
185144 // DetectLanguage returns the Chroma language identifier based on file extension.
186145 func DetectLanguage(path string) string {
187146 // Map common extensions to Chroma language identifiers
internal/mcptools/show.go+1−1
@@ -1,4 +1,4 @@
1-package mcp_tools
1+package mcptools
22
33 import (
44 "context"
internal/mcptools/web.go+15−16
@@ -1,4 +1,4 @@
1-package mcp_tools
1+package mcptools
22
33 import (
44 "bytes"
@@ -279,39 +279,38 @@ func formatSearchResults(results []exaResult) string {
279279 return b.String()
280280 }
281281
282+// isSkipTag returns true for tags whose content should be suppressed.
283+func isSkipTag(tag string) bool {
284+ return tag == "script" || tag == "style" || tag == "noscript"
285+}
286+
282287 // extractText parses HTML and returns visible text content.
283288 // Strips script, style, and noscript elements.
284289 func extractText(data []byte) string {
285290 tokenizer := html.NewTokenizer(bytes.NewReader(data))
286291 var b strings.Builder
287- skip := 0 // nesting depth inside skip elements
292+ skip := 0
288293
289294 for {
290295 tt := tokenizer.Next()
291- switch tt {
292- case html.ErrorToken:
296+ if tt == html.ErrorToken {
293297 return collapseWhitespace(b.String())
298+ }
299+ tn, _ := tokenizer.TagName()
300+ tag := string(tn)
294301
302+ switch tt {
295303 case html.StartTagToken, html.SelfClosingTagToken:
296- tn, _ := tokenizer.TagName()
297- tag := string(tn)
298- if tag == "script" || tag == "style" || tag == "noscript" {
304+ if isSkipTag(tag) {
299305 skip++
300306 }
301- // Insert whitespace for block elements.
302307 if isBlockElement(tag) && b.Len() > 0 {
303308 b.WriteByte('\n')
304309 }
305-
306310 case html.EndTagToken:
307- tn, _ := tokenizer.TagName()
308- tag := string(tn)
309- if tag == "script" || tag == "style" || tag == "noscript" {
310- if skip > 0 {
311- skip--
312- }
311+ if isSkipTag(tag) && skip > 0 {
312+ skip--
313313 }
314-
315314 case html.TextToken:
316315 if skip == 0 {
317316 b.Write(tokenizer.Text())
internal/mcptools/web_test.go+1−1
@@ -1,4 +1,4 @@
1-package mcp_tools
1+package mcptools
22
33 import (
44 "context"
internal/provider/anthropic.go+70−60
@@ -204,27 +204,35 @@ func toAnthropicTools(tools []Tool) []anthropicTool {
204204 // event: message_start / content_block_start / content_block_delta /
205205 // content_block_stop / message_delta / message_stop / ping
206206 // data: { JSON payload }
207+//
208+// anthropicBlockTracker maps Anthropic block indices to tool call indices.
209+type anthropicBlockTracker struct {
210+ toolCallCount int
211+ blockIsToolUse map[int]bool
212+ blockToolIndex map[int]int
213+}
214+
215+func newAnthropicBlockTracker() *anthropicBlockTracker {
216+ return &anthropicBlockTracker{
217+ blockIsToolUse: make(map[int]bool),
218+ blockToolIndex: make(map[int]int),
219+ }
220+}
221+
207222 func parseAnthropicSSEStream(ctx context.Context, reader io.Reader, ch chan<- StreamEvent) {
208223 scanner := bufio.NewScanner(reader)
209224 scanner.Buffer(make([]byte, 0, 64*1024), 512*1024)
210225
211- // Track tool call index mapping: anthropic block index -> our tool call counter
212- toolCallCount := 0
213- blockIsToolUse := make(map[int]bool)
214- blockToolIndex := make(map[int]int)
215-
226+ bt := newAnthropicBlockTracker()
216227 var currentEventType string
217228
218229 for scanner.Scan() {
219230 line := scanner.Text()
220231
221- // Parse event type line
222232 if strings.HasPrefix(line, "event: ") {
223233 currentEventType = strings.TrimPrefix(line, "event: ")
224234 continue
225235 }
226-
227- // Parse data line
228236 if !strings.HasPrefix(line, "data: ") {
229237 continue
230238 }
@@ -234,60 +242,14 @@ func parseAnthropicSSEStream(ctx context.Context, reader io.Reader, ch chan<- St
234242 case "message_stop":
235243 trySend(ctx, ch, StreamEvent{Type: EventDone})
236244 return
237-
238245 case "content_block_start":
239- var evt anthropicContentBlockStart
240- if err := json.Unmarshal([]byte(data), &evt); err != nil {
241- log.Warn().Err(err).Msg("Failed to parse anthropic content_block_start")
242- continue
243- }
244- if evt.ContentBlock.Type == "tool_use" {
245- idx := toolCallCount
246- toolCallCount++
Cut short: this commit's diff is over 1000 lines.
internal/provider/openai_common.go+101−98
Cut short: this commit's diff is over 1000 lines.
internal/provider/provider.go+4−4
Cut short: this commit's diff is over 1000 lines.
internal/tui/editor/update.go+171−148
Cut short: this commit's diff is over 1000 lines.
internal/tui/editor/view.go+236−228
Cut short: this commit's diff is over 1000 lines.
internal/tui/mouse.go+109−82
Cut short: this commit's diff is over 1000 lines.
internal/tui/selection.go+1−1
Cut short: this commit's diff is over 1000 lines.
internal/tui/styles.go+1−1
Cut short: this commit's diff is over 1000 lines.
internal/tui/update.go+136−131
Cut short: this commit's diff is over 1000 lines.
internal/tui/view.go+78−80
Cut short: this commit's diff is over 1000 lines.