config.go

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