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