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	MaxMessagesInContext int         `json:"max_messages_in_context,omitempty" jsonschema:"description=Maximum number of messages to keep in context (sliding window),default=50,minimum=10,maximum=200"`
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	// We currently only support large/small as values here.
249	Models map[SelectedModelType]SelectedModel `json:"models,omitempty" jsonschema:"description=Model configurations for different model types,example={\"large\":{\"model\":\"gpt-4o\",\"provider\":\"openai\"}}"`
250
251	// The providers that are configured
252	Providers *csync.Map[string, ProviderConfig] `json:"providers,omitempty" jsonschema:"description=AI provider configurations"`
253
254	MCP MCPs `json:"mcp,omitempty" jsonschema:"description=Model Context Protocol server configurations"`
255
256	LSP LSPs `json:"lsp,omitempty" jsonschema:"description=Language Server Protocol configurations"`
257
258	Options *Options `json:"options,omitempty" jsonschema:"description=General application options"`
259
260	Permissions *Permissions `json:"permissions,omitempty" jsonschema:"description=Permission settings for tool usage"`
261
262	// Internal
263	workingDir string `json:"-"`
264	// TODO: most likely remove this concept when I come back to it
265	Agents map[string]Agent `json:"-"`
266	// TODO: find a better way to do this this should probably not be part of the config
267	resolver       VariableResolver
268	dataConfigDir  string             `json:"-"`
269	knownProviders []catwalk.Provider `json:"-"`
270}
271
272func (c *Config) WorkingDir() string {
273	return c.workingDir
274}
275
276func (c *Config) EnabledProviders() []ProviderConfig {
277	var enabled []ProviderConfig
278	for p := range c.Providers.Seq() {
279		if !p.Disable {
280			enabled = append(enabled, p)
281		}
282	}
283	return enabled
284}
285
286// IsConfigured  return true if at least one provider is configured
287func (c *Config) IsConfigured() bool {
288	return len(c.EnabledProviders()) > 0
289}
290
291func (c *Config) GetModel(provider, model string) *catwalk.Model {
292	if providerConfig, ok := c.Providers.Get(provider); ok {
293		for _, m := range providerConfig.Models {
294			if m.ID == model {
295				return &m
296			}
297		}
298	}
299	return nil
300}
301
302func (c *Config) GetProviderForModel(modelType SelectedModelType) *ProviderConfig {
303	model, ok := c.Models[modelType]
304	if !ok {
305		return nil
306	}
307	if providerConfig, ok := c.Providers.Get(model.Provider); ok {
308		return &providerConfig
309	}
310	return nil
311}
312
313func (c *Config) GetModelByType(modelType SelectedModelType) *catwalk.Model {
314	model, ok := c.Models[modelType]
315	if !ok {
316		return nil
317	}
318	return c.GetModel(model.Provider, model.Model)
319}
320
321func (c *Config) LargeModel() *catwalk.Model {
322	model, ok := c.Models[SelectedModelTypeLarge]
323	if !ok {
324		return nil
325	}
326	return c.GetModel(model.Provider, model.Model)
327}
328
329func (c *Config) SmallModel() *catwalk.Model {
330	model, ok := c.Models[SelectedModelTypeSmall]
331	if !ok {
332		return nil
333	}
334	return c.GetModel(model.Provider, model.Model)
335}
336
337func (c *Config) SetCompactMode(enabled bool) error {
338	if c.Options == nil {
339		c.Options = &Options{}
340	}
341	c.Options.TUI.CompactMode = enabled
342	return c.SetConfigField("options.tui.compact_mode", enabled)
343}
344
345func (c *Config) Resolve(key string) (string, error) {
346	if c.resolver == nil {
347		return "", fmt.Errorf("no variable resolver configured")
348	}
349	return c.resolver.ResolveValue(key)
350}
351
352func (c *Config) UpdatePreferredModel(modelType SelectedModelType, model SelectedModel) error {
353	c.Models[modelType] = model
354	if err := c.SetConfigField(fmt.Sprintf("models.%s", modelType), model); err != nil {
355		return fmt.Errorf("failed to update preferred model: %w", err)
356	}
357	return nil
358}
359
360func (c *Config) SetConfigField(key string, value any) error {
361	// read the data
362	data, err := os.ReadFile(c.dataConfigDir)
363	if err != nil {
364		if os.IsNotExist(err) {
365			data = []byte("{}")
366		} else {
367			return fmt.Errorf("failed to read config file: %w", err)
368		}
369	}
370
371	newValue, err := sjson.Set(string(data), key, value)
372	if err != nil {
373		return fmt.Errorf("failed to set config field %s: %w", key, err)
374	}
375	if err := os.WriteFile(c.dataConfigDir, []byte(newValue), 0o600); err != nil {
376		return fmt.Errorf("failed to write config file: %w", err)
377	}
378	return nil
379}
380
381func (c *Config) SetProviderAPIKey(providerID, apiKey string) error {
382	// First save to the config file
383	err := c.SetConfigField("providers."+providerID+".api_key", apiKey)
384	if err != nil {
385		return fmt.Errorf("failed to save API key to config file: %w", err)
386	}
387
388	providerConfig, exists := c.Providers.Get(providerID)
389	if exists {
390		providerConfig.APIKey = apiKey
391		c.Providers.Set(providerID, providerConfig)
392		return nil
393	}
394
395	var foundProvider *catwalk.Provider
396	for _, p := range c.knownProviders {
397		if string(p.ID) == providerID {
398			foundProvider = &p
399			break
400		}
401	}
402
403	if foundProvider != nil {
404		// Create new provider config based on known provider
405		providerConfig = ProviderConfig{
406			ID:           providerID,
407			Name:         foundProvider.Name,
408			BaseURL:      foundProvider.APIEndpoint,
409			Type:         foundProvider.Type,
410			APIKey:       apiKey,
411			Disable:      false,
412			ExtraHeaders: make(map[string]string),
413			ExtraParams:  make(map[string]string),
414			Models:       foundProvider.Models,
415		}
416	} else {
417		return fmt.Errorf("provider with ID %s not found in known providers", providerID)
418	}
419	// Store the updated provider config
420	c.Providers.Set(providerID, providerConfig)
421	return nil
422}
423
424func (c *Config) SetupAgents() {
425	agents := map[string]Agent{
426		"coder": {
427			ID:           "coder",
428			Name:         "Coder",
429			Description:  "An agent that helps with executing coding tasks.",
430			Model:        SelectedModelTypeLarge,
431			ContextPaths: c.Options.ContextPaths,
432			// All tools allowed
433		},
434		"task": {
435			ID:           "task",
436			Name:         "Task",
437			Description:  "An agent that helps with searching for context and finding implementation details.",
438			Model:        SelectedModelTypeLarge,
439			ContextPaths: c.Options.ContextPaths,
440			AllowedTools: []string{
441				"glob",
442				"grep",
443				"ls",
444				"sourcegraph",
445				"view",
446			},
447			// NO MCPs or LSPs by default
448			AllowedMCP: map[string][]string{},
449			AllowedLSP: []string{},
450		},
451	}
452	c.Agents = agents
453}
454
455func (c *Config) Resolver() VariableResolver {
456	return c.resolver
457}
458
459func (c *ProviderConfig) TestConnection(resolver VariableResolver) error {
460	testURL := ""
461	headers := make(map[string]string)
462	apiKey, _ := resolver.ResolveValue(c.APIKey)
463	switch c.Type {
464	case catwalk.TypeOpenAI:
465		baseURL, _ := resolver.ResolveValue(c.BaseURL)
466		if baseURL == "" {
467			baseURL = "https://api.openai.com/v1"
468		}
469		testURL = baseURL + "/models"
470		headers["Authorization"] = "Bearer " + apiKey
471	case catwalk.TypeAnthropic:
472		baseURL, _ := resolver.ResolveValue(c.BaseURL)
473		if baseURL == "" {
474			baseURL = "https://api.anthropic.com/v1"
475		}
476		testURL = baseURL + "/models"
477		headers["x-api-key"] = apiKey
478		headers["anthropic-version"] = "2023-06-01"
479	case catwalk.TypeGemini:
480		baseURL, _ := resolver.ResolveValue(c.BaseURL)
481		if baseURL == "" {
482			baseURL = "https://generativelanguage.googleapis.com"
483		}
484		testURL = baseURL + "/v1beta/models?key=" + url.QueryEscape(apiKey)
485	}
486	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
487	defer cancel()
488	client := &http.Client{}
489	req, err := http.NewRequestWithContext(ctx, "GET", testURL, nil)
490	if err != nil {
491		return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
492	}
493	for k, v := range headers {
494		req.Header.Set(k, v)
495	}
496	for k, v := range c.ExtraHeaders {
497		req.Header.Set(k, v)
498	}
499	b, err := client.Do(req)
500	if err != nil {
501		return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
502	}
503	if b.StatusCode != http.StatusOK {
504		return fmt.Errorf("failed to connect to provider %s: %s", c.ID, b.Status)
505	}
506	_ = b.Body.Close()
507	return nil
508}