config.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. // Package config manages application configuration from various sources.
  2. package config
  3. import (
  4. "fmt"
  5. "log/slog"
  6. "os"
  7. "strings"
  8. "github.com/kujtimiihoxha/opencode/internal/llm/models"
  9. "github.com/kujtimiihoxha/opencode/internal/logging"
  10. "github.com/spf13/viper"
  11. )
  12. // MCPType defines the type of MCP (Model Control Protocol) server.
  13. type MCPType string
  14. // Supported MCP types
  15. const (
  16. MCPStdio MCPType = "stdio"
  17. MCPSse MCPType = "sse"
  18. )
  19. // MCPServer defines the configuration for a Model Control Protocol server.
  20. type MCPServer struct {
  21. Command string `json:"command"`
  22. Env []string `json:"env"`
  23. Args []string `json:"args"`
  24. Type MCPType `json:"type"`
  25. URL string `json:"url"`
  26. Headers map[string]string `json:"headers"`
  27. }
  28. type AgentName string
  29. const (
  30. AgentCoder AgentName = "coder"
  31. AgentTask AgentName = "task"
  32. AgentTitle AgentName = "title"
  33. )
  34. // Agent defines configuration for different LLM models and their token limits.
  35. type Agent struct {
  36. Model models.ModelID `json:"model"`
  37. MaxTokens int64 `json:"maxTokens"`
  38. ReasoningEffort string `json:"reasoningEffort"` // For openai models low,medium,heigh
  39. }
  40. // Provider defines configuration for an LLM provider.
  41. type Provider struct {
  42. APIKey string `json:"apiKey"`
  43. Disabled bool `json:"disabled"`
  44. }
  45. // Data defines storage configuration.
  46. type Data struct {
  47. Directory string `json:"directory"`
  48. }
  49. // LSPConfig defines configuration for Language Server Protocol integration.
  50. type LSPConfig struct {
  51. Disabled bool `json:"enabled"`
  52. Command string `json:"command"`
  53. Args []string `json:"args"`
  54. Options any `json:"options"`
  55. }
  56. // Config is the main configuration structure for the application.
  57. type Config struct {
  58. Data Data `json:"data"`
  59. WorkingDir string `json:"wd,omitempty"`
  60. MCPServers map[string]MCPServer `json:"mcpServers,omitempty"`
  61. Providers map[models.ModelProvider]Provider `json:"providers,omitempty"`
  62. LSP map[string]LSPConfig `json:"lsp,omitempty"`
  63. Agents map[AgentName]Agent `json:"agents"`
  64. Debug bool `json:"debug,omitempty"`
  65. DebugLSP bool `json:"debugLSP,omitempty"`
  66. }
  67. // Application constants
  68. const (
  69. defaultDataDirectory = ".opencode"
  70. defaultLogLevel = "info"
  71. appName = "opencode"
  72. )
  73. // Global configuration instance
  74. var cfg *Config
  75. // Load initializes the configuration from environment variables and config files.
  76. // If debug is true, debug mode is enabled and log level is set to debug.
  77. // It returns an error if configuration loading fails.
  78. func Load(workingDir string, debug bool) (*Config, error) {
  79. if cfg != nil {
  80. return cfg, nil
  81. }
  82. cfg = &Config{
  83. WorkingDir: workingDir,
  84. MCPServers: make(map[string]MCPServer),
  85. Providers: make(map[models.ModelProvider]Provider),
  86. LSP: make(map[string]LSPConfig),
  87. }
  88. configureViper()
  89. setDefaults(debug)
  90. setProviderDefaults()
  91. // Read global config
  92. if err := readConfig(viper.ReadInConfig()); err != nil {
  93. return cfg, err
  94. }
  95. // Load and merge local config
  96. mergeLocalConfig(workingDir)
  97. // Apply configuration to the struct
  98. if err := viper.Unmarshal(cfg); err != nil {
  99. return cfg, fmt.Errorf("failed to unmarshal config: %w", err)
  100. }
  101. applyDefaultValues()
  102. defaultLevel := slog.LevelInfo
  103. if cfg.Debug {
  104. defaultLevel = slog.LevelDebug
  105. }
  106. if os.Getenv("OPENCODE_DEV_DEBUG") == "true" {
  107. loggingFile := fmt.Sprintf("%s/%s", cfg.Data.Directory, "debug.log")
  108. // if file does not exist create it
  109. if _, err := os.Stat(loggingFile); os.IsNotExist(err) {
  110. if err := os.MkdirAll(cfg.Data.Directory, 0o755); err != nil {
  111. return cfg, fmt.Errorf("failed to create directory: %w", err)
  112. }
  113. if _, err := os.Create(loggingFile); err != nil {
  114. return cfg, fmt.Errorf("failed to create log file: %w", err)
  115. }
  116. }
  117. sloggingFileWriter, err := os.OpenFile(loggingFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o666)
  118. if err != nil {
  119. return cfg, fmt.Errorf("failed to open log file: %w", err)
  120. }
  121. // Configure logger
  122. logger := slog.New(slog.NewTextHandler(sloggingFileWriter, &slog.HandlerOptions{
  123. Level: defaultLevel,
  124. }))
  125. slog.SetDefault(logger)
  126. } else {
  127. // Configure logger
  128. logger := slog.New(slog.NewTextHandler(logging.NewWriter(), &slog.HandlerOptions{
  129. Level: defaultLevel,
  130. }))
  131. slog.SetDefault(logger)
  132. }
  133. // Validate configuration
  134. if err := Validate(); err != nil {
  135. return cfg, fmt.Errorf("config validation failed: %w", err)
  136. }
  137. if cfg.Agents == nil {
  138. cfg.Agents = make(map[AgentName]Agent)
  139. }
  140. // Override the max tokens for title agent
  141. cfg.Agents[AgentTitle] = Agent{
  142. Model: cfg.Agents[AgentTitle].Model,
  143. MaxTokens: 80,
  144. }
  145. return cfg, nil
  146. }
  147. // configureViper sets up viper's configuration paths and environment variables.
  148. func configureViper() {
  149. viper.SetConfigName(fmt.Sprintf(".%s", appName))
  150. viper.SetConfigType("json")
  151. viper.AddConfigPath("$HOME")
  152. viper.AddConfigPath(fmt.Sprintf("$XDG_CONFIG_HOME/%s", appName))
  153. viper.SetEnvPrefix(strings.ToUpper(appName))
  154. viper.AutomaticEnv()
  155. }
  156. // setDefaults configures default values for configuration options.
  157. func setDefaults(debug bool) {
  158. viper.SetDefault("data.directory", defaultDataDirectory)
  159. if debug {
  160. viper.SetDefault("debug", true)
  161. viper.Set("log.level", "debug")
  162. } else {
  163. viper.SetDefault("debug", false)
  164. viper.SetDefault("log.level", defaultLogLevel)
  165. }
  166. }
  167. // setProviderDefaults configures LLM provider defaults based on environment variables.
  168. // the default model priority is:
  169. // 1. Anthropic
  170. // 2. OpenAI
  171. // 3. Google Gemini
  172. // 4. AWS Bedrock
  173. func setProviderDefaults() {
  174. // Groq configuration
  175. if apiKey := os.Getenv("GROQ_API_KEY"); apiKey != "" {
  176. viper.SetDefault("providers.groq.apiKey", apiKey)
  177. viper.SetDefault("agents.coder.model", models.QWENQwq)
  178. viper.SetDefault("agents.task.model", models.QWENQwq)
  179. viper.SetDefault("agents.title.model", models.QWENQwq)
  180. }
  181. // Google Gemini configuration
  182. if apiKey := os.Getenv("GEMINI_API_KEY"); apiKey != "" {
  183. viper.SetDefault("providers.gemini.apiKey", apiKey)
  184. viper.SetDefault("agents.coder.model", models.Gemini25)
  185. viper.SetDefault("agents.task.model", models.Gemini25Flash)
  186. viper.SetDefault("agents.title.model", models.Gemini25Flash)
  187. }
  188. // OpenAI configuration
  189. if apiKey := os.Getenv("OPENAI_API_KEY"); apiKey != "" {
  190. viper.SetDefault("providers.openai.apiKey", apiKey)
  191. viper.SetDefault("agents.coder.model", models.GPT41)
  192. viper.SetDefault("agents.task.model", models.GPT41Mini)
  193. viper.SetDefault("agents.title.model", models.GPT41Mini)
  194. }
  195. // Anthropic configuration
  196. if apiKey := os.Getenv("ANTHROPIC_API_KEY"); apiKey != "" {
  197. viper.SetDefault("providers.anthropic.apiKey", apiKey)
  198. viper.SetDefault("agents.coder.model", models.Claude37Sonnet)
  199. viper.SetDefault("agents.task.model", models.Claude37Sonnet)
  200. viper.SetDefault("agents.title.model", models.Claude37Sonnet)
  201. }
  202. if hasAWSCredentials() {
  203. viper.SetDefault("agents.coder.model", models.BedrockClaude37Sonnet)
  204. viper.SetDefault("agents.task.model", models.BedrockClaude37Sonnet)
  205. viper.SetDefault("agents.title.model", models.BedrockClaude37Sonnet)
  206. }
  207. }
  208. // hasAWSCredentials checks if AWS credentials are available in the environment.
  209. func hasAWSCredentials() bool {
  210. // Check for explicit AWS credentials
  211. if os.Getenv("AWS_ACCESS_KEY_ID") != "" && os.Getenv("AWS_SECRET_ACCESS_KEY") != "" {
  212. return true
  213. }
  214. // Check for AWS profile
  215. if os.Getenv("AWS_PROFILE") != "" || os.Getenv("AWS_DEFAULT_PROFILE") != "" {
  216. return true
  217. }
  218. // Check for AWS region
  219. if os.Getenv("AWS_REGION") != "" || os.Getenv("AWS_DEFAULT_REGION") != "" {
  220. return true
  221. }
  222. // Check if running on EC2 with instance profile
  223. if os.Getenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI") != "" ||
  224. os.Getenv("AWS_CONTAINER_CREDENTIALS_FULL_URI") != "" {
  225. return true
  226. }
  227. return false
  228. }
  229. // readConfig handles the result of reading a configuration file.
  230. func readConfig(err error) error {
  231. if err == nil {
  232. return nil
  233. }
  234. // It's okay if the config file doesn't exist
  235. if _, ok := err.(viper.ConfigFileNotFoundError); ok {
  236. return nil
  237. }
  238. return fmt.Errorf("failed to read config: %w", err)
  239. }
  240. // mergeLocalConfig loads and merges configuration from the local directory.
  241. func mergeLocalConfig(workingDir string) {
  242. local := viper.New()
  243. local.SetConfigName(fmt.Sprintf(".%s", appName))
  244. local.SetConfigType("json")
  245. local.AddConfigPath(workingDir)
  246. // Merge local config if it exists
  247. if err := local.ReadInConfig(); err == nil {
  248. viper.MergeConfigMap(local.AllSettings())
  249. }
  250. }
  251. // applyDefaultValues sets default values for configuration fields that need processing.
  252. func applyDefaultValues() {
  253. // Set default MCP type if not specified
  254. for k, v := range cfg.MCPServers {
  255. if v.Type == "" {
  256. v.Type = MCPStdio
  257. cfg.MCPServers[k] = v
  258. }
  259. }
  260. }
  261. // Validate checks if the configuration is valid and applies defaults where needed.
  262. // It validates model IDs and providers, ensuring they are supported.
  263. func Validate() error {
  264. if cfg == nil {
  265. return fmt.Errorf("config not loaded")
  266. }
  267. // Validate agent models
  268. for name, agent := range cfg.Agents {
  269. // Check if model exists
  270. model, modelExists := models.SupportedModels[agent.Model]
  271. if !modelExists {
  272. logging.Warn("unsupported model configured, reverting to default",
  273. "agent", name,
  274. "configured_model", agent.Model)
  275. // Set default model based on available providers
  276. if setDefaultModelForAgent(name) {
  277. logging.Info("set default model for agent", "agent", name, "model", cfg.Agents[name].Model)
  278. } else {
  279. return fmt.Errorf("no valid provider available for agent %s", name)
  280. }
  281. continue
  282. }
  283. // Check if provider for the model is configured
  284. provider := model.Provider
  285. providerCfg, providerExists := cfg.Providers[provider]
  286. if !providerExists {
  287. // Provider not configured, check if we have environment variables
  288. apiKey := getProviderAPIKey(provider)
  289. if apiKey == "" {
  290. logging.Warn("provider not configured for model, reverting to default",
  291. "agent", name,
  292. "model", agent.Model,
  293. "provider", provider)
  294. // Set default model based on available providers
  295. if setDefaultModelForAgent(name) {
  296. logging.Info("set default model for agent", "agent", name, "model", cfg.Agents[name].Model)
  297. } else {
  298. return fmt.Errorf("no valid provider available for agent %s", name)
  299. }
  300. } else {
  301. // Add provider with API key from environment
  302. cfg.Providers[provider] = Provider{
  303. APIKey: apiKey,
  304. }
  305. logging.Info("added provider from environment", "provider", provider)
  306. }
  307. } else if providerCfg.Disabled || providerCfg.APIKey == "" {
  308. // Provider is disabled or has no API key
  309. logging.Warn("provider is disabled or has no API key, reverting to default",
  310. "agent", name,
  311. "model", agent.Model,
  312. "provider", provider)
  313. // Set default model based on available providers
  314. if setDefaultModelForAgent(name) {
  315. logging.Info("set default model for agent", "agent", name, "model", cfg.Agents[name].Model)
  316. } else {
  317. return fmt.Errorf("no valid provider available for agent %s", name)
  318. }
  319. }
  320. // Validate max tokens
  321. if agent.MaxTokens <= 0 {
  322. logging.Warn("invalid max tokens, setting to default",
  323. "agent", name,
  324. "model", agent.Model,
  325. "max_tokens", agent.MaxTokens)
  326. // Update the agent with default max tokens
  327. updatedAgent := cfg.Agents[name]
  328. if model.DefaultMaxTokens > 0 {
  329. updatedAgent.MaxTokens = model.DefaultMaxTokens
  330. } else {
  331. updatedAgent.MaxTokens = 4096 // Fallback default
  332. }
  333. cfg.Agents[name] = updatedAgent
  334. } else if model.ContextWindow > 0 && agent.MaxTokens > model.ContextWindow/2 {
  335. // Ensure max tokens doesn't exceed half the context window (reasonable limit)
  336. logging.Warn("max tokens exceeds half the context window, adjusting",
  337. "agent", name,
  338. "model", agent.Model,
  339. "max_tokens", agent.MaxTokens,
  340. "context_window", model.ContextWindow)
  341. // Update the agent with adjusted max tokens
  342. updatedAgent := cfg.Agents[name]
  343. updatedAgent.MaxTokens = model.ContextWindow / 2
  344. cfg.Agents[name] = updatedAgent
  345. }
  346. // Validate reasoning effort for models that support reasoning
  347. if model.CanReason && provider == models.ProviderOpenAI {
  348. if agent.ReasoningEffort == "" {
  349. // Set default reasoning effort for models that support it
  350. logging.Info("setting default reasoning effort for model that supports reasoning",
  351. "agent", name,
  352. "model", agent.Model)
  353. // Update the agent with default reasoning effort
  354. updatedAgent := cfg.Agents[name]
  355. updatedAgent.ReasoningEffort = "medium"
  356. cfg.Agents[name] = updatedAgent
  357. } else {
  358. // Check if reasoning effort is valid (low, medium, high)
  359. effort := strings.ToLower(agent.ReasoningEffort)
  360. if effort != "low" && effort != "medium" && effort != "high" {
  361. logging.Warn("invalid reasoning effort, setting to medium",
  362. "agent", name,
  363. "model", agent.Model,
  364. "reasoning_effort", agent.ReasoningEffort)
  365. // Update the agent with valid reasoning effort
  366. updatedAgent := cfg.Agents[name]
  367. updatedAgent.ReasoningEffort = "medium"
  368. cfg.Agents[name] = updatedAgent
  369. }
  370. }
  371. } else if !model.CanReason && agent.ReasoningEffort != "" {
  372. // Model doesn't support reasoning but reasoning effort is set
  373. logging.Warn("model doesn't support reasoning but reasoning effort is set, ignoring",
  374. "agent", name,
  375. "model", agent.Model,
  376. "reasoning_effort", agent.ReasoningEffort)
  377. // Update the agent to remove reasoning effort
  378. updatedAgent := cfg.Agents[name]
  379. updatedAgent.ReasoningEffort = ""
  380. cfg.Agents[name] = updatedAgent
  381. }
  382. }
  383. // Validate providers
  384. for provider, providerCfg := range cfg.Providers {
  385. if providerCfg.APIKey == "" && !providerCfg.Disabled {
  386. logging.Warn("provider has no API key, marking as disabled", "provider", provider)
  387. providerCfg.Disabled = true
  388. cfg.Providers[provider] = providerCfg
  389. }
  390. }
  391. // Validate LSP configurations
  392. for language, lspConfig := range cfg.LSP {
  393. if lspConfig.Command == "" && !lspConfig.Disabled {
  394. logging.Warn("LSP configuration has no command, marking as disabled", "language", language)
  395. lspConfig.Disabled = true
  396. cfg.LSP[language] = lspConfig
  397. }
  398. }
  399. return nil
  400. }
  401. // getProviderAPIKey gets the API key for a provider from environment variables
  402. func getProviderAPIKey(provider models.ModelProvider) string {
  403. switch provider {
  404. case models.ProviderAnthropic:
  405. return os.Getenv("ANTHROPIC_API_KEY")
  406. case models.ProviderOpenAI:
  407. return os.Getenv("OPENAI_API_KEY")
  408. case models.ProviderGemini:
  409. return os.Getenv("GEMINI_API_KEY")
  410. case models.ProviderGROQ:
  411. return os.Getenv("GROQ_API_KEY")
  412. case models.ProviderBedrock:
  413. if hasAWSCredentials() {
  414. return "aws-credentials-available"
  415. }
  416. }
  417. return ""
  418. }
  419. // setDefaultModelForAgent sets a default model for an agent based on available providers
  420. func setDefaultModelForAgent(agent AgentName) bool {
  421. // Check providers in order of preference
  422. if apiKey := os.Getenv("ANTHROPIC_API_KEY"); apiKey != "" {
  423. maxTokens := int64(5000)
  424. if agent == AgentTitle {
  425. maxTokens = 80
  426. }
  427. cfg.Agents[agent] = Agent{
  428. Model: models.Claude37Sonnet,
  429. MaxTokens: maxTokens,
  430. }
  431. return true
  432. }
  433. if apiKey := os.Getenv("OPENAI_API_KEY"); apiKey != "" {
  434. var model models.ModelID
  435. maxTokens := int64(5000)
  436. reasoningEffort := ""
  437. switch agent {
  438. case AgentTitle:
  439. model = models.GPT41Mini
  440. maxTokens = 80
  441. case AgentTask:
  442. model = models.GPT41Mini
  443. default:
  444. model = models.GPT41
  445. }
  446. // Check if model supports reasoning
  447. if modelInfo, ok := models.SupportedModels[model]; ok && modelInfo.CanReason {
  448. reasoningEffort = "medium"
  449. }
  450. cfg.Agents[agent] = Agent{
  451. Model: model,
  452. MaxTokens: maxTokens,
  453. ReasoningEffort: reasoningEffort,
  454. }
  455. return true
  456. }
  457. if apiKey := os.Getenv("GEMINI_API_KEY"); apiKey != "" {
  458. var model models.ModelID
  459. maxTokens := int64(5000)
  460. if agent == AgentTitle {
  461. model = models.Gemini25Flash
  462. maxTokens = 80
  463. } else {
  464. model = models.Gemini25
  465. }
  466. cfg.Agents[agent] = Agent{
  467. Model: model,
  468. MaxTokens: maxTokens,
  469. }
  470. return true
  471. }
  472. if apiKey := os.Getenv("GROQ_API_KEY"); apiKey != "" {
  473. maxTokens := int64(5000)
  474. if agent == AgentTitle {
  475. maxTokens = 80
  476. }
  477. cfg.Agents[agent] = Agent{
  478. Model: models.QWENQwq,
  479. MaxTokens: maxTokens,
  480. }
  481. return true
  482. }
  483. if hasAWSCredentials() {
  484. maxTokens := int64(5000)
  485. if agent == AgentTitle {
  486. maxTokens = 80
  487. }
  488. cfg.Agents[agent] = Agent{
  489. Model: models.BedrockClaude37Sonnet,
  490. MaxTokens: maxTokens,
  491. ReasoningEffort: "medium", // Claude models support reasoning
  492. }
  493. return true
  494. }
  495. return false
  496. }
  497. // Get returns the current configuration.
  498. // It's safe to call this function multiple times.
  499. func Get() *Config {
  500. return cfg
  501. }
  502. // WorkingDirectory returns the current working directory from the configuration.
  503. func WorkingDirectory() string {
  504. if cfg == nil {
  505. panic("config not loaded")
  506. }
  507. return cfg.WorkingDir
  508. }