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/tidwall/sjson"
 17)
 18
 19// OsShellResolver is a shell resolver that uses the current process environment
 20// variables.
 21//
 22// Deprecated: pass resolver explicitly instead.
 23var OsShellResolver = NewShellVariableResolver(os.Environ())
 24
 25const (
 26	defaultDataDirectory = ".crush"
 27)
 28
 29var defaultContextPaths = []string{
 30	".github/copilot-instructions.md",
 31	".cursorrules",
 32	".cursor/rules/",
 33	"CLAUDE.md",
 34	"CLAUDE.local.md",
 35	"GEMINI.md",
 36	"gemini.md",
 37	"crush.md",
 38	"crush.local.md",
 39	"Crush.md",
 40	"Crush.local.md",
 41	"CRUSH.md",
 42	"CRUSH.local.md",
 43	"AGENTS.md",
 44	"agents.md",
 45	"Agents.md",
 46}
 47
 48type SelectedModelType string
 49
 50const (
 51	SelectedModelTypeLarge SelectedModelType = "large"
 52	SelectedModelTypeSmall SelectedModelType = "small"
 53)
 54
 55type SelectedModel struct {
 56	// The model id as used by the provider API.
 57	// Required.
 58	Model string `json:"model" jsonschema:"required,description=The model ID as used by the provider API,example=gpt-4o"`
 59	// The model provider, same as the key/id used in the providers config.
 60	// Required.
 61	Provider string `json:"provider" jsonschema:"required,description=The model provider ID that matches a key in the providers config,example=openai"`
 62
 63	// Only used by models that use the openai provider and need this set.
 64	ReasoningEffort string `json:"reasoning_effort,omitempty" jsonschema:"description=Reasoning effort level for OpenAI models that support it,enum=low,enum=medium,enum=high"`
 65
 66	// Overrides the default model configuration.
 67	MaxTokens int64 `json:"max_tokens,omitempty" jsonschema:"description=Maximum number of tokens for model responses,minimum=1,maximum=200000,example=4096"`
 68
 69	// Used by anthropic models that can reason to indicate if the model should think.
 70	Think bool `json:"think,omitempty" jsonschema:"description=Enable thinking mode for Anthropic models that support reasoning"`
 71}
 72
 73type ProviderConfig struct {
 74	// The provider's id.
 75	ID string `json:"id,omitempty" jsonschema:"description=Unique identifier for the provider,example=openai"`
 76	// The provider's name, used for display purposes.
 77	Name string `json:"name,omitempty" jsonschema:"description=Human-readable name for the provider,example=OpenAI"`
 78	// The provider's API endpoint.
 79	BaseURL string `json:"base_url,omitempty" jsonschema:"description=Base URL for the provider's API,format=uri,example=https://api.openai.com/v1"`
 80	// The provider type, e.g. "openai", "anthropic", etc. if empty it defaults to openai.
 81	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"`
 82	// The provider's API key.
 83	APIKey string `json:"api_key,omitempty" jsonschema:"description=API key for authentication with the provider,example=$OPENAI_API_KEY"`
 84	// Marks the provider as disabled.
 85	Disable bool `json:"disable,omitempty" jsonschema:"description=Whether this provider is disabled,default=false"`
 86
 87	// Custom system prompt prefix.
 88	SystemPromptPrefix string `json:"system_prompt_prefix,omitempty" jsonschema:"description=Custom prefix to add to system prompts for this provider"`
 89
 90	// Extra headers to send with each request to the provider.
 91	ExtraHeaders map[string]string `json:"extra_headers,omitempty" jsonschema:"description=Additional HTTP headers to send with requests"`
 92	// Extra body
 93	ExtraBody map[string]any `json:"extra_body,omitempty" jsonschema:"description=Additional fields to include in request bodies"`
 94
 95	// Used to pass extra parameters to the provider.
 96	ExtraParams map[string]string `json:"-"`
 97
 98	// The provider models
 99	Models []catwalk.Model `json:"models,omitempty" jsonschema:"description=List of models available from this provider"`
100}
101
102type MCPType string
103
104const (
105	MCPStdio MCPType = "stdio"
106	MCPSse   MCPType = "sse"
107	MCPHttp  MCPType = "http"
108)
109
110type MCPConfig struct {
111	Command  string            `json:"command,omitempty" jsonschema:"description=Command to execute for stdio MCP servers,example=npx"`
112	Env      map[string]string `json:"env,omitempty" jsonschema:"description=Environment variables to set for the MCP server"`
113	Args     []string          `json:"args,omitempty" jsonschema:"description=Arguments to pass to the MCP server command"`
114	Type     MCPType           `json:"type" jsonschema:"required,description=Type of MCP connection,enum=stdio,enum=sse,enum=http,default=stdio"`
115	URL      string            `json:"url,omitempty" jsonschema:"description=URL for HTTP or SSE MCP servers,format=uri,example=http://localhost:3000/mcp"`
116	Disabled bool              `json:"disabled,omitempty" jsonschema:"description=Whether this MCP server is disabled,default=false"`
117	Timeout  int               `json:"timeout,omitempty" jsonschema:"description=Timeout in seconds for MCP server connections,default=15,example=30,example=60,example=120"`
118
119	// TODO: maybe make it possible to get the value from the env
120	Headers map[string]string `json:"headers,omitempty" jsonschema:"description=HTTP headers for HTTP/SSE MCP servers"`
121}
122
123type LSPConfig struct {
124	Disabled    bool              `json:"disabled,omitempty" jsonschema:"description=Whether this LSP server is disabled,default=false"`
125	Command     string            `json:"command,omitempty" jsonschema:"required,description=Command to execute for the LSP server,example=gopls"`
126	Args        []string          `json:"args,omitempty" jsonschema:"description=Arguments to pass to the LSP server command"`
127	Env         map[string]string `json:"env,omitempty" jsonschema:"description=Environment variables to set to the LSP server command"`
128	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"`
129	RootMarkers []string          `json:"root_markers,omitempty" jsonschema:"description=Files or directories that indicate the project root,example=go.mod,example=package.json,example=Cargo.toml"`
130	InitOptions map[string]any    `json:"init_options,omitempty" jsonschema:"description=Initialization options passed to the LSP server during initialize request"`
131	Options     map[string]any    `json:"options,omitempty" jsonschema:"description=LSP server-specific settings passed during initialization"`
132}
133
134type TUIOptions struct {
135	CompactMode bool   `json:"compact_mode,omitempty" jsonschema:"description=Enable compact mode for the TUI interface,default=false"`
136	DiffMode    string `json:"diff_mode,omitempty" jsonschema:"description=Diff mode for the TUI interface,enum=unified,enum=split"`
137	// Here we can add themes later or any TUI related options
138}
139
140type Permissions struct {
141	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
142	SkipRequests bool     `json:"-"`                                                                                                                              // Automatically accept all permissions (YOLO mode)
143}
144
145type Attribution struct {
146	CoAuthoredBy  bool `json:"co_authored_by,omitempty" jsonschema:"description=Add Co-Authored-By trailer to commit messages,default=true"`
147	GeneratedWith bool `json:"generated_with,omitempty" jsonschema:"description=Add Generated with Crush line to commit messages and issues and PRs,default=true"`
148}
149
150type Options struct {
151	ContextPaths              []string     `json:"context_paths,omitempty" jsonschema:"description=Paths to files containing context information for the AI,example=.cursorrules,example=CRUSH.md"`
152	TUI                       *TUIOptions  `json:"tui,omitempty" jsonschema:"description=Terminal user interface options"`
153	Debug                     bool         `json:"debug,omitempty" jsonschema:"description=Enable debug logging,default=false"`
154	DebugLSP                  bool         `json:"debug_lsp,omitempty" jsonschema:"description=Enable debug logging for LSP servers,default=false"`
155	DisableAutoSummarize      bool         `json:"disable_auto_summarize,omitempty" jsonschema:"description=Disable automatic conversation summarization,default=false"`
156	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
157	DisabledTools             []string     `json:"disabled_tools" jsonschema:"description=Tools to disable"`
158	DisableProviderAutoUpdate bool         `json:"disable_provider_auto_update,omitempty" jsonschema:"description=Disable providers auto-update,default=false"`
159	Attribution               *Attribution `json:"attribution,omitempty" jsonschema:"description=Attribution settings for generated content"`
160	DisableMetrics            bool         `json:"disable_metrics,omitempty" jsonschema:"description=Disable sending metrics,default=false"`
161}
162
163type MCPs map[string]MCPConfig
164
165type MCP struct {
166	Name string    `json:"name"`
167	MCP  MCPConfig `json:"mcp"`
168}
169
170func (m MCPs) Sorted() []MCP {
171	sorted := make([]MCP, 0, len(m))
172	for k, v := range m {
173		sorted = append(sorted, MCP{
174			Name: k,
175			MCP:  v,
176		})
177	}
178	slices.SortFunc(sorted, func(a, b MCP) int {
179		return strings.Compare(a.Name, b.Name)
180	})
181	return sorted
182}
183
184type LSPs map[string]LSPConfig
185
186type LSP struct {
187	Name string    `json:"name"`
188	LSP  LSPConfig `json:"lsp"`
189}
190
191func (l LSPs) Sorted() []LSP {
192	sorted := make([]LSP, 0, len(l))
193	for k, v := range l {
194		sorted = append(sorted, LSP{
195			Name: k,
196			LSP:  v,
197		})
198	}
199	slices.SortFunc(sorted, func(a, b LSP) int {
200		return strings.Compare(a.Name, b.Name)
201	})
202	return sorted
203}
204
205func (l LSPConfig) ResolvedEnv() []string {
206	return resolveEnvs(l.Env)
207}
208
209func (m MCPConfig) ResolvedEnv() []string {
210	return resolveEnvs(m.Env)
211}
212
213func (m MCPConfig) ResolvedHeaders() map[string]string {
214	resolver := NewShellVariableResolver(os.Environ())
215	for e, v := range m.Headers {
216		var err error
217		m.Headers[e], err = resolver.ResolveValue(v)
218		if err != nil {
219			slog.Error("error resolving header variable", "error", err, "variable", e, "value", v)
220			continue
221		}
222	}
223	return m.Headers
224}
225
226type Agent struct {
227	ID          string `json:"id,omitempty"`
228	Name        string `json:"name,omitempty"`
229	Description string `json:"description,omitempty"`
230	// This is the id of the system prompt used by the agent
231	Disabled bool `json:"disabled,omitempty"`
232
233	Model SelectedModelType `json:"model" jsonschema:"required,description=The model type to use for this agent,enum=large,enum=small,default=large"`
234
235	// The available tools for the agent
236	//  if this is nil, all tools are available
237	AllowedTools []string `json:"allowed_tools,omitempty"`
238
239	// this tells us which MCPs are available for this agent
240	//  if this is empty all mcps are available
241	//  the string array is the list of tools from the AllowedMCP the agent has available
242	//  if the string array is nil, all tools from the AllowedMCP are available
243	AllowedMCP map[string][]string `json:"allowed_mcp,omitempty"`
244
245	// The list of LSPs that this agent can use
246	//  if this is nil, all LSPs are available
247	AllowedLSP []string `json:"allowed_lsp,omitempty"`
248
249	// Overrides the context paths for this agent
250	ContextPaths []string `json:"context_paths,omitempty"`
251}
252
253// Config holds the configuration for crush.
254type Config struct {
255	Schema string `json:"$schema,omitempty"`
256
257	// We currently only support large/small as values here.
258	Models map[SelectedModelType]SelectedModel `json:"models,omitempty" jsonschema:"description=Model configurations for different model types,example={\"large\":{\"model\":\"gpt-4o\",\"provider\":\"openai\"}}"`
259
260	// The providers that are configured
261	Providers *csync.Map[string, ProviderConfig] `json:"providers,omitempty" jsonschema:"description=AI provider configurations"`
262
263	MCP MCPs `json:"mcp,omitempty" jsonschema:"description=Model Context Protocol server configurations"`
264
265	LSP LSPs `json:"lsp,omitempty" jsonschema:"description=Language Server Protocol configurations"`
266
267	Options *Options `json:"options,omitempty" jsonschema:"description=General application options"`
268
269	Permissions *Permissions `json:"permissions,omitempty" jsonschema:"description=Permission settings for tool usage"`
270
271	// Internal
272	workingDir string `json:"-"`
273	// TODO: most likely remove this concept when I come back to it
274	Agents map[string]Agent `json:"-"`
275	// TODO: find a better way to do this this should probably not be part of the config
276	dataConfigDir  string             `json:"-"`
277	knownProviders []catwalk.Provider `json:"-"`
278}
279
280func (c *Config) WorkingDir() string {
281	return c.workingDir
282}
283
284func (c *Config) EnabledProviders() []ProviderConfig {
285	var enabled []ProviderConfig
286	for p := range c.Providers.Seq() {
287		if !p.Disable {
288			enabled = append(enabled, p)
289		}
290	}
291	return enabled
292}
293
294// IsConfigured  return true if at least one provider is configured
295func (c *Config) IsConfigured() bool {
296	return len(c.EnabledProviders()) > 0
297}
298
299func (c *Config) GetModel(provider, model string) *catwalk.Model {
300	if providerConfig, ok := c.Providers.Get(provider); ok {
301		for _, m := range providerConfig.Models {
302			if m.ID == model {
303				return &m
304			}
305		}
306	}
307	return nil
308}
309
310func (c *Config) GetProviderForModel(modelType SelectedModelType) *ProviderConfig {
311	model, ok := c.Models[modelType]
312	if !ok {
313		return nil
314	}
315	if providerConfig, ok := c.Providers.Get(model.Provider); ok {
316		return &providerConfig
317	}
318	return nil
319}
320
321func (c *Config) GetModelByType(modelType SelectedModelType) *catwalk.Model {
322	model, ok := c.Models[modelType]
323	if !ok {
324		return nil
325	}
326	return c.GetModel(model.Provider, model.Model)
327}
328
329func (c *Config) LargeModel() *catwalk.Model {
330	model, ok := c.Models[SelectedModelTypeLarge]
331	if !ok {
332		return nil
333	}
334	return c.GetModel(model.Provider, model.Model)
335}
336
337func (c *Config) SmallModel() *catwalk.Model {
338	model, ok := c.Models[SelectedModelTypeSmall]
339	if !ok {
340		return nil
341	}
342	return c.GetModel(model.Provider, model.Model)
343}
344
345func (c *Config) SetCompactMode(enabled bool) error {
346	if c.Options == nil {
347		c.Options = &Options{}
348	}
349	c.Options.TUI.CompactMode = enabled
350	return c.SetConfigField("options.tui.compact_mode", enabled)
351}
352
353func (c *Config) UpdatePreferredModel(modelType SelectedModelType, model SelectedModel) error {
354	c.Models[modelType] = model
355	if err := c.SetConfigField(fmt.Sprintf("models.%s", modelType), model); err != nil {
356		return fmt.Errorf("failed to update preferred model: %w", err)
357	}
358	return nil
359}
360
361func (c *Config) SetConfigField(key string, value any) error {
362	// read the data
363	data, err := os.ReadFile(c.dataConfigDir)
364	if err != nil {
365		if os.IsNotExist(err) {
366			data = []byte("{}")
367		} else {
368			return fmt.Errorf("failed to read config file: %w", err)
369		}
370	}
371
372	newValue, err := sjson.Set(string(data), key, value)
373	if err != nil {
374		return fmt.Errorf("failed to set config field %s: %w", key, err)
375	}
376	if err := os.WriteFile(c.dataConfigDir, []byte(newValue), 0o600); err != nil {
377		return fmt.Errorf("failed to write config file: %w", err)
378	}
379	return nil
380}
381
382func (c *Config) SetProviderAPIKey(providerID, apiKey string) error {
383	// First save to the config file
384	err := c.SetConfigField("providers."+providerID+".api_key", apiKey)
385	if err != nil {
386		return fmt.Errorf("failed to save API key to config file: %w", err)
387	}
388
389	providerConfig, exists := c.Providers.Get(providerID)
390	if exists {
391		providerConfig.APIKey = apiKey
392		c.Providers.Set(providerID, providerConfig)
393		return nil
394	}
395
396	var foundProvider *catwalk.Provider
397	for _, p := range c.knownProviders {
398		if string(p.ID) == providerID {
399			foundProvider = &p
400			break
401		}
402	}
403
404	if foundProvider != nil {
405		// Create new provider config based on known provider
406		providerConfig = ProviderConfig{
407			ID:           providerID,
408			Name:         foundProvider.Name,
409			BaseURL:      foundProvider.APIEndpoint,
410			Type:         foundProvider.Type,
411			APIKey:       apiKey,
412			Disable:      false,
413			ExtraHeaders: make(map[string]string),
414			ExtraParams:  make(map[string]string),
415			Models:       foundProvider.Models,
416		}
417	} else {
418		return fmt.Errorf("provider with ID %s not found in known providers", providerID)
419	}
420	// Store the updated provider config
421	c.Providers.Set(providerID, providerConfig)
422	return nil
423}
424
425func allToolNames() []string {
426	return []string{
427		"agent",
428		"bash",
429		"download",
430		"edit",
431		"multiedit",
432		"fetch",
433		"glob",
434		"grep",
435		"ls",
436		"sourcegraph",
437		"view",
438		"write",
439	}
440}
441
442func resolveAllowedTools(allTools []string, disabledTools []string) []string {
443	if disabledTools == nil {
444		return allTools
445	}
446	// filter out disabled tools (exclude mode)
447	return filterSlice(allTools, disabledTools, false)
448}
449
450func resolveReadOnlyTools(tools []string) []string {
451	readOnlyTools := []string{"glob", "grep", "ls", "sourcegraph", "view"}
452	// filter to only include tools that are in allowedtools (include mode)
453	return filterSlice(tools, readOnlyTools, true)
454}
455
456func filterSlice(data []string, mask []string, include bool) []string {
457	filtered := []string{}
458	for _, s := range data {
459		// if include is true, we include items that ARE in the mask
460		// if include is false, we include items that are NOT in the mask
461		if include == slices.Contains(mask, s) {
462			filtered = append(filtered, s)
463		}
464	}
465	return filtered
466}
467
468func (c *Config) SetupAgents() {
469	allowedTools := resolveAllowedTools(allToolNames(), c.Options.DisabledTools)
470
471	agents := map[string]Agent{
472		"coder": {
473			ID:           "coder",
474			Name:         "Coder",
475			Description:  "An agent that helps with executing coding tasks.",
476			Model:        SelectedModelTypeLarge,
477			ContextPaths: c.Options.ContextPaths,
478			AllowedTools: allowedTools,
479		},
480		"task": {
481			ID:           "task",
482			Name:         "Task",
483			Description:  "An agent that helps with searching for context and finding implementation details.",
484			Model:        SelectedModelTypeLarge,
485			ContextPaths: c.Options.ContextPaths,
486			AllowedTools: resolveReadOnlyTools(allowedTools),
487			// NO MCPs or LSPs by default
488			AllowedMCP: map[string][]string{},
489			AllowedLSP: []string{},
490		},
491	}
492	c.Agents = agents
493}
494
495func (c *ProviderConfig) TestConnection(resolver VariableResolver) error {
496	testURL := ""
497	headers := make(map[string]string)
498	apiKey, _ := resolver.ResolveValue(c.APIKey)
499	switch c.Type {
500	case catwalk.TypeOpenAI:
501		baseURL, _ := resolver.ResolveValue(c.BaseURL)
502		if baseURL == "" {
503			baseURL = "https://api.openai.com/v1"
504		}
505		if c.ID == string(catwalk.InferenceProviderOpenRouter) {
506			testURL = baseURL + "/credits"
507		} else {
508			testURL = baseURL + "/models"
509		}
510		headers["Authorization"] = "Bearer " + apiKey
511	case catwalk.TypeAnthropic:
512		baseURL, _ := resolver.ResolveValue(c.BaseURL)
513		if baseURL == "" {
514			baseURL = "https://api.anthropic.com/v1"
515		}
516		testURL = baseURL + "/models"
517		headers["x-api-key"] = apiKey
518		headers["anthropic-version"] = "2023-06-01"
519	case catwalk.TypeGemini:
520		baseURL, _ := resolver.ResolveValue(c.BaseURL)
521		if baseURL == "" {
522			baseURL = "https://generativelanguage.googleapis.com"
523		}
524		testURL = baseURL + "/v1beta/models?key=" + url.QueryEscape(apiKey)
525	}
526	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
527	defer cancel()
528	client := &http.Client{}
529	req, err := http.NewRequestWithContext(ctx, "GET", testURL, nil)
530	if err != nil {
531		return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
532	}
533	for k, v := range headers {
534		req.Header.Set(k, v)
535	}
536	for k, v := range c.ExtraHeaders {
537		req.Header.Set(k, v)
538	}
539	b, err := client.Do(req)
540	if err != nil {
541		return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
542	}
543	if c.ID == string(catwalk.InferenceProviderZAI) {
544		if b.StatusCode == http.StatusUnauthorized {
545			// for z.ai just check if the http response is not 401
546			return fmt.Errorf("failed to connect to provider %s: %s", c.ID, b.Status)
547		}
548	} else {
549		if b.StatusCode != http.StatusOK {
550			return fmt.Errorf("failed to connect to provider %s: %s", c.ID, b.Status)
551		}
552	}
553	_ = b.Body.Close()
554	return nil
555}
556
557func resolveEnvs(envs map[string]string) []string {
558	resolver := NewShellVariableResolver(os.Environ())
559	for e, v := range envs {
560		var err error
561		envs[e], err = resolver.ResolveValue(v)
562		if err != nil {
563			slog.Error("error resolving environment variable", "error", err, "variable", e, "value", v)
564			continue
565		}
566	}
567
568	res := make([]string, 0, len(envs))
569	for k, v := range envs {
570		res = append(res, fmt.Sprintf("%s=%s", k, v))
571	}
572	return res
573}
574
575type contextKey struct{}
576
577var configKey = contextKey{}
578
579// WithContext returns a copy of the provided context with the given config.
580func WithContext(ctx context.Context, cfg *Config) context.Context {
581	return context.WithValue(ctx, configKey, cfg)
582}
583
584// FromContextConfig retrieves the config from the context, if present.
585func FromContext(ctx context.Context) (*Config, bool) {
586	cfg, ok := ctx.Value(configKey).(*Config)
587	return cfg, ok
588}