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
114 // TODO: maybe make it possible to get the value from the env
115 Headers map[string]string `json:"headers,omitempty" jsonschema:"description=HTTP headers for HTTP/SSE MCP servers"`
116}
117
118type LSPConfig struct {
119 Disabled bool `json:"enabled,omitempty" jsonschema:"description=Whether this LSP server is disabled,default=false"`
120 Command string `json:"command" jsonschema:"required,description=Command to execute for the LSP server,example=gopls"`
121 Args []string `json:"args,omitempty" jsonschema:"description=Arguments to pass to the LSP server command"`
122 Options any `json:"options,omitempty" jsonschema:"description=LSP server-specific configuration options"`
123}
124
125type TUIOptions struct {
126 CompactMode bool `json:"compact_mode,omitempty" jsonschema:"description=Enable compact mode for the TUI interface,default=false"`
127 DiffMode string `json:"diff_mode,omitempty" jsonschema:"description=Diff mode for the TUI interface,enum=unified,enum=split"`
128 // Here we can add themes later or any TUI related options
129}
130
131type Permissions struct {
132 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
133 SkipRequests bool `json:"-"` // Automatically accept all permissions (YOLO mode)
134}
135
136type Options struct {
137 ContextPaths []string `json:"context_paths,omitempty" jsonschema:"description=Paths to files containing context information for the AI,example=.cursorrules,example=CRUSH.md"`
138 TUI *TUIOptions `json:"tui,omitempty" jsonschema:"description=Terminal user interface options"`
139 Debug bool `json:"debug,omitempty" jsonschema:"description=Enable debug logging,default=false"`
140 DebugLSP bool `json:"debug_lsp,omitempty" jsonschema:"description=Enable debug logging for LSP servers,default=false"`
141 DisableAutoSummarize bool `json:"disable_auto_summarize,omitempty" jsonschema:"description=Disable automatic conversation summarization,default=false"`
142 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
143}
144
145type MCPs map[string]MCPConfig
146
147type MCP struct {
148 Name string `json:"name"`
149 MCP MCPConfig `json:"mcp"`
150}
151
152func (m MCPs) Sorted() []MCP {
153 sorted := make([]MCP, 0, len(m))
154 for k, v := range m {
155 sorted = append(sorted, MCP{
156 Name: k,
157 MCP: v,
158 })
159 }
160 slices.SortFunc(sorted, func(a, b MCP) int {
161 return strings.Compare(a.Name, b.Name)
162 })
163 return sorted
164}
165
166type LSPs map[string]LSPConfig
167
168type LSP struct {
169 Name string `json:"name"`
170 LSP LSPConfig `json:"lsp"`
171}
172
173func (l LSPs) Sorted() []LSP {
174 sorted := make([]LSP, 0, len(l))
175 for k, v := range l {
176 sorted = append(sorted, LSP{
177 Name: k,
178 LSP: v,
179 })
180 }
181 slices.SortFunc(sorted, func(a, b LSP) int {
182 return strings.Compare(a.Name, b.Name)
183 })
184 return sorted
185}
186
187func (m MCPConfig) ResolvedEnv() []string {
188 resolver := NewShellVariableResolver(env.New())
189 for e, v := range m.Env {
190 var err error
191 m.Env[e], err = resolver.ResolveValue(v)
192 if err != nil {
193 slog.Error("error resolving environment variable", "error", err, "variable", e, "value", v)
194 continue
195 }
196 }
197
198 env := make([]string, 0, len(m.Env))
199 for k, v := range m.Env {
200 env = append(env, fmt.Sprintf("%s=%s", k, v))
201 }
202 return env
203}
204
205func (m MCPConfig) ResolvedHeaders() map[string]string {
206 resolver := NewShellVariableResolver(env.New())
207 for e, v := range m.Headers {
208 var err error
209 m.Headers[e], err = resolver.ResolveValue(v)
210 if err != nil {
211 slog.Error("error resolving header variable", "error", err, "variable", e, "value", v)
212 continue
213 }
214 }
215 return m.Headers
216}
217
218type Agent struct {
219 ID string `json:"id,omitempty"`
220 Name string `json:"name,omitempty"`
221 Description string `json:"description,omitempty"`
222 // This is the id of the system prompt used by the agent
223 Disabled bool `json:"disabled,omitempty"`
224
225 Model SelectedModelType `json:"model" jsonschema:"required,description=The model type to use for this agent,enum=large,enum=small,default=large"`
226
227 // The available tools for the agent
228 // if this is nil, all tools are available
229 AllowedTools []string `json:"allowed_tools,omitempty"`
230
231 // this tells us which MCPs are available for this agent
232 // if this is empty all mcps are available
233 // the string array is the list of tools from the AllowedMCP the agent has available
234 // if the string array is nil, all tools from the AllowedMCP are available
235 AllowedMCP map[string][]string `json:"allowed_mcp,omitempty"`
236
237 // The list of LSPs that this agent can use
238 // if this is nil, all LSPs are available
239 AllowedLSP []string `json:"allowed_lsp,omitempty"`
240
241 // Overrides the context paths for this agent
242 ContextPaths []string `json:"context_paths,omitempty"`
243}
244
245// Config holds the configuration for crush.
246type Config struct {
247 Schema string `json:"$schema,omitempty"`
248
249 // We currently only support large/small as values here.
250 Models map[SelectedModelType]SelectedModel `json:"models,omitempty" jsonschema:"description=Model configurations for different model types,example={\"large\":{\"model\":\"gpt-4o\",\"provider\":\"openai\"}}"`
251
252 // The providers that are configured
253 Providers *csync.Map[string, ProviderConfig] `json:"providers,omitempty" jsonschema:"description=AI provider configurations"`
254
255 MCP MCPs `json:"mcp,omitempty" jsonschema:"description=Model Context Protocol server configurations"`
256
257 LSP LSPs `json:"lsp,omitempty" jsonschema:"description=Language Server Protocol configurations"`
258
259 Options *Options `json:"options,omitempty" jsonschema:"description=General application options"`
260
261 Permissions *Permissions `json:"permissions,omitempty" jsonschema:"description=Permission settings for tool usage"`
262
263 // Internal
264 workingDir string `json:"-"`
265 // TODO: most likely remove this concept when I come back to it
266 Agents map[string]Agent `json:"-"`
267 // TODO: find a better way to do this this should probably not be part of the config
268 resolver VariableResolver
269 dataConfigDir string `json:"-"`
270 knownProviders []catwalk.Provider `json:"-"`
271}
272
273func (c *Config) WorkingDir() string {
274 return c.workingDir
275}
276
277func (c *Config) EnabledProviders() []ProviderConfig {
278 var enabled []ProviderConfig
279 for p := range c.Providers.Seq() {
280 if !p.Disable {
281 enabled = append(enabled, p)
282 }
283 }
284 return enabled
285}
286
287// IsConfigured return true if at least one provider is configured
288func (c *Config) IsConfigured() bool {
289 return len(c.EnabledProviders()) > 0
290}
291
292func (c *Config) GetModel(provider, model string) *catwalk.Model {
293 if providerConfig, ok := c.Providers.Get(provider); ok {
294 for _, m := range providerConfig.Models {
295 if m.ID == model {
296 return &m
297 }
298 }
299 }
300 return nil
301}
302
303func (c *Config) GetProviderForModel(modelType SelectedModelType) *ProviderConfig {
304 model, ok := c.Models[modelType]
305 if !ok {
306 return nil
307 }
308 if providerConfig, ok := c.Providers.Get(model.Provider); ok {
309 return &providerConfig
310 }
311 return nil
312}
313
314func (c *Config) GetModelByType(modelType SelectedModelType) *catwalk.Model {
315 model, ok := c.Models[modelType]
316 if !ok {
317 return nil
318 }
319 return c.GetModel(model.Provider, model.Model)
320}
321
322func (c *Config) LargeModel() *catwalk.Model {
323 model, ok := c.Models[SelectedModelTypeLarge]
324 if !ok {
325 return nil
326 }
327 return c.GetModel(model.Provider, model.Model)
328}
329
330func (c *Config) SmallModel() *catwalk.Model {
331 model, ok := c.Models[SelectedModelTypeSmall]
332 if !ok {
333 return nil
334 }
335 return c.GetModel(model.Provider, model.Model)
336}
337
338func (c *Config) SetCompactMode(enabled bool) error {
339 if c.Options == nil {
340 c.Options = &Options{}
341 }
342 c.Options.TUI.CompactMode = enabled
343 return c.SetConfigField("options.tui.compact_mode", enabled)
344}
345
346func (c *Config) Resolve(key string) (string, error) {
347 if c.resolver == nil {
348 return "", fmt.Errorf("no variable resolver configured")
349 }
350 return c.resolver.ResolveValue(key)
351}
352
353func (c *Config) UpdatePreferredModel(modelType SelectedModelType, model SelectedModel) error {
354 c.Models[modelType] = model
355 if err := c.SetConfigField(fmt.Sprintf("models.%s", modelType), model); err != nil {
356 return fmt.Errorf("failed to update preferred model: %w", err)
357 }
358 return nil
359}
360
361func (c *Config) SetConfigField(key string, value any) error {
362 // read the data
363 data, err := os.ReadFile(c.dataConfigDir)
364 if err != nil {
365 if os.IsNotExist(err) {
366 data = []byte("{}")
367 } else {
368 return fmt.Errorf("failed to read config file: %w", err)
369 }
370 }
371
372 newValue, err := sjson.Set(string(data), key, value)
373 if err != nil {
374 return fmt.Errorf("failed to set config field %s: %w", key, err)
375 }
376 if err := os.WriteFile(c.dataConfigDir, []byte(newValue), 0o600); err != nil {
377 return fmt.Errorf("failed to write config file: %w", err)
378 }
379 return nil
380}
381
382func (c *Config) SetProviderAPIKey(providerID, apiKey string) error {
383 // First save to the config file
384 err := c.SetConfigField("providers."+providerID+".api_key", apiKey)
385 if err != nil {
386 return fmt.Errorf("failed to save API key to config file: %w", err)
387 }
388
389 providerConfig, exists := c.Providers.Get(providerID)
390 if exists {
391 providerConfig.APIKey = apiKey
392 c.Providers.Set(providerID, providerConfig)
393 return nil
394 }
395
396 var foundProvider *catwalk.Provider
397 for _, p := range c.knownProviders {
398 if string(p.ID) == providerID {
399 foundProvider = &p
400 break
401 }
402 }
403
404 if foundProvider != nil {
405 // Create new provider config based on known provider
406 providerConfig = ProviderConfig{
407 ID: providerID,
408 Name: foundProvider.Name,
409 BaseURL: foundProvider.APIEndpoint,
410 Type: foundProvider.Type,
411 APIKey: apiKey,
412 Disable: false,
413 ExtraHeaders: make(map[string]string),
414 ExtraParams: make(map[string]string),
415 Models: foundProvider.Models,
416 }
417 } else {
418 return fmt.Errorf("provider with ID %s not found in known providers", providerID)
419 }
420 // Store the updated provider config
421 c.Providers.Set(providerID, providerConfig)
422 return nil
423}
424
425func (c *Config) SetupAgents() {
426 agents := map[string]Agent{
427 "coder": {
428 ID: "coder",
429 Name: "Coder",
430 Description: "An agent that helps with executing coding tasks.",
431 Model: SelectedModelTypeLarge,
432 ContextPaths: c.Options.ContextPaths,
433 // All tools allowed
434 },
435 "task": {
436 ID: "task",
437 Name: "Task",
438 Description: "An agent that helps with searching for context and finding implementation details.",
439 Model: SelectedModelTypeLarge,
440 ContextPaths: c.Options.ContextPaths,
441 AllowedTools: []string{
442 "glob",
443 "grep",
444 "ls",
445 "sourcegraph",
446 "view",
447 },
448 // NO MCPs or LSPs by default
449 AllowedMCP: map[string][]string{},
450 AllowedLSP: []string{},
451 },
452 }
453 c.Agents = agents
454}
455
456func (c *Config) Resolver() VariableResolver {
457 return c.resolver
458}
459
460func (c *ProviderConfig) TestConnection(resolver VariableResolver) error {
461 testURL := ""
462 headers := make(map[string]string)
463 apiKey, _ := resolver.ResolveValue(c.APIKey)
464 switch c.Type {
465 case catwalk.TypeOpenAI:
466 baseURL, _ := resolver.ResolveValue(c.BaseURL)
467 if baseURL == "" {
468 baseURL = "https://api.openai.com/v1"
469 }
470 testURL = baseURL + "/models"
471 headers["Authorization"] = "Bearer " + apiKey
472 case catwalk.TypeAnthropic:
473 baseURL, _ := resolver.ResolveValue(c.BaseURL)
474 if baseURL == "" {
475 baseURL = "https://api.anthropic.com/v1"
476 }
477 testURL = baseURL + "/models"
478 headers["x-api-key"] = apiKey
479 headers["anthropic-version"] = "2023-06-01"
480 case catwalk.TypeGemini:
481 baseURL, _ := resolver.ResolveValue(c.BaseURL)
482 if baseURL == "" {
483 baseURL = "https://generativelanguage.googleapis.com"
484 }
485 testURL = baseURL + "/v1beta/models?key=" + url.QueryEscape(apiKey)
486 }
487 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
488 defer cancel()
489 client := &http.Client{}
490 req, err := http.NewRequestWithContext(ctx, "GET", testURL, nil)
491 if err != nil {
492 return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
493 }
494 for k, v := range headers {
495 req.Header.Set(k, v)
496 }
497 for k, v := range c.ExtraHeaders {
498 req.Header.Set(k, v)
499 }
500 b, err := client.Do(req)
501 if err != nil {
502 return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
503 }
504 if b.StatusCode != http.StatusOK {
505 return fmt.Errorf("failed to connect to provider %s: %s", c.ID, b.Status)
506 }
507 _ = b.Body.Close()
508 return nil
509}