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