1package config
2
3import (
4 "context"
5 "fmt"
6 "log/slog"
7 "net/http"
8 "net/url"
9 "os"
10 "slices"
11 "strings"
12 "time"
13
14 "github.com/charmbracelet/catwalk/pkg/catwalk"
15 "github.com/charmbracelet/crush/internal/csync"
16 "github.com/charmbracelet/crush/internal/env"
17 "github.com/tidwall/sjson"
18)
19
20const (
21 appName = "crush"
22 defaultDataDirectory = ".crush"
23)
24
25var defaultContextPaths = []string{
26 ".github/copilot-instructions.md",
27 ".cursorrules",
28 ".cursor/rules/",
29 "CLAUDE.md",
30 "CLAUDE.local.md",
31 "GEMINI.md",
32 "gemini.md",
33 "crush.md",
34 "crush.local.md",
35 "Crush.md",
36 "Crush.local.md",
37 "CRUSH.md",
38 "CRUSH.local.md",
39 "AGENTS.md",
40 "agents.md",
41 "Agents.md",
42}
43
44type SelectedModelType string
45
46const (
47 SelectedModelTypeLarge SelectedModelType = "large"
48 SelectedModelTypeSmall SelectedModelType = "small"
49)
50
51type SelectedModel struct {
52 // The model id as used by the provider API.
53 // Required.
54 Model string `json:"model" jsonschema:"required,description=The model ID as used by the provider API,example=gpt-4o"`
55 // The model provider, same as the key/id used in the providers config.
56 // Required.
57 Provider string `json:"provider" jsonschema:"required,description=The model provider ID that matches a key in the providers config,example=openai"`
58
59 // Only used by models that use the openai provider and need this set.
60 ReasoningEffort string `json:"reasoning_effort,omitempty" jsonschema:"description=Reasoning effort level for OpenAI models that support it,enum=low,enum=medium,enum=high"`
61
62 // Overrides the default model configuration.
63 MaxTokens int64 `json:"max_tokens,omitempty" jsonschema:"description=Maximum number of tokens for model responses,minimum=1,maximum=200000,example=4096"`
64
65 // Used by anthropic models that can reason to indicate if the model should think.
66 Think bool `json:"think,omitempty" jsonschema:"description=Enable thinking mode for Anthropic models that support reasoning"`
67}
68
69type ProviderConfig struct {
70 // The provider's id.
71 ID string `json:"id,omitempty" jsonschema:"description=Unique identifier for the provider,example=openai"`
72 // The provider's name, used for display purposes.
73 Name string `json:"name,omitempty" jsonschema:"description=Human-readable name for the provider,example=OpenAI"`
74 // The provider's API endpoint.
75 BaseURL string `json:"base_url,omitempty" jsonschema:"description=Base URL for the provider's API,format=uri,example=https://api.openai.com/v1"`
76 // The provider type, e.g. "openai", "anthropic", etc. if empty it defaults to openai.
77 Type catwalk.Type `json:"type,omitempty" jsonschema:"description=Provider type that determines the API format,enum=openai,enum=anthropic,enum=gemini,enum=azure,enum=vertexai,default=openai"`
78 // The provider's API key.
79 APIKey string `json:"api_key,omitempty" jsonschema:"description=API key for authentication with the provider,example=$OPENAI_API_KEY"`
80 // Marks the provider as disabled.
81 Disable bool `json:"disable,omitempty" jsonschema:"description=Whether this provider is disabled,default=false"`
82
83 // Custom system prompt prefix.
84 SystemPromptPrefix string `json:"system_prompt_prefix,omitempty" jsonschema:"description=Custom prefix to add to system prompts for this provider"`
85
86 // Extra headers to send with each request to the provider.
87 ExtraHeaders map[string]string `json:"extra_headers,omitempty" jsonschema:"description=Additional HTTP headers to send with requests"`
88 // Extra body
89 ExtraBody map[string]any `json:"extra_body,omitempty" jsonschema:"description=Additional fields to include in request bodies"`
90
91 // Used to pass extra parameters to the provider.
92 ExtraParams map[string]string `json:"-"`
93
94 // The provider models
95 Models []catwalk.Model `json:"models,omitempty" jsonschema:"description=List of models available from this provider"`
96}
97
98type MCPType string
99
100const (
101 MCPStdio MCPType = "stdio"
102 MCPSse MCPType = "sse"
103 MCPHttp MCPType = "http"
104)
105
106type MCPConfig struct {
107 Command string `json:"command,omitempty" jsonschema:"description=Command to execute for stdio MCP servers,example=npx"`
108 Env map[string]string `json:"env,omitempty" jsonschema:"description=Environment variables to set for the MCP server"`
109 Args []string `json:"args,omitempty" jsonschema:"description=Arguments to pass to the MCP server command"`
110 Type MCPType `json:"type" jsonschema:"required,description=Type of MCP connection,enum=stdio,enum=sse,enum=http,default=stdio"`
111 URL string `json:"url,omitempty" jsonschema:"description=URL for HTTP or SSE MCP servers,format=uri,example=http://localhost:3000/mcp"`
112 Disabled bool `json:"disabled,omitempty" jsonschema:"description=Whether this MCP server is disabled,default=false"`
113 Timeout int `json:"timeout,omitempty" jsonschema:"description=Timeout in seconds for MCP server connections,default=15,example=30,example=60,example=120"`
114
115 // TODO: maybe make it possible to get the value from the env
116 Headers map[string]string `json:"headers,omitempty" jsonschema:"description=HTTP headers for HTTP/SSE MCP servers"`
117}
118
119type LSPConfig struct {
120 Disabled bool `json:"enabled,omitempty" jsonschema:"description=Whether this LSP server is disabled,default=false"`
121 Command string `json:"command" jsonschema:"required,description=Command to execute for the LSP server,example=gopls"`
122 Args []string `json:"args,omitempty" jsonschema:"description=Arguments to pass to the LSP server command"`
123 Env map[string]string `json:"env,omitempty" jsonschema:"description=Environment variables to set to the LSP server command"`
124 Options any `json:"options,omitempty" jsonschema:"description=LSP server-specific configuration options"`
125 FileTypes []string `json:"filetypes,omitempty" jsonschema:"description=File types this LSP server handles,example=go,example=mod,example=rs,example=c,example=js,example=ts"`
126}
127
128type TUIOptions struct {
129 CompactMode bool `json:"compact_mode,omitempty" jsonschema:"description=Enable compact mode for the TUI interface,default=false"`
130 DiffMode string `json:"diff_mode,omitempty" jsonschema:"description=Diff mode for the TUI interface,enum=unified,enum=split"`
131 // Here we can add themes later or any TUI related options
132}
133
134type Permissions struct {
135 AllowedTools []string `json:"allowed_tools,omitempty" jsonschema:"description=List of tools that don't require permission prompts,example=bash,example=view"` // Tools that don't require permission prompts
136 SkipRequests bool `json:"-"` // Automatically accept all permissions (YOLO mode)
137}
138
139type Options struct {
140 ContextPaths []string `json:"context_paths,omitempty" jsonschema:"description=Paths to files containing context information for the AI,example=.cursorrules,example=CRUSH.md"`
141 TUI *TUIOptions `json:"tui,omitempty" jsonschema:"description=Terminal user interface options"`
142 Debug bool `json:"debug,omitempty" jsonschema:"description=Enable debug logging,default=false"`
143 DebugLSP bool `json:"debug_lsp,omitempty" jsonschema:"description=Enable debug logging for LSP servers,default=false"`
144 DisableAutoSummarize bool `json:"disable_auto_summarize,omitempty" jsonschema:"description=Disable automatic conversation summarization,default=false"`
145 DataDirectory string `json:"data_directory,omitempty" jsonschema:"description=Directory for storing application data (relative to working directory),default=.crush,example=.crush"` // Relative to the cwd
146}
147
148type MCPs map[string]MCPConfig
149
150type MCP struct {
151 Name string `json:"name"`
152 MCP MCPConfig `json:"mcp"`
153}
154
155func (m MCPs) Sorted() []MCP {
156 sorted := make([]MCP, 0, len(m))
157 for k, v := range m {
158 sorted = append(sorted, MCP{
159 Name: k,
160 MCP: v,
161 })
162 }
163 slices.SortFunc(sorted, func(a, b MCP) int {
164 return strings.Compare(a.Name, b.Name)
165 })
166 return sorted
167}
168
169type LSPs map[string]LSPConfig
170
171type LSP struct {
172 Name string `json:"name"`
173 LSP LSPConfig `json:"lsp"`
174}
175
176func (l LSPs) Sorted() []LSP {
177 sorted := make([]LSP, 0, len(l))
178 for k, v := range l {
179 sorted = append(sorted, LSP{
180 Name: k,
181 LSP: v,
182 })
183 }
184 slices.SortFunc(sorted, func(a, b LSP) int {
185 return strings.Compare(a.Name, b.Name)
186 })
187 return sorted
188}
189
190func (l LSPConfig) ResolvedEnv() []string {
191 return resolveEnvs(l.Env)
192}
193
194func (m MCPConfig) ResolvedEnv() []string {
195 return resolveEnvs(m.Env)
196}
197
198func (m MCPConfig) ResolvedHeaders() map[string]string {
199 resolver := NewShellVariableResolver(env.New())
200 for e, v := range m.Headers {
201 var err error
202 m.Headers[e], err = resolver.ResolveValue(v)
203 if err != nil {
204 slog.Error("error resolving header variable", "error", err, "variable", e, "value", v)
205 continue
206 }
207 }
208 return m.Headers
209}
210
211type Agent struct {
212 ID string `json:"id,omitempty"`
213 Name string `json:"name,omitempty"`
214 Description string `json:"description,omitempty"`
215 // This is the id of the system prompt used by the agent
216 Disabled bool `json:"disabled,omitempty"`
217
218 Model SelectedModelType `json:"model" jsonschema:"required,description=The model type to use for this agent,enum=large,enum=small,default=large"`
219
220 // The available tools for the agent
221 // if this is nil, all tools are available
222 AllowedTools []string `json:"allowed_tools,omitempty"`
223
224 // this tells us which MCPs are available for this agent
225 // if this is empty all mcps are available
226 // the string array is the list of tools from the AllowedMCP the agent has available
227 // if the string array is nil, all tools from the AllowedMCP are available
228 AllowedMCP map[string][]string `json:"allowed_mcp,omitempty"`
229
230 // The list of LSPs that this agent can use
231 // if this is nil, all LSPs are available
232 AllowedLSP []string `json:"allowed_lsp,omitempty"`
233
234 // Overrides the context paths for this agent
235 ContextPaths []string `json:"context_paths,omitempty"`
236}
237
238// Config holds the configuration for crush.
239type Config struct {
240 Schema string `json:"$schema,omitempty"`
241
242 // We currently only support large/small as values here.
243 Models map[SelectedModelType]SelectedModel `json:"models,omitempty" jsonschema:"description=Model configurations for different model types,example={\"large\":{\"model\":\"gpt-4o\",\"provider\":\"openai\"}}"`
244
245 // The providers that are configured
246 Providers *csync.Map[string, ProviderConfig] `json:"providers,omitempty" jsonschema:"description=AI provider configurations"`
247
248 MCP MCPs `json:"mcp,omitempty" jsonschema:"description=Model Context Protocol server configurations"`
249
250 LSP LSPs `json:"lsp,omitempty" jsonschema:"description=Language Server Protocol configurations"`
251
252 Options *Options `json:"options,omitempty" jsonschema:"description=General application options"`
253
254 Permissions *Permissions `json:"permissions,omitempty" jsonschema:"description=Permission settings for tool usage"`
255
256 // Internal
257 workingDir string `json:"-"`
258 // TODO: most likely remove this concept when I come back to it
259 Agents map[string]Agent `json:"-"`
260 // TODO: find a better way to do this this should probably not be part of the config
261 resolver VariableResolver
262 dataConfigDir string `json:"-"`
263 knownProviders []catwalk.Provider `json:"-"`
264}
265
266func (c *Config) WorkingDir() string {
267 return c.workingDir
268}
269
270func (c *Config) EnabledProviders() []ProviderConfig {
271 var enabled []ProviderConfig
272 for p := range c.Providers.Seq() {
273 if !p.Disable {
274 enabled = append(enabled, p)
275 }
276 }
277 return enabled
278}
279
280// IsConfigured return true if at least one provider is configured
281func (c *Config) IsConfigured() bool {
282 return len(c.EnabledProviders()) > 0
283}
284
285func (c *Config) GetModel(provider, model string) *catwalk.Model {
286 if providerConfig, ok := c.Providers.Get(provider); ok {
287 for _, m := range providerConfig.Models {
288 if m.ID == model {
289 return &m
290 }
291 }
292 }
293 return nil
294}
295
296func (c *Config) GetProviderForModel(modelType SelectedModelType) *ProviderConfig {
297 model, ok := c.Models[modelType]
298 if !ok {
299 return nil
300 }
301 if providerConfig, ok := c.Providers.Get(model.Provider); ok {
302 return &providerConfig
303 }
304 return nil
305}
306
307func (c *Config) GetModelByType(modelType SelectedModelType) *catwalk.Model {
308 model, ok := c.Models[modelType]
309 if !ok {
310 return nil
311 }
312 return c.GetModel(model.Provider, model.Model)
313}
314
315func (c *Config) LargeModel() *catwalk.Model {
316 model, ok := c.Models[SelectedModelTypeLarge]
317 if !ok {
318 return nil
319 }
320 return c.GetModel(model.Provider, model.Model)
321}
322
323func (c *Config) SmallModel() *catwalk.Model {
324 model, ok := c.Models[SelectedModelTypeSmall]
325 if !ok {
326 return nil
327 }
328 return c.GetModel(model.Provider, model.Model)
329}
330
331func (c *Config) SetCompactMode(enabled bool) error {
332 if c.Options == nil {
333 c.Options = &Options{}
334 }
335 c.Options.TUI.CompactMode = enabled
336 return c.SetConfigField("options.tui.compact_mode", enabled)
337}
338
339func (c *Config) Resolve(key string) (string, error) {
340 if c.resolver == nil {
341 return "", fmt.Errorf("no variable resolver configured")
342 }
343 return c.resolver.ResolveValue(key)
344}
345
346func (c *Config) UpdatePreferredModel(modelType SelectedModelType, model SelectedModel) error {
347 c.Models[modelType] = model
348 if err := c.SetConfigField(fmt.Sprintf("models.%s", modelType), model); err != nil {
349 return fmt.Errorf("failed to update preferred model: %w", err)
350 }
351 return nil
352}
353
354func (c *Config) SetConfigField(key string, value any) error {
355 // read the data
356 data, err := os.ReadFile(c.dataConfigDir)
357 if err != nil {
358 if os.IsNotExist(err) {
359 data = []byte("{}")
360 } else {
361 return fmt.Errorf("failed to read config file: %w", err)
362 }
363 }
364
365 newValue, err := sjson.Set(string(data), key, value)
366 if err != nil {
367 return fmt.Errorf("failed to set config field %s: %w", key, err)
368 }
369 if err := os.WriteFile(c.dataConfigDir, []byte(newValue), 0o600); err != nil {
370 return fmt.Errorf("failed to write config file: %w", err)
371 }
372 return nil
373}
374
375func (c *Config) SetProviderAPIKey(providerID, apiKey string) error {
376 // First save to the config file
377 err := c.SetConfigField("providers."+providerID+".api_key", apiKey)
378 if err != nil {
379 return fmt.Errorf("failed to save API key to config file: %w", err)
380 }
381
382 providerConfig, exists := c.Providers.Get(providerID)
383 if exists {
384 providerConfig.APIKey = apiKey
385 c.Providers.Set(providerID, providerConfig)
386 return nil
387 }
388
389 var foundProvider *catwalk.Provider
390 for _, p := range c.knownProviders {
391 if string(p.ID) == providerID {
392 foundProvider = &p
393 break
394 }
395 }
396
397 if foundProvider != nil {
398 // Create new provider config based on known provider
399 providerConfig = ProviderConfig{
400 ID: providerID,
401 Name: foundProvider.Name,
402 BaseURL: foundProvider.APIEndpoint,
403 Type: foundProvider.Type,
404 APIKey: apiKey,
405 Disable: false,
406 ExtraHeaders: make(map[string]string),
407 ExtraParams: make(map[string]string),
408 Models: foundProvider.Models,
409 }
410 } else {
411 return fmt.Errorf("provider with ID %s not found in known providers", providerID)
412 }
413 // Store the updated provider config
414 c.Providers.Set(providerID, providerConfig)
415 return nil
416}
417
418func (c *Config) SetupAgents() {
419 agents := map[string]Agent{
420 "coder": {
421 ID: "coder",
422 Name: "Coder",
423 Description: "An agent that helps with executing coding tasks.",
424 Model: SelectedModelTypeLarge,
425 ContextPaths: c.Options.ContextPaths,
426 // All tools allowed
427 },
428 "task": {
429 ID: "task",
430 Name: "Task",
431 Description: "An agent that helps with searching for context and finding implementation details.",
432 Model: SelectedModelTypeLarge,
433 ContextPaths: c.Options.ContextPaths,
434 AllowedTools: []string{
435 "glob",
436 "grep",
437 "ls",
438 "sourcegraph",
439 "view",
440 },
441 // NO MCPs or LSPs by default
442 AllowedMCP: map[string][]string{},
443 AllowedLSP: []string{},
444 },
445 }
446 c.Agents = agents
447}
448
449func (c *Config) Resolver() VariableResolver {
450 return c.resolver
451}
452
453func (c *ProviderConfig) TestConnection(resolver VariableResolver) error {
454 testURL := ""
455 headers := make(map[string]string)
456 apiKey, _ := resolver.ResolveValue(c.APIKey)
457 switch c.Type {
458 case catwalk.TypeOpenAI:
459 baseURL, _ := resolver.ResolveValue(c.BaseURL)
460 if baseURL == "" {
461 baseURL = "https://api.openai.com/v1"
462 }
463 if c.ID == "openrouter" {
464 testURL = baseURL + "/credits"
465 } else {
466 testURL = baseURL + "/models"
467 }
468 headers["Authorization"] = "Bearer " + apiKey
469 case catwalk.TypeAnthropic:
470 baseURL, _ := resolver.ResolveValue(c.BaseURL)
471 if baseURL == "" {
472 baseURL = "https://api.anthropic.com/v1"
473 }
474 testURL = baseURL + "/models"
475 headers["x-api-key"] = apiKey
476 headers["anthropic-version"] = "2023-06-01"
477 case catwalk.TypeGemini:
478 baseURL, _ := resolver.ResolveValue(c.BaseURL)
479 if baseURL == "" {
480 baseURL = "https://generativelanguage.googleapis.com"
481 }
482 testURL = baseURL + "/v1beta/models?key=" + url.QueryEscape(apiKey)
483 }
484 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
485 defer cancel()
486 client := &http.Client{}
487 req, err := http.NewRequestWithContext(ctx, "GET", testURL, nil)
488 if err != nil {
489 return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
490 }
491 for k, v := range headers {
492 req.Header.Set(k, v)
493 }
494 for k, v := range c.ExtraHeaders {
495 req.Header.Set(k, v)
496 }
497 b, err := client.Do(req)
498 if err != nil {
499 return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
500 }
501 if b.StatusCode != http.StatusOK {
502 return fmt.Errorf("failed to connect to provider %s: %s", c.ID, b.Status)
503 }
504 _ = b.Body.Close()
505 return nil
506}
507
508func resolveEnvs(envs map[string]string) []string {
509 resolver := NewShellVariableResolver(env.New())
510 for e, v := range envs {
511 var err error
512 envs[e], err = resolver.ResolveValue(v)
513 if err != nil {
514 slog.Error("error resolving environment variable", "error", err, "variable", e, "value", v)
515 continue
516 }
517 }
518
519 res := make([]string, 0, len(envs))
520 for k, v := range envs {
521 res = append(res, fmt.Sprintf("%s=%s", k, v))
522 }
523 return res
524}