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