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