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
114	// TODO: maybe make it possible to get the value from the env
115	Headers map[string]string `json:"headers,omitempty" jsonschema:"description=HTTP headers for HTTP/SSE MCP servers"`
116}
117
118type LSPConfig struct {
119	Disabled bool     `json:"enabled,omitempty" jsonschema:"description=Whether this LSP server is disabled,default=false"`
120	Command  string   `json:"command" jsonschema:"required,description=Command to execute for the LSP server,example=gopls"`
121	Args     []string `json:"args,omitempty" jsonschema:"description=Arguments to pass to the LSP server command"`
122	Options  any      `json:"options,omitempty" jsonschema:"description=LSP server-specific configuration options"`
123}
124
125type TUIOptions struct {
126	CompactMode bool `json:"compact_mode,omitempty" jsonschema:"description=Enable compact mode for the TUI interface,default=false"`
127	// Here we can add themes later or any TUI related options
128}
129
130type Permissions struct {
131	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
132	SkipRequests bool     `json:"-"`                                                                                                                              // Automatically accept all permissions (YOLO mode)
133}
134
135type Options struct {
136	ContextPaths         []string    `json:"context_paths,omitempty" jsonschema:"description=Paths to files containing context information for the AI,example=.cursorrules,example=CRUSH.md"`
137	TUI                  *TUIOptions `json:"tui,omitempty" jsonschema:"description=Terminal user interface options"`
138	Debug                bool        `json:"debug,omitempty" jsonschema:"description=Enable debug logging,default=false"`
139	DebugLSP             bool        `json:"debug_lsp,omitempty" jsonschema:"description=Enable debug logging for LSP servers,default=false"`
140	DisableAutoSummarize bool        `json:"disable_auto_summarize,omitempty" jsonschema:"description=Disable automatic conversation summarization,default=false"`
141	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
142}
143
144type MCPs map[string]MCPConfig
145
146type MCP struct {
147	Name string    `json:"name"`
148	MCP  MCPConfig `json:"mcp"`
149}
150
151func (m MCPs) Sorted() []MCP {
152	sorted := make([]MCP, 0, len(m))
153	for k, v := range m {
154		sorted = append(sorted, MCP{
155			Name: k,
156			MCP:  v,
157		})
158	}
159	slices.SortFunc(sorted, func(a, b MCP) int {
160		return strings.Compare(a.Name, b.Name)
161	})
162	return sorted
163}
164
165type LSPs map[string]LSPConfig
166
167type LSP struct {
168	Name string    `json:"name"`
169	LSP  LSPConfig `json:"lsp"`
170}
171
172func (l LSPs) Sorted() []LSP {
173	sorted := make([]LSP, 0, len(l))
174	for k, v := range l {
175		sorted = append(sorted, LSP{
176			Name: k,
177			LSP:  v,
178		})
179	}
180	slices.SortFunc(sorted, func(a, b LSP) int {
181		return strings.Compare(a.Name, b.Name)
182	})
183	return sorted
184}
185
186func (m MCPConfig) ResolvedEnv() []string {
187	resolver := NewShellVariableResolver(env.New())
188	for e, v := range m.Env {
189		var err error
190		m.Env[e], err = resolver.ResolveValue(v)
191		if err != nil {
192			slog.Error("error resolving environment variable", "error", err, "variable", e, "value", v)
193			continue
194		}
195	}
196
197	env := make([]string, 0, len(m.Env))
198	for k, v := range m.Env {
199		env = append(env, fmt.Sprintf("%s=%s", k, v))
200	}
201	return env
202}
203
204func (m MCPConfig) ResolvedHeaders() map[string]string {
205	resolver := NewShellVariableResolver(env.New())
206	for e, v := range m.Headers {
207		var err error
208		m.Headers[e], err = resolver.ResolveValue(v)
209		if err != nil {
210			slog.Error("error resolving header variable", "error", err, "variable", e, "value", v)
211			continue
212		}
213	}
214	return m.Headers
215}
216
217type Agent struct {
218	ID          string `json:"id,omitempty"`
219	Name        string `json:"name,omitempty"`
220	Description string `json:"description,omitempty"`
221	// This is the id of the system prompt used by the agent
222	Disabled bool `json:"disabled,omitempty"`
223
224	Model SelectedModelType `json:"model" jsonschema:"required,description=The model type to use for this agent,enum=large,enum=small,default=large"`
225
226	// The available tools for the agent
227	//  if this is nil, all tools are available
228	AllowedTools []string `json:"allowed_tools,omitempty"`
229
230	// this tells us which MCPs are available for this agent
231	//  if this is empty all mcps are available
232	//  the string array is the list of tools from the AllowedMCP the agent has available
233	//  if the string array is nil, all tools from the AllowedMCP are available
234	AllowedMCP map[string][]string `json:"allowed_mcp,omitempty"`
235
236	// The list of LSPs that this agent can use
237	//  if this is nil, all LSPs are available
238	AllowedLSP []string `json:"allowed_lsp,omitempty"`
239
240	// Overrides the context paths for this agent
241	ContextPaths []string `json:"context_paths,omitempty"`
242}
243
244// Config holds the configuration for crush.
245type Config struct {
246	Schema string `json:"$schema,omitempty"`
247
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}