xonecas.io
62159
Sy

symb / commit fe74780

feat: agentic loop

xonecas2026-02-11 fe74780ab969fdda87718eee58d4d52410717774 parent 35829ed

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.

AGENTS.md+1−0
@@ -16,3 +16,4 @@
1616 - Go & Golintci
1717 - Bubbletea, Bubbles and Lipgloss.
1818 - Use Makefile commands to build, lint and test.
19+- Use `journalctl -u ollama --no-pager -n 100` to see ollama logs
cmd/symb/main.go+117−3
@@ -1,19 +1,108 @@
11 package main
22
33 import (
4+ "context"
45 "fmt"
56 "os"
7+ "path/filepath"
68
79 tea "github.com/charmbracelet/bubbletea"
10+ "github.com/rs/zerolog"
11+ "github.com/rs/zerolog/log"
12+ "github.com/xonecas/symb/internal/config"
13+ "github.com/xonecas/symb/internal/mcp"
14+ "github.com/xonecas/symb/internal/provider"
815 "github.com/xonecas/symb/internal/tui"
916 )
1017
1118 func main() {
19+ // Configure zerolog to write to file (TUI uses stdout)
20+ if err := setupFileLogging(); err != nil {
21+ fmt.Fprintf(os.Stderr, "Warning: failed to setup logging: %v\n", err)
22+ }
23+ // Load configuration
24+ configPath := filepath.Join(".", "config.toml")
25+ cfg, err := config.Load(configPath)
26+ if err != nil {
27+ fmt.Printf("Error loading config: %v\n", err)
28+ os.Exit(1)
29+ }
30+
31+ // Load credentials
32+ creds, err := config.LoadCredentials()
33+ if err != nil {
34+ fmt.Printf("Error loading credentials: %v\n", err)
35+ os.Exit(1)
36+ }
37+
38+ // Create provider registry
39+ registry := provider.NewRegistry()
40+
41+ // Register all providers from config
42+ for name, providerCfg := range cfg.Providers {
43+ var factory provider.ProviderFactory
44+
45+ if providerCfg.APIKeyName != "" {
46+ apiKey := creds.GetAPIKey(providerCfg.APIKeyName)
47+ factory = provider.NewOpenCodeFactory(name, providerCfg.Endpoint, apiKey)
48+ } else {
49+ factory = provider.NewOllamaFactory(name, providerCfg.Endpoint)
50+ }
51+
52+ registry.RegisterFactory(name, factory)
53+ }
54+
55+ // Get default provider
56+ providerName := cfg.DefaultProvider
57+ if providerName == "" {
58+ providers := registry.List()
59+ if len(providers) == 0 {
60+ fmt.Println("Error: No providers configured")
61+ os.Exit(1)
62+ }
63+ providerName = providers[0]
64+ }
65+
66+ providerCfg, ok := cfg.Providers[providerName]
67+ if !ok {
68+ fmt.Printf("Error: Provider %q not found\n", providerName)
69+ os.Exit(1)
70+ }
71+
72+ // Create provider
73+ prov, err := registry.Create(providerName, providerCfg.Model, providerCfg.Temperature)
74+ if err != nil {
75+ fmt.Printf("Error creating provider: %v\n", err)
76+ os.Exit(1)
77+ }
78+ defer prov.Close()
79+
80+ // Create MCP proxy
81+ var mcpClient mcp.UpstreamClient
82+ if cfg.MCP.Upstream != "" {
83+ mcpClient = mcp.NewClient(cfg.MCP.Upstream)
84+ } else {
85+ mcpClient = mcp.NewStubClient()
86+ }
87+
88+ proxy := mcp.NewProxy(mcpClient)
89+ if err := proxy.Initialize(context.Background()); err != nil {
90+ fmt.Printf("Warning: MCP init failed: %v\n", err)
91+ }
92+ defer proxy.Close()
93+
94+ // List tools
95+ tools, err := proxy.ListTools(context.Background())
96+ if err != nil {
97+ fmt.Printf("Warning: Failed to list tools: %v\n", err)
98+ tools = []mcp.Tool{}
99+ }
100+
12101 // Create the BubbleTea program
13102 p := tea.NewProgram(
14- tui.New(),
15- tea.WithAltScreen(), // Use alternate screen buffer
16- tea.WithMouseCellMotion(), // Enable mouse support
103+ tui.New(prov, proxy, tools),
104+ tea.WithAltScreen(),
105+ tea.WithMouseCellMotion(),
17106 )
18107
19108 // Run the program
@@ -22,3 +111,28 @@ func main() {
22111 os.Exit(1)
23112 }
24113 }
114+
115+func setupFileLogging() error {
116+ zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
117+
118+ dataDir, err := config.DataDir()
119+ if err != nil {
120+ return err
121+ }
122+
123+ logDir := filepath.Join(dataDir, "logs")
124+ if err := os.MkdirAll(logDir, 0750); err != nil {
125+ return err
126+ }
127+
128+ logFile := filepath.Join(logDir, "symb.log")
129+ file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
130+ if err != nil {
131+ return err
132+ }
133+
134+ log.Logger = log.Output(file)
135+ zerolog.SetGlobalLevel(zerolog.InfoLevel)
136+
137+ return nil
138+}
config.toml+48−12
@@ -1,19 +1,55 @@
11 # Symb Configuration File
22
3-[llm]
4-provider = "ollama" # Options: "ollama", "opencode-zen"
3+# Default provider (optional - if not set, first provider in map is used)
4+default_provider = "ollama-qwen"
5+
6+# Ollama providers (local)
7+[providers.ollama-qwen]
8+endpoint = "http://localhost:11434"
9+model = "qwen3:8b"
10+temperature = 0.3
11+
12+[providers.ollama-qwen-small]
13+endpoint = "http://localhost:11434"
14+model = "qwen3:4b"
15+temperature = 0.3
16+
17+[providers.ollama-llama]
18+endpoint = "http://localhost:11434"
19+model = "llama3.1:8b"
20+temperature = 0.3
21+
22+[providers.ollama-llama32]
23+endpoint = "http://localhost:11434"
524 model = "llama3.2"
6-base_url = "http://localhost:11434"
7-api_key = ""
25+temperature = 0.3
826
9-[editor]
10-tab_size = 4
11-show_line_nums = true
12-syntax_theme = "monokai"
27+[providers.mfd-deepseek]
28+endpoint = "http://localhost:11434"
29+model = "MFDoom/deepseek-r1-tool-calling:14b"
30+temperature = 0.3
1331
14-[git]
15-enable_sandbox = false # Enable git worktree sandboxing (experimental)
32+# OpenCode Zen providers (cloud)
33+[providers.zen-nano]
34+endpoint = "https://opencode.ai/zen/v1"
35+model = "gpt-5-nano"
36+api_key_name = "opencode_zen"
37+temperature = 0.3
1638
39+[providers.zen-pickle]
40+endpoint = "https://opencode.ai/zen/v1"
41+model = "big-pickle"
42+api_key_name = "opencode_zen"
43+temperature = 0.3
44+
45+[mcp]
46+upstream = ""
47+
48+# UI settings for Symb TUI
1749 [ui]
18-theme = "molokai" # Cursor and spinner color.
19-split_ratio = 0.5 # Editor:Agent pane split ratio (0.0-1.0)
50+theme = "molokai"
51+split_ratio = 0.5
52+syntax_theme = "monokai"
53+
54+[git]
55+enable_sandbox = false
docs/DESIGN.md+30−0
@@ -128,3 +128,33 @@ Confidence Level: High for a prototype. The ecosystem is ready.
128128 - Sandboxed worktrees
129129 - Sub-agents
130130 - Context optimization with tree-sitter
131+
132+# Agent message:
133+
134+````text
135+
136+Done! The textarea is now wired to send messages to the LLM when the user presses Enter:
137+ 1. Model - Added LLM components (provider, proxy, tools, history)
138+ 2. New() - Takes provider, proxy, and tools as parameters
139+ 3. sendToLLM() - ELM command that processes user input through LLM
140+ 4. Enter key - Captures input, clears textarea, sends to LLM
141+ 5. main.go - Initializes all components and passes to TUI
142+
143+→ Read(...)
144+← Write(...)
145+
146+All done!
147+
148+XXs 00:00 ───────────────────────── // DarkGray color, timestamp and duration of the LLM response: `10s 19:57`
149+```
150+
151+# User Message
152+
153+```
154+Thanks! Can you look into these: // User messages use GrayColor
155+ - one
156+ - two
157+
158+XXs 00:00 ───────────────────────── // DarkGray color
159+
160+````
go.mod+9−5
@@ -3,19 +3,24 @@ module github.com/xonecas/symb
33 go 1.25.6
44
55 require (
6+ github.com/BurntSushi/toml v1.6.0
7+ github.com/alecthomas/chroma/v2 v2.23.1
8+ github.com/atotto/clipboard v0.1.4
69 github.com/charmbracelet/bubbles v1.0.0
710 github.com/charmbracelet/bubbletea v1.3.10
811 github.com/charmbracelet/lipgloss v1.1.0
12+ github.com/charmbracelet/x/ansi v0.11.6
913 github.com/charmbracelet/x/exp/golden v0.0.0-20260209194814-eeb2896ac759
14+ github.com/mattn/go-runewidth v0.0.19
15+ github.com/rivo/uniseg v0.4.7
16+ github.com/rs/zerolog v1.34.0
17+ github.com/sashabaranov/go-openai v1.41.2
1018 )
1119
1220 require (
13- github.com/alecthomas/chroma/v2 v2.23.1 // indirect
14- github.com/atotto/clipboard v0.1.4 // indirect
1521 github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
1622 github.com/aymanbagabas/go-udiff v0.3.1 // indirect
1723 github.com/charmbracelet/colorprofile v0.4.1 // indirect
18- github.com/charmbracelet/x/ansi v0.11.6 // indirect
1924 github.com/charmbracelet/x/cellbuf v0.0.15 // indirect
2025 github.com/charmbracelet/x/term v0.2.2 // indirect
2126 github.com/clipperhouse/displaywidth v0.9.0 // indirect
@@ -24,13 +29,12 @@ require (
2429 github.com/dlclark/regexp2 v1.11.5 // indirect
2530 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
2631 github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
32+ github.com/mattn/go-colorable v0.1.13 // indirect
2733 github.com/mattn/go-isatty v0.0.20 // indirect
2834 github.com/mattn/go-localereader v0.0.1 // indirect
29- github.com/mattn/go-runewidth v0.0.19 // indirect
3035 github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
3136 github.com/muesli/cancelreader v0.2.2 // indirect
3237 github.com/muesli/termenv v0.16.0 // indirect
33- github.com/rivo/uniseg v0.4.7 // indirect
3438 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
3539 golang.org/x/sys v0.38.0 // indirect
3640 golang.org/x/text v0.3.8 // indirect
go.sum+22−2
@@ -1,7 +1,11 @@
1-github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
2-github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
1+github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
2+github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
3+github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0=
4+github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=
35 github.com/alecthomas/chroma/v2 v2.23.1 h1:nv2AVZdTyClGbVQkIzlDm/rnhk1E9bU9nXwmZ/Vk/iY=
46 github.com/alecthomas/chroma/v2 v2.23.1/go.mod h1:NqVhfBR0lte5Ouh3DcthuUCTUpDC9cxBOfyMbMQPs3o=
7+github.com/alecthomas/repr v0.5.2 h1:SU73FTI9D1P5UNtvseffFSGmdNci/O6RsqzeXJtP0Qs=
8+github.com/alecthomas/repr v0.5.2/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
59 github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
610 github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
711 github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
@@ -30,12 +34,20 @@ github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfa
3034 github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=
3135 github.com/clipperhouse/uax29/v2 v2.5.0 h1:x7T0T4eTHDONxFJsL94uKNKPHrclyFI0lm7+w94cO8U=
3236 github.com/clipperhouse/uax29/v2 v2.5.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
37+github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
3338 github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
3439 github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
3540 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
3641 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
42+github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
43+github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
44+github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
3745 github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
3846 github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
47+github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
48+github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
49+github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
50+github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
3951 github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
4052 github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
4153 github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
@@ -48,14 +60,22 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU
4860 github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
4961 github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
5062 github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
63+github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
5164 github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
5265 github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
66+github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
67+github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
68+github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
69+github.com/sashabaranov/go-openai v1.41.2 h1:vfPRBZNMpnqu8ELsclWcAvF19lDNgh1t6TVfFFOPiSM=
70+github.com/sashabaranov/go-openai v1.41.2/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=
5371 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
5472 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
5573 golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
5674 golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
5775 golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
76+golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
5877 golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
78+golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
5979 golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
6080 golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
6181 golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
internal/config/config.go+157−0
@@ -0,0 +1,157 @@
1+// Package config handles configuration loading from TOML files and environment variables.
2+package config
3+
4+import (
5+ "errors"
6+ "fmt"
7+ "net/url"
8+ "os"
9+ "path/filepath"
10+
11+ "github.com/BurntSushi/toml"
12+)
13+
14+// Config is the root configuration structure.
15+type Config struct {
16+ DefaultProvider string `toml:"default_provider"`
17+ Providers map[string]ProviderConfig `toml:"providers"`
18+ MCP MCPConfig `toml:"mcp"`
19+}
20+
21+// ProviderConfig holds LLM provider settings.
22+type ProviderConfig struct {
23+ Endpoint string `toml:"endpoint"`
24+ Model string `toml:"model"`
25+ APIKeyName string `toml:"api_key_name"`
26+ Temperature float64 `toml:"temperature"`
27+}
28+
29+// MCPConfig holds MCP proxy settings.
30+type MCPConfig struct {
31+ Upstream string `toml:"upstream"`
32+}
33+
34+// Load reads configuration from a TOML file and applies environment variable overrides.
35+func Load(path string) (*Config, error) {
36+ cfg := &Config{
37+ Providers: make(map[string]ProviderConfig),
38+ }
39+
40+ // Config file is required
41+ if path == "" {
42+ return nil, fmt.Errorf("config path is required")
43+ }
44+
45+ // File must exist
46+ if _, err := os.Stat(path); err != nil {
47+ return nil, fmt.Errorf("config file not found: %s", path)
48+ }
49+
50+ // Load from file
51+ _, err := toml.DecodeFile(path, cfg)
52+ if err != nil {
53+ return nil, fmt.Errorf("failed to parse config: %w", err)
54+ }
55+
56+ // Apply environment variable overrides
57+ applyEnvOverrides(cfg)
58+
59+ if err := cfg.Validate(); err != nil {
60+ return nil, err
61+ }
62+
63+ return cfg, nil
64+}
65+
66+// Validate returns an error if the configuration is invalid.
67+func (c *Config) Validate() error {
68+ var errs []error
69+
70+ if len(c.Providers) == 0 {
71+ errs = append(errs, errors.New("providers: at least one provider must be configured"))
72+ } else {
73+ for name, providerCfg := range c.Providers {
74+ errs = append(errs, validateProviderConfig(name, providerCfg)...)
75+ }
76+ }
77+
78+ // Validate default provider if specified
79+ if c.DefaultProvider != "" {
80+ if _, ok := c.Providers[c.DefaultProvider]; !ok {
81+ errs = append(errs, fmt.Errorf("default_provider=%q does not exist in providers", c.DefaultProvider))
82+ }
83+ }
84+
85+ if len(errs) > 0 {
86+ return errors.Join(errs...)
87+ }
88+
89+ return nil
90+}
91+
92+func validateProviderConfig(name string, cfg ProviderConfig) []error {
93+ var errs []error
94+ if cfg.Endpoint == "" {
95+ errs = append(errs, fmt.Errorf("providers.%s.endpoint is required", name))
96+ } else if err := validateEndpoint(cfg.Endpoint); err != nil {
97+ errs = append(errs, fmt.Errorf("providers.%s.endpoint=%q is invalid: %v", name, cfg.Endpoint, err))
98+ }
99+
100+ if cfg.Model == "" {
101+ errs = append(errs, fmt.Errorf("providers.%s.model is required", name))
102+ }
103+
104+ if cfg.Temperature < 0.0 || cfg.Temperature > 2.0 {
105+ errs = append(errs, fmt.Errorf("providers.%s.temperature=%v must be between 0.0 and 2.0", name, cfg.Temperature))
106+ }
107+
108+ return errs
109+}
110+
111+func validateEndpoint(value string) error {
112+ parsed, err := url.Parse(value)
113+ if err != nil {
114+ return err
115+ }
116+ if parsed.Scheme == "" || parsed.Host == "" {
117+ return errors.New("missing scheme or host")
118+ }
119+ return nil
120+}
121+
122+// applyEnvOverrides applies environment variable overrides to the configuration.
123+func applyEnvOverrides(cfg *Config) {
124+ for _, setter := range []struct {
125+ env string
126+ apply func(string)
127+ }{
128+ {"SYMB_MCP_ENDPOINT", func(v string) {
129+ if v != "" {
130+ cfg.MCP.Upstream = v
131+ }
132+ }},
133+ } {
134+ setter.apply(os.Getenv(setter.env))
135+ }
136+}
137+
138+// DataDir returns the path to the Symb data directory (~/.config/symb).
139+func DataDir() (string, error) {
140+ home, err := os.UserHomeDir()
141+ if err != nil {
142+ return "", err
143+ }
144+ return filepath.Join(home, ".config", "symb"), nil
145+}
146+
147+// EnsureDataDir creates the data directory if it doesn't exist.
148+func EnsureDataDir() (string, error) {
149+ dir, err := DataDir()
150+ if err != nil {
151+ return "", err
152+ }
153+ if err := os.MkdirAll(dir, 0750); err != nil {
154+ return "", err
155+ }
156+ return dir, nil
157+}
internal/config/credentials.go+84−0
@@ -0,0 +1,84 @@
1+package config
2+
3+import (
4+ "encoding/json"
5+ "os"
6+ "path/filepath"
7+)
8+
9+// Credentials holds API keys for LLM providers.
10+type Credentials struct {
11+ Providers map[string]ProviderCredentials `json:"providers"`
12+}
13+
14+// ProviderCredentials holds authentication for a single provider.
15+type ProviderCredentials struct {
16+ APIKey string `json:"api_key"`
17+}
18+
19+// LoadCredentials reads credentials from ~/.config/symb/credentials.json.
20+func LoadCredentials() (*Credentials, error) {
21+ path, err := credentialsPath()
22+ if err != nil {
23+ return nil, err
24+ }
25+
26+ creds := &Credentials{
27+ Providers: make(map[string]ProviderCredentials),
28+ }
29+
30+ //nolint:gosec // G304: Path from validated config file
31+ data, err := os.ReadFile(path)
32+ if os.IsNotExist(err) {
33+ return creds, nil
34+ }
35+ if err != nil {
36+ return nil, err
37+ }
38+
39+ if err := json.Unmarshal(data, creds); err != nil {
40+ return nil, err
41+ }
42+
43+ return creds, nil
44+}
45+
46+// SaveCredentials writes credentials to ~/.config/symb/credentials.json with 0600 permissions.
47+func SaveCredentials(creds *Credentials) error {
48+ dir, err := EnsureDataDir()
49+ if err != nil {
50+ return err
51+ }
52+
53+ path := filepath.Join(dir, "credentials.json")
54+ data, err := json.MarshalIndent(creds, "", " ")
55+ if err != nil {
56+ return err
57+ }
58+
59+ return os.WriteFile(path, data, 0600)
60+}
61+
62+// GetAPIKey returns the API key for a given provider, or empty string if not set.
63+func (c *Credentials) GetAPIKey(provider string) string {
64+ if c == nil || c.Providers == nil {
65+ return ""
66+ }
67+ return c.Providers[provider].APIKey
68+}
69+
70+// SetAPIKey sets the API key for a given provider.
71+func (c *Credentials) SetAPIKey(provider, apiKey string) {
72+ if c.Providers == nil {
73+ c.Providers = make(map[string]ProviderCredentials)
74+ }
75+ c.Providers[provider] = ProviderCredentials{APIKey: apiKey}
76+}
77+
78+func credentialsPath() (string, error) {
79+ dir, err := DataDir()
80+ if err != nil {
81+ return "", err
82+ }
83+ return filepath.Join(dir, "credentials.json"), nil
84+}
internal/llm/loop.go+168−0
@@ -0,0 +1,168 @@
1+package llm
2+
3+import (
4+ "context"
5+ "fmt"
6+ "time"
7+
8+ "github.com/xonecas/symb/internal/mcp"
9+ "github.com/xonecas/symb/internal/provider"
10+)
11+
12+// MessageCallback is called when a message should be added to history and saved.
13+type MessageCallback func(msg provider.Message)
14+
15+// ToolCallCallback is called when tool calls are about to be executed.
16+type ToolCallCallback func()
17+
18+// ProcessTurnOptions holds configuration for processing a turn.
19+type ProcessTurnOptions struct {
20+ Provider provider.Provider
21+ Proxy *mcp.Proxy
22+ Tools []mcp.Tool
23+ History []provider.Message
24+ OnMessage MessageCallback
25+ OnToolCall ToolCallCallback // Optional: called before executing tool calls
26+ MaxToolRounds int
27+}
28+
29+// ProcessTurn handles one conversation turn, which may involve tool calls.
30+// It returns an error if the LLM call fails or max rounds are exceeded.
31+func ProcessTurn(ctx context.Context, opts ProcessTurnOptions) error {
32+ if opts.MaxToolRounds == 0 {
33+ opts.MaxToolRounds = 20
34+ }
35+
36+ for round := 0; round < opts.MaxToolRounds; round++ {
37+ // Convert MCP tools to provider format
38+ providerTools := make([]provider.Tool, len(opts.Tools))
39+ for i, t := range opts.Tools {
40+ providerTools[i] = provider.Tool{
41+ Name: t.Name,
42+ Description: t.Description,
43+ Parameters: t.InputSchema,
44+ }
45+ }
46+
47+ // Call LLM with history
48+ resp, err := opts.Provider.ChatWithTools(ctx, opts.History, providerTools)
49+ if err != nil {
50+ return fmt.Errorf("LLM call failed: %w", err)
51+ }
52+
53+ // If no tool calls, we're done
54+ if len(resp.ToolCalls) == 0 {
55+ // Add assistant response to history
56+ assistantMsg := provider.Message{
57+ Role: "assistant",
58+ Content: resp.Content,
59+ Reasoning: resp.Reasoning,
60+ CreatedAt: time.Now(),
61+ }
62+ if opts.OnMessage != nil {
63+ opts.OnMessage(assistantMsg)
64+ }
65+ opts.History = append(opts.History, assistantMsg)
66+
67+ return nil
68+ }
69+
70+ // Tool calls present - add assistant message with tool calls to history
71+ assistantMsg := provider.Message{
72+ Role: "assistant",
73+ Content: resp.Content,
74+ Reasoning: resp.Reasoning,
75+ ToolCalls: resp.ToolCalls,
76+ CreatedAt: time.Now(),
77+ }
78+ if opts.OnMessage != nil {
79+ opts.OnMessage(assistantMsg)
80+ }
81+ opts.History = append(opts.History, assistantMsg)
82+
83+ // Notify about tool calls if callback provided
84+ if opts.OnToolCall != nil {
85+ opts.OnToolCall()
86+ }
87+
88+ // Execute each tool call and update history
89+ toolResults := executeToolCalls(ctx, opts.Proxy, resp.ToolCalls, opts.OnMessage)
90+ opts.History = append(opts.History, toolResults...)
91+
92+ // Continue loop to let LLM process tool results
93+ }
94+
95+ return fmt.Errorf("too many tool call rounds (limit: %d)", opts.MaxToolRounds)
96+}
97+
98+// executeToolCalls executes a list of tool calls and adds results to history.
99+// Returns the list of tool result messages that were added.
100+func executeToolCalls(ctx context.Context, proxy *mcp.Proxy, toolCalls []provider.ToolCall, onMessage MessageCallback) []provider.Message {
101+ toolResults := make([]provider.Message, 0, len(toolCalls))
102+
103+ for _, toolCall := range toolCalls {
104+ // Execute tool via MCP proxy
105+ result, err := proxy.CallTool(ctx, toolCall.Name, toolCall.Arguments)
106+
107+ if err != nil {
108+ // Add error result to history
109+ toolMsg := provider.Message{
110+ Role: "tool",
111+ Content: fmt.Sprintf("Error: %v", err),
112+ ToolCallID: toolCall.ID,
113+ CreatedAt: time.Now(),
114+ }
115+ if onMessage != nil {
116+ onMessage(toolMsg)
117+ }
118+ toolResults = append(toolResults, toolMsg)
119+ continue
120+ }
121+
122+ // Check if result is an error
123+ if result.IsError {
124+ errText := extractTextFromContent(result.Content)
125+
126+ // Add error result to history
127+ toolMsg := provider.Message{
128+ Role: "tool",
129+ Content: errText,
130+ ToolCallID: toolCall.ID,
131+ CreatedAt: time.Now(),
132+ }
133+ if onMessage != nil {
134+ onMessage(toolMsg)
135+ }
136+ toolResults = append(toolResults, toolMsg)
137+ continue
138+ }
139+
140+ // Success - extract result text
141+ resultText := extractTextFromContent(result.Content)
142+
143+ // Add tool result to history
144+ toolMsg := provider.Message{
145+ Role: "tool",
146+ Content: resultText,
147+ ToolCallID: toolCall.ID,
148+ CreatedAt: time.Now(),
149+ }
150+ if onMessage != nil {
151+ onMessage(toolMsg)
152+ }
153+ toolResults = append(toolResults, toolMsg)
154+ }
155+
156+ return toolResults
157+}
158+
159+// extractTextFromContent extracts text from MCP content blocks.
160+func extractTextFromContent(content []mcp.ContentBlock) string {
161+ var text string
162+ for _, block := range content {
163+ if block.Type == "text" {
164+ text += block.Text
165+ }
166+ }
167+ return text
168+}
internal/mcp/client.go+347−0
@@ -0,0 +1,347 @@
1+package mcp
2+
3+import (
4+ "bufio"
5+ "bytes"
6+ "context"
7+ "encoding/json"
8+ "fmt"
9+ "io"
10+ "net/http"
11+ "strings"
12+ "sync/atomic"
13+ "time"
14+
15+ "github.com/rs/zerolog/log"
16+)
17+
18+// Client is an MCP client that communicates with an upstream server.
19+type Client struct {
20+ endpoint string
21+ httpClient *http.Client
22+ requestID atomic.Int64
23+ sessionID string // Session ID from server, included in subsequent requests
24+ protocolVersion string // Negotiated protocol version
25+}
26+
27+// NewClient creates a new MCP client.
28+func NewClient(endpoint string) *Client {
29+ return &Client{
30+ endpoint: endpoint,
31+ httpClient: &http.Client{
32+ Timeout: 30 * time.Second, // 30s timeout to prevent hanging requests
33+ },
34+ protocolVersion: "2024-11-05", // Default, may be updated during initialization
35+ }
36+}
37+
38+// nextID returns the next request ID.
39+func (c *Client) nextID() int64 {
40+ return c.requestID.Add(1)
41+}
42+
43+// Call makes an MCP request and returns the response.
44+func (c *Client) Call(ctx context.Context, method string, params interface{}) (*Response, error) {
45+ req, err := NewRequest(c.nextID(), method, params)
46+ if err != nil {
47+ return nil, fmt.Errorf("create request: %w", err)
48+ }
49+
50+ return c.send(ctx, req)
51+}
52+
53+// send sends a request and receives a response.
54+// Supports both JSON and SSE (Streamable HTTP) responses per MCP spec.
55+func (c *Client) send(ctx context.Context, req *Request) (*Response, error) {
56+ body, err := json.Marshal(req)
57+ if err != nil {
58+ return nil, fmt.Errorf("marshal request: %w", err)
59+ }
60+
61+ httpReq, err := http.NewRequestWithContext(ctx, "POST", c.endpoint, bytes.NewReader(body))
62+ if err != nil {
63+ return nil, fmt.Errorf("create http request: %w", err)
64+ }
65+
66+ httpReq.Header.Set("Content-Type", "application/json")
67+ httpReq.Header.Set("Accept", "application/json, text/event-stream")
68+
69+ // Include session ID if we have one (required after initialization)
70+ if c.sessionID != "" {
71+ httpReq.Header.Set("Mcp-Session-Id", c.sessionID)
72+ }
73+
74+ // Include protocol version header
75+ if c.protocolVersion != "" {
76+ httpReq.Header.Set("MCP-Protocol-Version", c.protocolVersion)
77+ }
78+
79+ httpResp, err := c.httpClient.Do(httpReq)
80+ if err != nil {
81+ return nil, fmt.Errorf("http request: %w", err)
82+ }
83+ defer func() {
84+ if err := httpResp.Body.Close(); err != nil {
85+ log.Warn().Err(err).Msg("Failed to close response body")
86+ }
87+ }()
88+
89+ if httpResp.StatusCode != http.StatusOK {
90+ respBody, _ := io.ReadAll(httpResp.Body)
91+
92+ // For 429 rate limits, include Retry-After header if present
93+ if httpResp.StatusCode == http.StatusTooManyRequests {
94+ if retryAfter := httpResp.Header.Get("Retry-After"); retryAfter != "" {
95+ return nil, fmt.Errorf("http error %d: %s (Retry-After: %s)", httpResp.StatusCode, string(respBody), retryAfter)
96+ }
97+ }
98+
99+ return nil, fmt.Errorf("http error %d: %s", httpResp.StatusCode, string(respBody))
100+ }
101+
102+ // Capture session ID from response if present
103+ if sessionID := httpResp.Header.Get("Mcp-Session-Id"); sessionID != "" {
104+ c.sessionID = sessionID
105+ }
106+
107+ contentType := httpResp.Header.Get("Content-Type")
108+
109+ // Handle SSE (Server-Sent Events) response
110+ if strings.HasPrefix(contentType, "text/event-stream") {
111+ return c.parseSSEResponse(httpResp.Body)
112+ }
113+
114+ // Handle plain JSON response
115+ respBody, err := io.ReadAll(httpResp.Body)
116+ if err != nil {
117+ return nil, fmt.Errorf("read response: %w", err)
118+ }
119+
120+ var resp Response
121+ if err := json.Unmarshal(respBody, &resp); err != nil {
122+ return nil, fmt.Errorf("unmarshal response: %w", err)
123+ }
124+
125+ return &resp, nil
126+}
127+
128+// parseSSEResponse parses a Server-Sent Events stream for MCP responses.
129+func (c *Client) parseSSEResponse(body io.Reader) (*Response, error) {
130+ scanner := bufio.NewScanner(body)
131+ maxTokenSize := 2 * 1024 * 1024
132+ scanner.Buffer(make([]byte, 0, 64*1024), maxTokenSize)
133+ var dataLines []string
134+
135+ for scanner.Scan() {
136+ line := scanner.Text()
137+
138+ // SSE format: "data: {...json...}" or "event: message"
139+ if strings.HasPrefix(line, "data: ") {
140+ dataLines = append(dataLines, strings.TrimPrefix(line, "data: "))
141+ } else if line == "" && len(dataLines) > 0 {
142+ // Empty line marks end of event, try to parse accumulated data
143+ data := strings.Join(dataLines, "")
144+ dataLines = nil
145+
146+ var resp Response
147+ if err := json.Unmarshal([]byte(data), &resp); err != nil {
148+ continue // Skip malformed events
149+ }
150+
151+ // Return first valid response with our request ID
152+ if resp.ID != nil {
153+ return &resp, nil
154+ }
155+ }
156+ }
157+
158+ if err := scanner.Err(); err != nil {
159+ return nil, fmt.Errorf("read SSE stream: %w", err)
160+ }
161+
162+ // If we collected data but no empty line terminated it
163+ if len(dataLines) > 0 {
164+ data := strings.Join(dataLines, "")
165+ var resp Response
166+ if err := json.Unmarshal([]byte(data), &resp); err != nil {
167+ return nil, fmt.Errorf("unmarshal final SSE data: %w", err)
168+ }
169+ return &resp, nil
170+ }
171+
172+ return nil, fmt.Errorf("no response in SSE stream")
173+}
174+
175+// ListTools requests the list of available tools from the server.
176+func (c *Client) ListTools(ctx context.Context) ([]Tool, error) {
177+ resp, err := c.Call(ctx, "tools/list", nil)
178+ if err != nil {
179+ return nil, err
180+ }
181+
182+ if resp.Error != nil {
183+ return nil, fmt.Errorf("mcp error %d: %s", resp.Error.Code, resp.Error.Message)
184+ }
185+
186+ var result ListToolsResult
187+ if err := json.Unmarshal(resp.Result, &result); err != nil {
188+ return nil, fmt.Errorf("unmarshal tools: %w", err)
189+ }
190+
191+ return result.Tools, nil
192+}
193+
194+// CallTool invokes a tool on the server.
195+func (c *Client) CallTool(ctx context.Context, name string, arguments interface{}) (*ToolResult, error) {
196+ var argsJSON json.RawMessage
197+ if arguments != nil {
198+ data, err := json.Marshal(arguments)
199+ if err != nil {
200+ return nil, fmt.Errorf("marshal arguments: %w", err)
201+ }
202+ argsJSON = data
203+ }
204+
205+ params := CallToolParams{
206+ Name: name,
207+ Arguments: argsJSON,
208+ }
209+
210+ resp, err := c.Call(ctx, "tools/call", params)
211+ if err != nil {
212+ return nil, err
213+ }
214+
215+ if resp.Error != nil {
216+ return &ToolResult{
217+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Error: %s", resp.Error.Message)}},
218+ IsError: true,
219+ }, nil
220+ }
221+
222+ var result ToolResult
223+ if err := json.Unmarshal(resp.Result, &result); err != nil {
224+ return nil, fmt.Errorf("unmarshal result: %w", err)
225+ }
226+
227+ return &result, nil
228+}
229+
230+// Initialize sends the initialize request to the server and completes the handshake.
231+func (c *Client) Initialize(ctx context.Context, clientInfo map[string]interface{}) (*Response, error) {
232+ params := map[string]interface{}{
233+ "protocolVersion": "2024-11-05",
234+ "capabilities": map[string]interface{}{},
235+ "clientInfo": clientInfo,
236+ }
237+
238+ var resp *Response
Cut short: this commit's diff is over 1000 lines.
internal/mcp/proxy.go+262−0
Cut short: this commit's diff is over 1000 lines.
internal/mcp/stub.go+128−0
Cut short: this commit's diff is over 1000 lines.
internal/mcp/tools.go+144−0
Cut short: this commit's diff is over 1000 lines.
internal/mcp/types.go+130−0
Cut short: this commit's diff is over 1000 lines.
internal/provider/factory.go+39−0
Cut short: this commit's diff is over 1000 lines.
internal/provider/mock.go+173−0
Cut short: this commit's diff is over 1000 lines.
internal/provider/ollama.go+482−0
Cut short: this commit's diff is over 1000 lines.
internal/provider/openai_common.go+203−0
Cut short: this commit's diff is over 1000 lines.
internal/provider/opencode.go+394−0
Cut short: this commit's diff is over 1000 lines.
internal/provider/provider.go+106−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestLayout/120x40/ANSI.golden+5−5
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestLayout/120x40/Stripped.golden+5−5
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestLayout/80x24/ANSI.golden+5−5
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestLayout/80x24/Stripped.golden+5−5
Cut short: this commit's diff is over 1000 lines.
internal/tui/tui.go+275−35
Cut short: this commit's diff is over 1000 lines.