xonecas.io
62159
Sy

symb / files

symb / internal / config / config.go

4.6 KB
1// Package config handles configuration loading from TOML files and environment variables.
2package config
3
4import (
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.
15type Config struct {
16	DefaultProvider string                    `toml:"default_provider"`
17	Providers       map[string]ProviderConfig `toml:"providers"`
18	MCP             MCPConfig                 `toml:"mcp"`
19	Cache           CacheConfig               `toml:"cache"`
20	UI              UIConfig                  `toml:"ui"`
21}
22
23// UIConfig holds user-interface settings.
24type UIConfig struct {
25	// SyntaxTheme is the Chroma syntax highlighting theme used across the TUI.
26	// UI chrome colors are derived from this theme via highlight.ThemePalette.
27	// Defaults to "vulcan" if unset.
28	SyntaxTheme string `toml:"syntax_theme"`
29}
30
31// SyntaxThemeOrDefault returns the configured syntax theme or "vulcan" if unset.
32func (u UIConfig) SyntaxThemeOrDefault() string {
33	if u.SyntaxTheme == "" {
34		return "vulcan"
35	}
36	return u.SyntaxTheme
37}
38
39// CacheConfig holds web cache settings.
40type CacheConfig struct {
41	TTLHours int `toml:"ttl_hours"`
42}
43
44// CacheTTLOrDefault returns the configured TTL or 24 hours if unset.
45func (c CacheConfig) CacheTTLOrDefault() int {
46	if c.TTLHours <= 0 {
47		return 24
48	}
49	return c.TTLHours
50}
51
52// ProviderConfig holds LLM provider settings.
53type ProviderConfig struct {
54	Endpoint    string  `toml:"endpoint"`
55	Model       string  `toml:"model"`
56	Temperature float64 `toml:"temperature"`
57}
58
59// MCPConfig holds MCP proxy settings.
60type MCPConfig struct {
61	Upstream string `toml:"upstream"`
62}
63
64// Load reads configuration from a TOML file and applies environment variable overrides.
65func Load(path string) (*Config, error) {
66	cfg := &Config{
67		Providers: make(map[string]ProviderConfig),
68	}
69
70	// Config file is required
71	if path == "" {
72		return nil, fmt.Errorf("config path is required")
73	}
74
75	// File must exist
76	if _, err := os.Stat(path); err != nil {
77		return nil, fmt.Errorf("config file not found: %s", path)
78	}
79
80	// Load from file
81	_, err := toml.DecodeFile(path, cfg)
82	if err != nil {
83		return nil, fmt.Errorf("failed to parse config: %w", err)
84	}
85
86	// Apply environment variable overrides
87	applyEnvOverrides(cfg)
88
89	if err := cfg.Validate(); err != nil {
90		return nil, err
91	}
92
93	return cfg, nil
94}
95
96// Validate returns an error if the configuration is invalid.
97func (c *Config) Validate() error {
98	var errs []error
99
100	if len(c.Providers) == 0 {
101		errs = append(errs, errors.New("providers: at least one provider must be configured"))
102	} else {
103		for name, providerCfg := range c.Providers {
104			errs = append(errs, validateProviderConfig(name, providerCfg)...)
105		}
106	}
107
108	// Validate default provider if specified
109	if c.DefaultProvider != "" {
110		if _, ok := c.Providers[c.DefaultProvider]; !ok {
111			errs = append(errs, fmt.Errorf("default_provider=%q does not exist in providers", c.DefaultProvider))
112		}
113	}
114
115	if len(errs) > 0 {
116		return errors.Join(errs...)
117	}
118
119	return nil
120}
121
122func validateProviderConfig(name string, cfg ProviderConfig) []error {
123	var errs []error
124	if cfg.Endpoint == "" {
125		errs = append(errs, fmt.Errorf("providers.%s.endpoint is required", name))
126	} else if err := validateEndpoint(cfg.Endpoint); err != nil {
127		errs = append(errs, fmt.Errorf("providers.%s.endpoint=%q is invalid: %v", name, cfg.Endpoint, err))
128	}
129
130	if cfg.Model == "" {
131		errs = append(errs, fmt.Errorf("providers.%s.model is required", name))
132	}
133
134	if cfg.Temperature < 0.0 || cfg.Temperature > 2.0 {
135		errs = append(errs, fmt.Errorf("providers.%s.temperature=%v must be between 0.0 and 2.0", name, cfg.Temperature))
136	}
137
138	return errs
139}
140
141func validateEndpoint(value string) error {
142	parsed, err := url.Parse(value)
143	if err != nil {
144		return err
145	}
146	if parsed.Scheme == "" || parsed.Host == "" {
147		return errors.New("missing scheme or host")
148	}
149	return nil
150}
151
152// applyEnvOverrides applies environment variable overrides to the configuration.
153func applyEnvOverrides(cfg *Config) {
154	for _, setter := range []struct {
155		env   string
156		apply func(string)
157	}{
158		{"SYMB_MCP_ENDPOINT", func(v string) {
159			if v != "" {
160				cfg.MCP.Upstream = v
161			}
162		}},
163	} {
164		setter.apply(os.Getenv(setter.env))
165	}
166}
167
168// DataDir returns the path to the Symb data directory (~/.config/symb).
169func DataDir() (string, error) {
170	home, err := os.UserHomeDir()
171	if err != nil {
172		return "", err
173	}
174	return filepath.Join(home, ".config", "symb"), nil
175}
176
177// EnsureDataDir creates the data directory if it doesn't exist.
178func EnsureDataDir() (string, error) {
179	dir, err := DataDir()
180	if err != nil {
181		return "", err
182	}
183	if err := os.MkdirAll(dir, 0750); err != nil {
184		return "", err
185	}
186	return dir, nil
187}