config.go 22 KB

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