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