config.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. // Package config manages application configuration from various sources.
  2. package config
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "log/slog"
  7. "os"
  8. "strings"
  9. "github.com/opencode-ai/opencode/internal/llm/models"
  10. "github.com/opencode-ai/opencode/internal/logging"
  11. "github.com/spf13/viper"
  12. )
  13. // MCPType defines the type of MCP (Model Control Protocol) server.
  14. type MCPType string
  15. // Supported MCP types
  16. const (
  17. MCPStdio MCPType = "stdio"
  18. MCPSse MCPType = "sse"
  19. )
  20. // MCPServer defines the configuration for a Model Control Protocol server.
  21. type MCPServer struct {
  22. Command string `json:"command"`
  23. Env []string `json:"env"`
  24. Args []string `json:"args"`
  25. Type MCPType `json:"type"`
  26. URL string `json:"url"`
  27. Headers map[string]string `json:"headers"`
  28. }
  29. type AgentName string
  30. const (
  31. AgentCoder AgentName = "coder"
  32. AgentTask AgentName = "task"
  33. AgentTitle AgentName = "title"
  34. )
  35. // Agent defines configuration for different LLM models and their token limits.
  36. type Agent struct {
  37. Model models.ModelID `json:"model"`
  38. MaxTokens int64 `json:"maxTokens"`
  39. ReasoningEffort string `json:"reasoningEffort"` // For openai models low,medium,heigh
  40. }
  41. // Provider defines configuration for an LLM provider.
  42. type Provider struct {
  43. APIKey string `json:"apiKey"`
  44. Disabled bool `json:"disabled"`
  45. }
  46. // Data defines storage configuration.
  47. type Data struct {
  48. Directory string `json:"directory"`
  49. }
  50. // LSPConfig defines configuration for Language Server Protocol integration.
  51. type LSPConfig struct {
  52. Disabled bool `json:"enabled"`
  53. Command string `json:"command"`
  54. Args []string `json:"args"`
  55. Options any `json:"options"`
  56. }
  57. // TUIConfig defines the configuration for the Terminal User Interface.
  58. type TUIConfig struct {
  59. Theme string `json:"theme,omitempty"`
  60. }
  61. // Config is the main configuration structure for the application.
  62. type Config struct {
  63. Data Data `json:"data"`
  64. WorkingDir string `json:"wd,omitempty"`
  65. MCPServers map[string]MCPServer `json:"mcpServers,omitempty"`
  66. Providers map[models.ModelProvider]Provider `json:"providers,omitempty"`
  67. LSP map[string]LSPConfig `json:"lsp,omitempty"`
  68. Agents map[AgentName]Agent `json:"agents"`
  69. Debug bool `json:"debug,omitempty"`
  70. DebugLSP bool `json:"debugLSP,omitempty"`
  71. ContextPaths []string `json:"contextPaths,omitempty"`
  72. TUI TUIConfig `json:"tui"`
  73. }
  74. // Application constants
  75. const (
  76. defaultDataDirectory = ".opencode"
  77. defaultLogLevel = "info"
  78. appName = "opencode"
  79. MaxTokensFallbackDefault = 4096
  80. )
  81. var defaultContextPaths = []string{
  82. ".github/copilot-instructions.md",
  83. ".cursorrules",
  84. ".cursor/rules/",
  85. "CLAUDE.md",
  86. "CLAUDE.local.md",
  87. "opencode.md",
  88. "opencode.local.md",
  89. "OpenCode.md",
  90. "OpenCode.local.md",
  91. "OPENCODE.md",
  92. "OPENCODE.local.md",
  93. }
  94. // Global configuration instance
  95. var cfg *Config
  96. // Load initializes the configuration from environment variables and config files.
  97. // If debug is true, debug mode is enabled and log level is set to debug.
  98. // It returns an error if configuration loading fails.
  99. func Load(workingDir string, debug bool) (*Config, error) {
  100. if cfg != nil {
  101. return cfg, nil
  102. }
  103. cfg = &Config{
  104. WorkingDir: workingDir,
  105. MCPServers: make(map[string]MCPServer),
  106. Providers: make(map[models.ModelProvider]Provider),
  107. LSP: make(map[string]LSPConfig),
  108. }
  109. configureViper()
  110. setDefaults(debug)
  111. setProviderDefaults()
  112. // Read global config
  113. if err := readConfig(viper.ReadInConfig()); err != nil {
  114. return cfg, err
  115. }
  116. // Load and merge local config
  117. mergeLocalConfig(workingDir)
  118. // Apply configuration to the struct
  119. if err := viper.Unmarshal(cfg); err != nil {
  120. return cfg, fmt.Errorf("failed to unmarshal config: %w", err)
  121. }
  122. applyDefaultValues()
  123. defaultLevel := slog.LevelInfo
  124. if cfg.Debug {
  125. defaultLevel = slog.LevelDebug
  126. }
  127. if os.Getenv("OPENCODE_DEV_DEBUG") == "true" {
  128. loggingFile := fmt.Sprintf("%s/%s", cfg.Data.Directory, "debug.log")
  129. // if file does not exist create it
  130. if _, err := os.Stat(loggingFile); os.IsNotExist(err) {
  131. if err := os.MkdirAll(cfg.Data.Directory, 0o755); err != nil {
  132. return cfg, fmt.Errorf("failed to create directory: %w", err)
  133. }
  134. if _, err := os.Create(loggingFile); err != nil {
  135. return cfg, fmt.Errorf("failed to create log file: %w", err)
  136. }
  137. }
  138. sloggingFileWriter, err := os.OpenFile(loggingFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o666)
  139. if err != nil {
  140. return cfg, fmt.Errorf("failed to open log file: %w", err)
  141. }
  142. // Configure logger
  143. logger := slog.New(slog.NewTextHandler(sloggingFileWriter, &slog.HandlerOptions{
  144. Level: defaultLevel,
  145. }))
  146. slog.SetDefault(logger)
  147. } else {
  148. // Configure logger
  149. logger := slog.New(slog.NewTextHandler(logging.NewWriter(), &slog.HandlerOptions{
  150. Level: defaultLevel,
  151. }))
  152. slog.SetDefault(logger)
  153. }
  154. // Validate configuration
  155. if err := Validate(); err != nil {
  156. return cfg, fmt.Errorf("config validation failed: %w", err)
  157. }
  158. if cfg.Agents == nil {
  159. cfg.Agents = make(map[AgentName]Agent)
  160. }
  161. // Override the max tokens for title agent
  162. cfg.Agents[AgentTitle] = Agent{
  163. Model: cfg.Agents[AgentTitle].Model,
  164. MaxTokens: 80,
  165. }
  166. return cfg, nil
  167. }
  168. // configureViper sets up viper's configuration paths and environment variables.
  169. func configureViper() {
  170. viper.SetConfigName(fmt.Sprintf(".%s", appName))
  171. viper.SetConfigType("json")
  172. viper.AddConfigPath("$HOME")
  173. viper.AddConfigPath(fmt.Sprintf("$XDG_CONFIG_HOME/%s", appName))
  174. viper.AddConfigPath(fmt.Sprintf("$HOME/.config/%s", appName))
  175. viper.SetEnvPrefix(strings.ToUpper(appName))
  176. viper.AutomaticEnv()
  177. }
  178. // setDefaults configures default values for configuration options.
  179. func setDefaults(debug bool) {
  180. viper.SetDefault("data.directory", defaultDataDirectory)
  181. viper.SetDefault("contextPaths", defaultContextPaths)
  182. viper.SetDefault("tui.theme", "catppuccin")
  183. if debug {
  184. viper.SetDefault("debug", true)
  185. viper.Set("log.level", "debug")
  186. } else {
  187. viper.SetDefault("debug", false)
  188. viper.SetDefault("log.level", defaultLogLevel)
  189. }
  190. }
  191. // setProviderDefaults configures LLM provider defaults based on environment variables.
  192. func setProviderDefaults() {
  193. // Set all API keys we can find in the environment
  194. if apiKey := os.Getenv("ANTHROPIC_API_KEY"); apiKey != "" {
  195. viper.SetDefault("providers.anthropic.apiKey", apiKey)
  196. }
  197. if apiKey := os.Getenv("OPENAI_API_KEY"); apiKey != "" {
  198. viper.SetDefault("providers.openai.apiKey", apiKey)
  199. }
  200. if apiKey := os.Getenv("GEMINI_API_KEY"); apiKey != "" {
  201. viper.SetDefault("providers.gemini.apiKey", apiKey)
  202. }
  203. if apiKey := os.Getenv("GROQ_API_KEY"); apiKey != "" {
  204. viper.SetDefault("providers.groq.apiKey", apiKey)
  205. }
  206. if apiKey := os.Getenv("OPENROUTER_API_KEY"); apiKey != "" {
  207. viper.SetDefault("providers.openrouter.apiKey", apiKey)
  208. }
  209. // Use this order to set the default models
  210. // 1. Anthropic
  211. // 2. OpenAI
  212. // 3. Google Gemini
  213. // 4. Groq
  214. // 5. AWS Bedrock
  215. // Anthropic configuration
  216. if apiKey := os.Getenv("ANTHROPIC_API_KEY"); apiKey != "" {
  217. viper.SetDefault("agents.coder.model", models.Claude37Sonnet)
  218. viper.SetDefault("agents.task.model", models.Claude37Sonnet)
  219. viper.SetDefault("agents.title.model", models.Claude37Sonnet)
  220. return
  221. }
  222. // OpenAI configuration
  223. if apiKey := os.Getenv("OPENAI_API_KEY"); apiKey != "" {
  224. viper.SetDefault("agents.coder.model", models.GPT41)
  225. viper.SetDefault("agents.task.model", models.GPT41Mini)
  226. viper.SetDefault("agents.title.model", models.GPT41Mini)
  227. return
  228. }
  229. // Google Gemini configuration
  230. if apiKey := os.Getenv("GEMINI_API_KEY"); apiKey != "" {
  231. viper.SetDefault("agents.coder.model", models.Gemini25)
  232. viper.SetDefault("agents.task.model", models.Gemini25Flash)
  233. viper.SetDefault("agents.title.model", models.Gemini25Flash)
  234. return
  235. }
  236. // Groq configuration
  237. if apiKey := os.Getenv("GROQ_API_KEY"); apiKey != "" {
  238. viper.SetDefault("agents.coder.model", models.QWENQwq)
  239. viper.SetDefault("agents.task.model", models.QWENQwq)
  240. viper.SetDefault("agents.title.model", models.QWENQwq)
  241. return
  242. }
  243. // OpenRouter configuration
  244. if apiKey := os.Getenv("OPENROUTER_API_KEY"); apiKey != "" {
  245. viper.SetDefault("providers.openrouter.apiKey", apiKey)
  246. viper.SetDefault("agents.coder.model", models.OpenRouterClaude37Sonnet)
  247. viper.SetDefault("agents.task.model", models.OpenRouterClaude37Sonnet)
  248. viper.SetDefault("agents.title.model", models.OpenRouterClaude35Haiku)
  249. return
  250. }
  251. // AWS Bedrock configuration
  252. if hasAWSCredentials() {
  253. viper.SetDefault("agents.coder.model", models.BedrockClaude37Sonnet)
  254. viper.SetDefault("agents.task.model", models.BedrockClaude37Sonnet)
  255. viper.SetDefault("agents.title.model", models.BedrockClaude37Sonnet)
  256. return
  257. }
  258. if os.Getenv("AZURE_OPENAI_ENDPOINT") != "" {
  259. // api-key may be empty when using Entra ID credentials – that's okay
  260. viper.SetDefault("providers.azure.apiKey", os.Getenv("AZURE_OPENAI_API_KEY"))
  261. viper.SetDefault("agents.coder.model", models.AzureGPT41)
  262. viper.SetDefault("agents.task.model", models.AzureGPT41Mini)
  263. viper.SetDefault("agents.title.model", models.AzureGPT41Mini)
  264. return
  265. }
  266. }
  267. // hasAWSCredentials checks if AWS credentials are available in the environment.
  268. func hasAWSCredentials() bool {
  269. // Check for explicit AWS credentials
  270. if os.Getenv("AWS_ACCESS_KEY_ID") != "" && os.Getenv("AWS_SECRET_ACCESS_KEY") != "" {
  271. return true
  272. }
  273. // Check for AWS profile
  274. if os.Getenv("AWS_PROFILE") != "" || os.Getenv("AWS_DEFAULT_PROFILE") != "" {
  275. return true
  276. }
  277. // Check for AWS region
  278. if os.Getenv("AWS_REGION") != "" || os.Getenv("AWS_DEFAULT_REGION") != "" {
  279. return true
  280. }
  281. // Check if running on EC2 with instance profile
  282. if os.Getenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI") != "" ||
  283. os.Getenv("AWS_CONTAINER_CREDENTIALS_FULL_URI") != "" {
  284. return true
  285. }
  286. return false
  287. }
  288. // readConfig handles the result of reading a configuration file.
  289. func readConfig(err error) error {
  290. if err == nil {
  291. return nil
  292. }
  293. // It's okay if the config file doesn't exist
  294. if _, ok := err.(viper.ConfigFileNotFoundError); ok {
  295. return nil
  296. }
  297. return fmt.Errorf("failed to read config: %w", err)
  298. }
  299. // mergeLocalConfig loads and merges configuration from the local directory.
  300. func mergeLocalConfig(workingDir string) {
  301. local := viper.New()
  302. local.SetConfigName(fmt.Sprintf(".%s", appName))
  303. local.SetConfigType("json")
  304. local.AddConfigPath(workingDir)
  305. // Merge local config if it exists
  306. if err := local.ReadInConfig(); err == nil {
  307. viper.MergeConfigMap(local.AllSettings())
  308. }
  309. }
  310. // applyDefaultValues sets default values for configuration fields that need processing.
  311. func applyDefaultValues() {
  312. // Set default MCP type if not specified
  313. for k, v := range cfg.MCPServers {
  314. if v.Type == "" {
  315. v.Type = MCPStdio
  316. cfg.MCPServers[k] = v
  317. }
  318. }
  319. }
  320. // It validates model IDs and providers, ensuring they are supported.
  321. func validateAgent(cfg *Config, name AgentName, agent Agent) error {
  322. // Check if model exists
  323. model, modelExists := models.SupportedModels[agent.Model]
  324. if !modelExists {
  325. logging.Warn("unsupported model configured, reverting to default",
  326. "agent", name,
  327. "configured_model", agent.Model)
  328. // Set default model based on available providers
  329. if setDefaultModelForAgent(name) {
  330. logging.Info("set default model for agent", "agent", name, "model", cfg.Agents[name].Model)
  331. } else {
  332. return fmt.Errorf("no valid provider available for agent %s", name)
  333. }
  334. return nil
  335. }
  336. // Check if provider for the model is configured
  337. provider := model.Provider
  338. providerCfg, providerExists := cfg.Providers[provider]
  339. if !providerExists {
  340. // Provider not configured, check if we have environment variables
  341. apiKey := getProviderAPIKey(provider)
  342. if apiKey == "" {
  343. logging.Warn("provider not configured for model, reverting to default",
  344. "agent", name,
  345. "model", agent.Model,
  346. "provider", provider)
  347. // Set default model based on available providers
  348. if setDefaultModelForAgent(name) {
  349. logging.Info("set default model for agent", "agent", name, "model", cfg.Agents[name].Model)
  350. } else {
  351. return fmt.Errorf("no valid provider available for agent %s", name)
  352. }
  353. } else {
  354. // Add provider with API key from environment
  355. cfg.Providers[provider] = Provider{
  356. APIKey: apiKey,
  357. }
  358. logging.Info("added provider from environment", "provider", provider)
  359. }
  360. } else if providerCfg.Disabled || providerCfg.APIKey == "" {
  361. // Provider is disabled or has no API key
  362. logging.Warn("provider is disabled or has no API key, reverting to default",
  363. "agent", name,
  364. "model", agent.Model,
  365. "provider", provider)
  366. // Set default model based on available providers
  367. if setDefaultModelForAgent(name) {
  368. logging.Info("set default model for agent", "agent", name, "model", cfg.Agents[name].Model)
  369. } else {
  370. return fmt.Errorf("no valid provider available for agent %s", name)
  371. }
  372. }
  373. // Validate max tokens
  374. if agent.MaxTokens <= 0 {
  375. logging.Warn("invalid max tokens, setting to default",
  376. "agent", name,
  377. "model", agent.Model,
  378. "max_tokens", agent.MaxTokens)
  379. // Update the agent with default max tokens
  380. updatedAgent := cfg.Agents[name]
  381. if model.DefaultMaxTokens > 0 {
  382. updatedAgent.MaxTokens = model.DefaultMaxTokens
  383. } else {
  384. updatedAgent.MaxTokens = MaxTokensFallbackDefault
  385. }
  386. cfg.Agents[name] = updatedAgent
  387. } else if model.ContextWindow > 0 && agent.MaxTokens > model.ContextWindow/2 {
  388. // Ensure max tokens doesn't exceed half the context window (reasonable limit)
  389. logging.Warn("max tokens exceeds half the context window, adjusting",
  390. "agent", name,
  391. "model", agent.Model,
  392. "max_tokens", agent.MaxTokens,
  393. "context_window", model.ContextWindow)
  394. // Update the agent with adjusted max tokens
  395. updatedAgent := cfg.Agents[name]
  396. updatedAgent.MaxTokens = model.ContextWindow / 2
  397. cfg.Agents[name] = updatedAgent
  398. }
  399. // Validate reasoning effort for models that support reasoning
  400. if model.CanReason && provider == models.ProviderOpenAI {
  401. if agent.ReasoningEffort == "" {
  402. // Set default reasoning effort for models that support it
  403. logging.Info("setting default reasoning effort for model that supports reasoning",
  404. "agent", name,
  405. "model", agent.Model)
  406. // Update the agent with default reasoning effort
  407. updatedAgent := cfg.Agents[name]
  408. updatedAgent.ReasoningEffort = "medium"
  409. cfg.Agents[name] = updatedAgent
  410. } else {
  411. // Check if reasoning effort is valid (low, medium, high)
  412. effort := strings.ToLower(agent.ReasoningEffort)
  413. if effort != "low" && effort != "medium" && effort != "high" {
  414. logging.Warn("invalid reasoning effort, setting to medium",
  415. "agent", name,
  416. "model", agent.Model,
  417. "reasoning_effort", agent.ReasoningEffort)
  418. // Update the agent with valid reasoning effort
  419. updatedAgent := cfg.Agents[name]
  420. updatedAgent.ReasoningEffort = "medium"
  421. cfg.Agents[name] = updatedAgent
  422. }
  423. }
  424. } else if !model.CanReason && agent.ReasoningEffort != "" {
  425. // Model doesn't support reasoning but reasoning effort is set
  426. logging.Warn("model doesn't support reasoning but reasoning effort is set, ignoring",
  427. "agent", name,
  428. "model", agent.Model,
  429. "reasoning_effort", agent.ReasoningEffort)
  430. // Update the agent to remove reasoning effort
  431. updatedAgent := cfg.Agents[name]
  432. updatedAgent.ReasoningEffort = ""
  433. cfg.Agents[name] = updatedAgent
  434. }
  435. return nil
  436. }
  437. // Validate checks if the configuration is valid and applies defaults where needed.
  438. func Validate() error {
  439. if cfg == nil {
  440. return fmt.Errorf("config not loaded")
  441. }
  442. // Validate agent models
  443. for name, agent := range cfg.Agents {
  444. if err := validateAgent(cfg, name, agent); err != nil {
  445. return err
  446. }
  447. }
  448. // Validate providers
  449. for provider, providerCfg := range cfg.Providers {
  450. if providerCfg.APIKey == "" && !providerCfg.Disabled {
  451. logging.Warn("provider has no API key, marking as disabled", "provider", provider)
  452. providerCfg.Disabled = true
  453. cfg.Providers[provider] = providerCfg
  454. }
  455. }
  456. // Validate LSP configurations
  457. for language, lspConfig := range cfg.LSP {
  458. if lspConfig.Command == "" && !lspConfig.Disabled {
  459. logging.Warn("LSP configuration has no command, marking as disabled", "language", language)
  460. lspConfig.Disabled = true
  461. cfg.LSP[language] = lspConfig
  462. }
  463. }
  464. return nil
  465. }
  466. // getProviderAPIKey gets the API key for a provider from environment variables
  467. func getProviderAPIKey(provider models.ModelProvider) string {
  468. switch provider {
  469. case models.ProviderAnthropic:
  470. return os.Getenv("ANTHROPIC_API_KEY")
  471. case models.ProviderOpenAI:
  472. return os.Getenv("OPENAI_API_KEY")
  473. case models.ProviderGemini:
  474. return os.Getenv("GEMINI_API_KEY")
  475. case models.ProviderGROQ:
  476. return os.Getenv("GROQ_API_KEY")
  477. case models.ProviderAzure:
  478. return os.Getenv("AZURE_OPENAI_API_KEY")
  479. case models.ProviderOpenRouter:
  480. return os.Getenv("OPENROUTER_API_KEY")
  481. case models.ProviderBedrock:
  482. if hasAWSCredentials() {
  483. return "aws-credentials-available"
  484. }
  485. }
  486. return ""
  487. }
  488. // setDefaultModelForAgent sets a default model for an agent based on available providers
  489. func setDefaultModelForAgent(agent AgentName) bool {
  490. // Check providers in order of preference
  491. if apiKey := os.Getenv("ANTHROPIC_API_KEY"); apiKey != "" {
  492. maxTokens := int64(5000)
  493. if agent == AgentTitle {
  494. maxTokens = 80
  495. }
  496. cfg.Agents[agent] = Agent{
  497. Model: models.Claude37Sonnet,
  498. MaxTokens: maxTokens,
  499. }
  500. return true
  501. }
  502. if apiKey := os.Getenv("OPENAI_API_KEY"); apiKey != "" {
  503. var model models.ModelID
  504. maxTokens := int64(5000)
  505. reasoningEffort := ""
  506. switch agent {
  507. case AgentTitle:
  508. model = models.GPT41Mini
  509. maxTokens = 80
  510. case AgentTask:
  511. model = models.GPT41Mini
  512. default:
  513. model = models.GPT41
  514. }
  515. // Check if model supports reasoning
  516. if modelInfo, ok := models.SupportedModels[model]; ok && modelInfo.CanReason {
  517. reasoningEffort = "medium"
  518. }
  519. cfg.Agents[agent] = Agent{
  520. Model: model,
  521. MaxTokens: maxTokens,
  522. ReasoningEffort: reasoningEffort,
  523. }
  524. return true
  525. }
  526. if apiKey := os.Getenv("OPENROUTER_API_KEY"); apiKey != "" {
  527. var model models.ModelID
  528. maxTokens := int64(5000)
  529. reasoningEffort := ""
  530. switch agent {
  531. case AgentTitle:
  532. model = models.OpenRouterClaude35Haiku
  533. maxTokens = 80
  534. case AgentTask:
  535. model = models.OpenRouterClaude37Sonnet
  536. default:
  537. model = models.OpenRouterClaude37Sonnet
  538. }
  539. // Check if model supports reasoning
  540. if modelInfo, ok := models.SupportedModels[model]; ok && modelInfo.CanReason {
  541. reasoningEffort = "medium"
  542. }
  543. cfg.Agents[agent] = Agent{
  544. Model: model,
  545. MaxTokens: maxTokens,
  546. ReasoningEffort: reasoningEffort,
  547. }
  548. return true
  549. }
  550. if apiKey := os.Getenv("GEMINI_API_KEY"); apiKey != "" {
  551. var model models.ModelID
  552. maxTokens := int64(5000)
  553. if agent == AgentTitle {
  554. model = models.Gemini25Flash
  555. maxTokens = 80
  556. } else {
  557. model = models.Gemini25
  558. }
  559. cfg.Agents[agent] = Agent{
  560. Model: model,
  561. MaxTokens: maxTokens,
  562. }
  563. return true
  564. }
  565. if apiKey := os.Getenv("GROQ_API_KEY"); apiKey != "" {
  566. maxTokens := int64(5000)
  567. if agent == AgentTitle {
  568. maxTokens = 80
  569. }
  570. cfg.Agents[agent] = Agent{
  571. Model: models.QWENQwq,
  572. MaxTokens: maxTokens,
  573. }
  574. return true
  575. }
  576. if hasAWSCredentials() {
  577. maxTokens := int64(5000)
  578. if agent == AgentTitle {
  579. maxTokens = 80
  580. }
  581. cfg.Agents[agent] = Agent{
  582. Model: models.BedrockClaude37Sonnet,
  583. MaxTokens: maxTokens,
  584. ReasoningEffort: "medium", // Claude models support reasoning
  585. }
  586. return true
  587. }
  588. return false
  589. }
  590. // Get returns the current configuration.
  591. // It's safe to call this function multiple times.
  592. func Get() *Config {
  593. return cfg
  594. }
  595. // WorkingDirectory returns the current working directory from the configuration.
  596. func WorkingDirectory() string {
  597. if cfg == nil {
  598. panic("config not loaded")
  599. }
  600. return cfg.WorkingDir
  601. }
  602. func UpdateAgentModel(agentName AgentName, modelID models.ModelID) error {
  603. if cfg == nil {
  604. panic("config not loaded")
  605. }
  606. existingAgentCfg := cfg.Agents[agentName]
  607. model, ok := models.SupportedModels[modelID]
  608. if !ok {
  609. return fmt.Errorf("model %s not supported", modelID)
  610. }
  611. maxTokens := existingAgentCfg.MaxTokens
  612. if model.DefaultMaxTokens > 0 {
  613. maxTokens = model.DefaultMaxTokens
  614. }
  615. newAgentCfg := Agent{
  616. Model: modelID,
  617. MaxTokens: maxTokens,
  618. ReasoningEffort: existingAgentCfg.ReasoningEffort,
  619. }
  620. cfg.Agents[agentName] = newAgentCfg
  621. if err := validateAgent(cfg, agentName, newAgentCfg); err != nil {
  622. // revert config update on failure
  623. cfg.Agents[agentName] = existingAgentCfg
  624. return fmt.Errorf("failed to update agent model: %w", err)
  625. }
  626. return nil
  627. }
  628. // UpdateTheme updates the theme in the configuration and writes it to the config file.
  629. func UpdateTheme(themeName string) error {
  630. if cfg == nil {
  631. return fmt.Errorf("config not loaded")
  632. }
  633. // Update the in-memory config
  634. cfg.TUI.Theme = themeName
  635. // Get the config file path
  636. configFile := viper.ConfigFileUsed()
  637. if configFile == "" {
  638. // If no config file exists yet, create one with default settings
  639. viper.Set("tui.theme", themeName)
  640. return viper.SafeWriteConfig()
  641. }
  642. // Read the existing config file
  643. configData, err := os.ReadFile(configFile)
  644. if err != nil {
  645. return fmt.Errorf("failed to read config file: %w", err)
  646. }
  647. // Parse the JSON
  648. var configMap map[string]interface{}
  649. if err := json.Unmarshal(configData, &configMap); err != nil {
  650. return fmt.Errorf("failed to parse config file: %w", err)
  651. }
  652. // Update just the theme value
  653. tuiConfig, ok := configMap["tui"].(map[string]interface{})
  654. if !ok {
  655. // TUI config doesn't exist yet, create it
  656. configMap["tui"] = map[string]interface{}{"theme": themeName}
  657. } else {
  658. // Update existing TUI config
  659. tuiConfig["theme"] = themeName
  660. configMap["tui"] = tuiConfig
  661. }
  662. // Write the updated config back to file
  663. updatedData, err := json.MarshalIndent(configMap, "", " ")
  664. if err != nil {
  665. return fmt.Errorf("failed to marshal config: %w", err)
  666. }
  667. if err := os.WriteFile(configFile, updatedData, 0644); err != nil {
  668. return fmt.Errorf("failed to write config file: %w", err)
  669. }
  670. return nil
  671. }