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 defaultLogLevel = "info"
24)
25
26var defaultContextPaths = []string{
27 ".github/copilot-instructions.md",
28 ".cursorrules",
29 ".cursor/rules/",
30 "CLAUDE.md",
31 "CLAUDE.local.md",
32 "GEMINI.md",
33 "gemini.md",
34 "crush.md",
35 "crush.local.md",
36 "Crush.md",
37 "Crush.local.md",
38 "CRUSH.md",
39 "CRUSH.local.md",
40 "AGENTS.md",
41 "agents.md",
42 "Agents.md",
43}
44
45type SelectedModelType string
46
47const (
48 SelectedModelTypeLarge SelectedModelType = "large"
49 SelectedModelTypeSmall SelectedModelType = "small"
50)
51
52type SelectedModel struct {
53 // The model id as used by the provider API.
54 // Required.
55 Model string `json:"model" jsonschema:"required,description=The model ID as used by the provider API,example=gpt-4o"`
56 // The model provider, same as the key/id used in the providers config.
57 // Required.
58 Provider string `json:"provider" jsonschema:"required,description=The model provider ID that matches a key in the providers config,example=openai"`
59
60 // Only used by models that use the openai provider and need this set.
61 ReasoningEffort string `json:"reasoning_effort,omitempty" jsonschema:"description=Reasoning effort level for OpenAI models that support it,enum=low,enum=medium,enum=high"`
62
63 // Overrides the default model configuration.
64 MaxTokens int64 `json:"max_tokens,omitempty" jsonschema:"description=Maximum number of tokens for model responses,minimum=1,maximum=200000,example=4096"`
65
66 // Used by anthropic models that can reason to indicate if the model should think.
67 Think bool `json:"think,omitempty" jsonschema:"description=Enable thinking mode for Anthropic models that support reasoning"`
68}
69
70type ProviderConfig struct {
71 // The provider's id.
72 ID string `json:"id,omitempty" jsonschema:"description=Unique identifier for the provider,example=openai"`
73 // The provider's name, used for display purposes.
74 Name string `json:"name,omitempty" jsonschema:"description=Human-readable name for the provider,example=OpenAI"`
75 // The provider's API endpoint.
76 BaseURL string `json:"base_url,omitempty" jsonschema:"description=Base URL for the provider's API,format=uri,example=https://api.openai.com/v1"`
77 // The provider type, e.g. "openai", "anthropic", etc. if empty it defaults to openai.
78 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"`
79 // The provider's API key.
80 APIKey string `json:"api_key,omitempty" jsonschema:"description=API key for authentication with the provider,example=$OPENAI_API_KEY"`
81 // Marks the provider as disabled.
82 Disable bool `json:"disable,omitempty" jsonschema:"description=Whether this provider is disabled,default=false"`
83
84 // Custom system prompt prefix.
85 SystemPromptPrefix string `json:"system_prompt_prefix,omitempty" jsonschema:"description=Custom prefix to add to system prompts for this provider"`
86
87 // Extra headers to send with each request to the provider.
88 ExtraHeaders map[string]string `json:"extra_headers,omitempty" jsonschema:"description=Additional HTTP headers to send with requests"`
89 // Extra body
90 ExtraBody map[string]any `json:"extra_body,omitempty" jsonschema:"description=Additional fields to include in request bodies"`
91
92 // Used to pass extra parameters to the provider.
93 ExtraParams map[string]string `json:"-"`
94
95 // The provider models
96 Models []catwalk.Model `json:"models,omitempty" jsonschema:"description=List of models available from this provider"`
97}
98
99type MCPType string
100
101const (
102 MCPStdio MCPType = "stdio"
103 MCPSse MCPType = "sse"
104 MCPHttp MCPType = "http"
105)
106
107type MCPConfig struct {
108 Command string `json:"command,omitempty" jsonschema:"description=Command to execute for stdio MCP servers,example=npx"`
109 Env map[string]string `json:"env,omitempty" jsonschema:"description=Environment variables to set for the MCP server"`
110 Args []string `json:"args,omitempty" jsonschema:"description=Arguments to pass to the MCP server command"`
111 Type MCPType `json:"type" jsonschema:"required,description=Type of MCP connection,enum=stdio,enum=sse,enum=http,default=stdio"`
112 URL string `json:"url,omitempty" jsonschema:"description=URL for HTTP or SSE MCP servers,format=uri,example=http://localhost:3000/mcp"`
113 Disabled bool `json:"disabled,omitempty" jsonschema:"description=Whether this MCP server is disabled,default=false"`
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 Options any `json:"options,omitempty" jsonschema:"description=LSP server-specific configuration options"`
124}
125
126type TUIOptions struct {
127 CompactMode bool `json:"compact_mode,omitempty" jsonschema:"description=Enable compact mode for the TUI interface,default=false"`
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 // We currently only support large/small as values here.
248 Models map[SelectedModelType]SelectedModel `json:"models,omitempty" jsonschema:"description=Model configurations for different model types,example={\"large\":{\"model\":\"gpt-4o\",\"provider\":\"openai\"}}"`
249
250 // The providers that are configured
251 Providers *csync.Map[string, ProviderConfig] `json:"providers,omitempty" jsonschema:"description=AI provider configurations"`
252
253 MCP MCPs `json:"mcp,omitempty" jsonschema:"description=Model Context Protocol server configurations"`
254
255 LSP LSPs `json:"lsp,omitempty" jsonschema:"description=Language Server Protocol configurations"`
256
257 Options *Options `json:"options,omitempty" jsonschema:"description=General application options"`
258
259 Permissions *Permissions `json:"permissions,omitempty" jsonschema:"description=Permission settings for tool usage"`
260
261 // Internal
262 workingDir string `json:"-"`
263 // TODO: most likely remove this concept when I come back to it
264 Agents map[string]Agent `json:"-"`
265 // TODO: find a better way to do this this should probably not be part of the config
266 resolver VariableResolver
267 dataConfigDir string `json:"-"`
268 knownProviders []catwalk.Provider `json:"-"`
269}
270
271func (c *Config) WorkingDir() string {
272 return c.workingDir
273}
274
275func (c *Config) EnabledProviders() []ProviderConfig {
276 var enabled []ProviderConfig
277 for p := range c.Providers.Seq() {
278 if !p.Disable {
279 enabled = append(enabled, p)
280 }
281 }
282 return enabled
283}
284
285// IsConfigured return true if at least one provider is configured
286func (c *Config) IsConfigured() bool {
287 return len(c.EnabledProviders()) > 0
288}
289
290func (c *Config) GetModel(provider, model string) *catwalk.Model {
291 if providerConfig, ok := c.Providers.Get(provider); ok {
292 for _, m := range providerConfig.Models {
293 if m.ID == model {
294 return &m
295 }
296 }
297 }
298 return nil
299}
300
301func (c *Config) GetProviderForModel(modelType SelectedModelType) *ProviderConfig {
302 model, ok := c.Models[modelType]
303 if !ok {
304 return nil
305 }
306 if providerConfig, ok := c.Providers.Get(model.Provider); ok {
307 return &providerConfig
308 }
309 return nil
310}
311
312func (c *Config) GetModelByType(modelType SelectedModelType) *catwalk.Model {
313 model, ok := c.Models[modelType]
314 if !ok {
315 return nil
316 }
317 return c.GetModel(model.Provider, model.Model)
318}
319
320func (c *Config) LargeModel() *catwalk.Model {
321 model, ok := c.Models[SelectedModelTypeLarge]
322 if !ok {
323 return nil
324 }
325 return c.GetModel(model.Provider, model.Model)
326}
327
328func (c *Config) SmallModel() *catwalk.Model {
329 model, ok := c.Models[SelectedModelTypeSmall]
330 if !ok {
331 return nil
332 }
333 return c.GetModel(model.Provider, model.Model)
334}
335
336func (c *Config) SetCompactMode(enabled bool) error {
337 if c.Options == nil {
338 c.Options = &Options{}
339 }
340 c.Options.TUI.CompactMode = enabled
341 return c.SetConfigField("options.tui.compact_mode", enabled)
342}
343
344func (c *Config) Resolve(key string) (string, error) {
345 if c.resolver == nil {
346 return "", fmt.Errorf("no variable resolver configured")
347 }
348 return c.resolver.ResolveValue(key)
349}
350
351func (c *Config) UpdatePreferredModel(modelType SelectedModelType, model SelectedModel) error {
352 c.Models[modelType] = model
353 if err := c.SetConfigField(fmt.Sprintf("models.%s", modelType), model); err != nil {
354 return fmt.Errorf("failed to update preferred model: %w", err)
355 }
356 return nil
357}
358
359func (c *Config) SetConfigField(key string, value any) error {
360 // read the data
361 data, err := os.ReadFile(c.dataConfigDir)
362 if err != nil {
363 if os.IsNotExist(err) {
364 data = []byte("{}")
365 } else {
366 return fmt.Errorf("failed to read config file: %w", err)
367 }
368 }
369
370 newValue, err := sjson.Set(string(data), key, value)
371 if err != nil {
372 return fmt.Errorf("failed to set config field %s: %w", key, err)
373 }
374 if err := os.WriteFile(c.dataConfigDir, []byte(newValue), 0o644); err != nil {
375 return fmt.Errorf("failed to write config file: %w", err)
376 }
377 return nil
378}
379
380func (c *Config) SetProviderAPIKey(providerID, apiKey string) error {
381 // First save to the config file
382 err := c.SetConfigField("providers."+providerID+".api_key", apiKey)
383 if err != nil {
384 return fmt.Errorf("failed to save API key to config file: %w", err)
385 }
386
387 providerConfig, exists := c.Providers.Get(providerID)
388 if exists {
389 providerConfig.APIKey = apiKey
390 c.Providers.Set(providerID, providerConfig)
391 return nil
392 }
393
394 var foundProvider *catwalk.Provider
395 for _, p := range c.knownProviders {
396 if string(p.ID) == providerID {
397 foundProvider = &p
398 break
399 }
400 }
401
402 if foundProvider != nil {
403 // Create new provider config based on known provider
404 providerConfig = ProviderConfig{
405 ID: providerID,
406 Name: foundProvider.Name,
407 BaseURL: foundProvider.APIEndpoint,
408 Type: foundProvider.Type,
409 APIKey: apiKey,
410 Disable: false,
411 ExtraHeaders: make(map[string]string),
412 ExtraParams: make(map[string]string),
413 Models: foundProvider.Models,
414 }
415 } else {
416 return fmt.Errorf("provider with ID %s not found in known providers", providerID)
417 }
418 // Store the updated provider config
419 c.Providers.Set(providerID, providerConfig)
420 return nil
421}
422
423func (c *Config) SetupAgents() {
424 agents := map[string]Agent{
425 "coder": {
426 ID: "coder",
427 Name: "Coder",
428 Description: "An agent that helps with executing coding tasks.",
429 Model: SelectedModelTypeLarge,
430 ContextPaths: c.Options.ContextPaths,
431 // All tools allowed
432 },
433 "task": {
434 ID: "task",
435 Name: "Task",
436 Description: "An agent that helps with searching for context and finding implementation details.",
437 Model: SelectedModelTypeLarge,
438 ContextPaths: c.Options.ContextPaths,
439 AllowedTools: []string{
440 "glob",
441 "grep",
442 "ls",
443 "sourcegraph",
444 "view",
445 },
446 // NO MCPs or LSPs by default
447 AllowedMCP: map[string][]string{},
448 AllowedLSP: []string{},
449 },
450 }
451 c.Agents = agents
452}
453
454func (c *Config) Resolver() VariableResolver {
455 return c.resolver
456}
457
458func (c *ProviderConfig) TestConnection(resolver VariableResolver) error {
459 testURL := ""
460 headers := make(map[string]string)
461 apiKey, _ := resolver.ResolveValue(c.APIKey)
462 switch c.Type {
463 case catwalk.TypeOpenAI:
464 baseURL, _ := resolver.ResolveValue(c.BaseURL)
465 if baseURL == "" {
466 baseURL = "https://api.openai.com/v1"
467 }
468 testURL = baseURL + "/models"
469 headers["Authorization"] = "Bearer " + apiKey
470 case catwalk.TypeAnthropic:
471 baseURL, _ := resolver.ResolveValue(c.BaseURL)
472 if baseURL == "" {
473 baseURL = "https://api.anthropic.com/v1"
474 }
475 testURL = baseURL + "/models"
476 headers["x-api-key"] = apiKey
477 headers["anthropic-version"] = "2023-06-01"
478 case catwalk.TypeGemini:
479 baseURL, _ := resolver.ResolveValue(c.BaseURL)
480 if baseURL == "" {
481 baseURL = "https://generativelanguage.googleapis.com"
482 }
483 testURL = baseURL + "/v1beta/models?key=" + url.QueryEscape(apiKey)
484 }
485 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
486 defer cancel()
487 client := &http.Client{}
488 req, err := http.NewRequestWithContext(ctx, "GET", testURL, nil)
489 if err != nil {
490 return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
491 }
492 for k, v := range headers {
493 req.Header.Set(k, v)
494 }
495 for k, v := range c.ExtraHeaders {
496 req.Header.Set(k, v)
497 }
498 b, err := client.Do(req)
499 if err != nil {
500 return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
501 }
502 if b.StatusCode != http.StatusOK {
503 return fmt.Errorf("failed to connect to provider %s: %s", c.ID, b.Status)
504 }
505 _ = b.Body.Close()
506 return nil
507}