config.go

  1package config
  2
  3import (
  4	"cmp"
  5	"context"
  6	"fmt"
  7	"log/slog"
  8	"maps"
  9	"net/http"
 10	"net/url"
 11	"os"
 12	"path/filepath"
 13	"slices"
 14	"strings"
 15	"time"
 16
 17	"charm.land/catwalk/pkg/catwalk"
 18	hyperp "github.com/charmbracelet/crush/internal/agent/hyper"
 19	"github.com/charmbracelet/crush/internal/csync"
 20	"github.com/charmbracelet/crush/internal/env"
 21	"github.com/charmbracelet/crush/internal/oauth"
 22	"github.com/charmbracelet/crush/internal/oauth/copilot"
 23	"github.com/charmbracelet/crush/internal/oauth/hyper"
 24	"github.com/invopop/jsonschema"
 25	"github.com/tidwall/gjson"
 26	"github.com/tidwall/sjson"
 27)
 28
 29const (
 30	appName              = "crush"
 31	defaultDataDirectory = ".crush"
 32	defaultInitializeAs  = "AGENTS.md"
 33)
 34
 35var defaultContextPaths = []string{
 36	".github/copilot-instructions.md",
 37	".cursorrules",
 38	".cursor/rules/",
 39	"CLAUDE.md",
 40	"CLAUDE.local.md",
 41	"GEMINI.md",
 42	"gemini.md",
 43	"crush.md",
 44	"crush.local.md",
 45	"Crush.md",
 46	"Crush.local.md",
 47	"CRUSH.md",
 48	"CRUSH.local.md",
 49	"AGENTS.md",
 50	"agents.md",
 51	"Agents.md",
 52}
 53
 54type SelectedModelType string
 55
 56// String returns the string representation of the [SelectedModelType].
 57func (s SelectedModelType) String() string {
 58	return string(s)
 59}
 60
 61const (
 62	SelectedModelTypeLarge SelectedModelType = "large"
 63	SelectedModelTypeSmall SelectedModelType = "small"
 64)
 65
 66const (
 67	AgentCoder string = "coder"
 68	AgentTask  string = "task"
 69)
 70
 71type SelectedModel struct {
 72	// The model id as used by the provider API.
 73	// Required.
 74	Model string `json:"model" jsonschema:"required,description=The model ID as used by the provider API,example=gpt-4o"`
 75	// The model provider, same as the key/id used in the providers config.
 76	// Required.
 77	Provider string `json:"provider" jsonschema:"required,description=The model provider ID that matches a key in the providers config,example=openai"`
 78
 79	// Only used by models that use the openai provider and need this set.
 80	ReasoningEffort string `json:"reasoning_effort,omitempty" jsonschema:"description=Reasoning effort level for OpenAI models that support it,enum=low,enum=medium,enum=high"`
 81
 82	// Used by anthropic models that can reason to indicate if the model should think.
 83	Think bool `json:"think,omitempty" jsonschema:"description=Enable thinking mode for Anthropic models that support reasoning"`
 84
 85	// Overrides the default model configuration.
 86	MaxTokens        int64    `json:"max_tokens,omitempty" jsonschema:"description=Maximum number of tokens for model responses,maximum=200000,example=4096"`
 87	Temperature      *float64 `json:"temperature,omitempty" jsonschema:"description=Sampling temperature,minimum=0,maximum=1,example=0.7"`
 88	TopP             *float64 `json:"top_p,omitempty" jsonschema:"description=Top-p (nucleus) sampling parameter,minimum=0,maximum=1,example=0.9"`
 89	TopK             *int64   `json:"top_k,omitempty" jsonschema:"description=Top-k sampling parameter"`
 90	FrequencyPenalty *float64 `json:"frequency_penalty,omitempty" jsonschema:"description=Frequency penalty to reduce repetition"`
 91	PresencePenalty  *float64 `json:"presence_penalty,omitempty" jsonschema:"description=Presence penalty to increase topic diversity"`
 92
 93	// Override provider specific options.
 94	ProviderOptions map[string]any `json:"provider_options,omitempty" jsonschema:"description=Additional provider-specific options for the model"`
 95}
 96
 97type ProviderConfig struct {
 98	// The provider's id.
 99	ID string `json:"id,omitempty" jsonschema:"description=Unique identifier for the provider,example=openai"`
100	// The provider's name, used for display purposes.
101	Name string `json:"name,omitempty" jsonschema:"description=Human-readable name for the provider,example=OpenAI"`
102	// The provider's API endpoint.
103	BaseURL string `json:"base_url,omitempty" jsonschema:"description=Base URL for the provider's API,format=uri,example=https://api.openai.com/v1"`
104	// The provider type, e.g. "openai", "anthropic", etc. if empty it defaults to openai.
105	Type catwalk.Type `json:"type,omitempty" jsonschema:"description=Provider type that determines the API format,enum=openai,enum=openai-compat,enum=anthropic,enum=gemini,enum=azure,enum=vertexai,default=openai"`
106	// The provider's API key.
107	APIKey string `json:"api_key,omitempty" jsonschema:"description=API key for authentication with the provider,example=$OPENAI_API_KEY"`
108	// The original API key template before resolution (for re-resolution on auth errors).
109	APIKeyTemplate string `json:"-"`
110	// OAuthToken for providers that use OAuth2 authentication.
111	OAuthToken *oauth.Token `json:"oauth,omitempty" jsonschema:"description=OAuth2 token for authentication with the provider"`
112	// Marks the provider as disabled.
113	Disable bool `json:"disable,omitempty" jsonschema:"description=Whether this provider is disabled,default=false"`
114
115	// Custom system prompt prefix.
116	SystemPromptPrefix string `json:"system_prompt_prefix,omitempty" jsonschema:"description=Custom prefix to add to system prompts for this provider"`
117
118	// Extra headers to send with each request to the provider.
119	ExtraHeaders map[string]string `json:"extra_headers,omitempty" jsonschema:"description=Additional HTTP headers to send with requests"`
120	// Extra body
121	ExtraBody map[string]any `json:"extra_body,omitempty" jsonschema:"description=Additional fields to include in request bodies, only works with openai-compatible providers"`
122
123	ProviderOptions map[string]any `json:"provider_options,omitempty" jsonschema:"description=Additional provider-specific options for this provider"`
124
125	// Used to pass extra parameters to the provider.
126	ExtraParams map[string]string `json:"-"`
127
128	// The provider models
129	Models []catwalk.Model `json:"models,omitempty" jsonschema:"description=List of models available from this provider"`
130}
131
132// ToProvider converts the [ProviderConfig] to a [catwalk.Provider].
133func (pc *ProviderConfig) ToProvider() catwalk.Provider {
134	// Convert config provider to provider.Provider format
135	provider := catwalk.Provider{
136		Name:   pc.Name,
137		ID:     catwalk.InferenceProvider(pc.ID),
138		Models: make([]catwalk.Model, len(pc.Models)),
139	}
140
141	// Convert models
142	for i, model := range pc.Models {
143		provider.Models[i] = catwalk.Model{
144			ID:                     model.ID,
145			Name:                   model.Name,
146			CostPer1MIn:            model.CostPer1MIn,
147			CostPer1MOut:           model.CostPer1MOut,
148			CostPer1MInCached:      model.CostPer1MInCached,
149			CostPer1MOutCached:     model.CostPer1MOutCached,
150			ContextWindow:          model.ContextWindow,
151			DefaultMaxTokens:       model.DefaultMaxTokens,
152			CanReason:              model.CanReason,
153			ReasoningLevels:        model.ReasoningLevels,
154			DefaultReasoningEffort: model.DefaultReasoningEffort,
155			SupportsImages:         model.SupportsImages,
156		}
157	}
158
159	return provider
160}
161
162func (pc *ProviderConfig) SetupGitHubCopilot() {
163	maps.Copy(pc.ExtraHeaders, copilot.Headers())
164}
165
166type MCPType string
167
168const (
169	MCPStdio MCPType = "stdio"
170	MCPSSE   MCPType = "sse"
171	MCPHttp  MCPType = "http"
172)
173
174type MCPConfig struct {
175	Command       string            `json:"command,omitempty" jsonschema:"description=Command to execute for stdio MCP servers,example=npx"`
176	Env           map[string]string `json:"env,omitempty" jsonschema:"description=Environment variables to set for the MCP server"`
177	Args          []string          `json:"args,omitempty" jsonschema:"description=Arguments to pass to the MCP server command"`
178	Type          MCPType           `json:"type" jsonschema:"required,description=Type of MCP connection,enum=stdio,enum=sse,enum=http,default=stdio"`
179	URL           string            `json:"url,omitempty" jsonschema:"description=URL for HTTP or SSE MCP servers,format=uri,example=http://localhost:3000/mcp"`
180	Disabled      bool              `json:"disabled,omitempty" jsonschema:"description=Whether this MCP server is disabled,default=false"`
181	DisabledTools []string          `json:"disabled_tools,omitempty" jsonschema:"description=List of tools from this MCP server to disable,example=get-library-doc"`
182	Timeout       int               `json:"timeout,omitempty" jsonschema:"description=Timeout in seconds for MCP server connections,default=15,example=30,example=60,example=120"`
183
184	// TODO: maybe make it possible to get the value from the env
185	Headers map[string]string `json:"headers,omitempty" jsonschema:"description=HTTP headers for HTTP/SSE MCP servers"`
186}
187
188type LSPConfig struct {
189	Disabled    bool              `json:"disabled,omitempty" jsonschema:"description=Whether this LSP server is disabled,default=false"`
190	Command     string            `json:"command,omitempty" jsonschema:"description=Command to execute for the LSP server,example=gopls"`
191	Args        []string          `json:"args,omitempty" jsonschema:"description=Arguments to pass to the LSP server command"`
192	Env         map[string]string `json:"env,omitempty" jsonschema:"description=Environment variables to set to the LSP server command"`
193	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"`
194	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"`
195	InitOptions map[string]any    `json:"init_options,omitempty" jsonschema:"description=Initialization options passed to the LSP server during initialize request"`
196	Options     map[string]any    `json:"options,omitempty" jsonschema:"description=LSP server-specific settings passed during initialization"`
197	Timeout     int               `json:"timeout,omitempty" jsonschema:"description=Timeout in seconds for LSP server initialization,default=30,example=60,example=120"`
198}
199
200type TUIOptions struct {
201	CompactMode bool   `json:"compact_mode,omitempty" jsonschema:"description=Enable compact mode for the TUI interface,default=false"`
202	DiffMode    string `json:"diff_mode,omitempty" jsonschema:"description=Diff mode for the TUI interface,enum=unified,enum=split"`
203	// Here we can add themes later or any TUI related options
204	//
205
206	Completions Completions `json:"completions,omitzero" jsonschema:"description=Completions UI options"`
207	Transparent *bool       `json:"transparent,omitempty" jsonschema:"description=Enable transparent background for the TUI interface,default=false"`
208}
209
210// Completions defines options for the completions UI.
211type Completions struct {
212	MaxDepth *int `json:"max_depth,omitempty" jsonschema:"description=Maximum depth for the ls tool,default=0,example=10"`
213	MaxItems *int `json:"max_items,omitempty" jsonschema:"description=Maximum number of items to return for the ls tool,default=1000,example=100"`
214}
215
216func (c Completions) Limits() (depth, items int) {
217	return ptrValOr(c.MaxDepth, 0), ptrValOr(c.MaxItems, 0)
218}
219
220type Permissions struct {
221	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
222	SkipRequests bool     `json:"-"`                                                                                                                              // Automatically accept all permissions (YOLO mode)
223}
224
225type TrailerStyle string
226
227const (
228	TrailerStyleNone         TrailerStyle = "none"
229	TrailerStyleCoAuthoredBy TrailerStyle = "co-authored-by"
230	TrailerStyleAssistedBy   TrailerStyle = "assisted-by"
231)
232
233type Attribution struct {
234	TrailerStyle  TrailerStyle `json:"trailer_style,omitempty" jsonschema:"description=Style of attribution trailer to add to commits,enum=none,enum=co-authored-by,enum=assisted-by,default=assisted-by"`
235	CoAuthoredBy  *bool        `json:"co_authored_by,omitempty" jsonschema:"description=Deprecated: use trailer_style instead"`
236	GeneratedWith bool         `json:"generated_with,omitempty" jsonschema:"description=Add Generated with Crush line to commit messages and issues and PRs,default=true"`
237}
238
239// JSONSchemaExtend marks the co_authored_by field as deprecated in the schema.
240func (Attribution) JSONSchemaExtend(schema *jsonschema.Schema) {
241	if schema.Properties != nil {
242		if prop, ok := schema.Properties.Get("co_authored_by"); ok {
243			prop.Deprecated = true
244		}
245	}
246}
247
248type Options struct {
249	ContextPaths              []string     `json:"context_paths,omitempty" jsonschema:"description=Paths to files containing context information for the AI,example=.cursorrules,example=CRUSH.md"`
250	SkillsPaths               []string     `json:"skills_paths,omitempty" jsonschema:"description=Paths to directories containing Agent Skills (folders with SKILL.md files),example=~/.config/crush/skills,example=./skills"`
251	TUI                       *TUIOptions  `json:"tui,omitempty" jsonschema:"description=Terminal user interface options"`
252	Debug                     bool         `json:"debug,omitempty" jsonschema:"description=Enable debug logging,default=false"`
253	DebugLSP                  bool         `json:"debug_lsp,omitempty" jsonschema:"description=Enable debug logging for LSP servers,default=false"`
254	DisableAutoSummarize      bool         `json:"disable_auto_summarize,omitempty" jsonschema:"description=Disable automatic conversation summarization,default=false"`
255	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
256	DisabledTools             []string     `json:"disabled_tools,omitempty" jsonschema:"description=List of built-in tools to disable and hide from the agent,example=bash,example=sourcegraph"`
257	DisableProviderAutoUpdate bool         `json:"disable_provider_auto_update,omitempty" jsonschema:"description=Disable providers auto-update,default=false"`
258	DisableDefaultProviders   bool         `json:"disable_default_providers,omitempty" jsonschema:"description=Ignore all default/embedded providers. When enabled, providers must be fully specified in the config file with base_url, models, and api_key - no merging with defaults occurs,default=false"`
259	Attribution               *Attribution `json:"attribution,omitempty" jsonschema:"description=Attribution settings for generated content"`
260	DisableMetrics            bool         `json:"disable_metrics,omitempty" jsonschema:"description=Disable sending metrics,default=false"`
261	InitializeAs              string       `json:"initialize_as,omitempty" jsonschema:"description=Name of the context file to create/update during project initialization,default=AGENTS.md,example=AGENTS.md,example=CRUSH.md,example=CLAUDE.md,example=docs/LLMs.md"`
262	AutoLSP                   *bool        `json:"auto_lsp,omitempty" jsonschema:"description=Automatically setup LSPs based on root markers,default=true"`
263	Progress                  *bool        `json:"progress,omitempty" jsonschema:"description=Show indeterminate progress updates during long operations,default=true"`
264	DisableNotifications      bool         `json:"disable_notifications,omitempty" jsonschema:"description=Disable desktop notifications,default=false"`
265}
266
267type MCPs map[string]MCPConfig
268
269type MCP struct {
270	Name string    `json:"name"`
271	MCP  MCPConfig `json:"mcp"`
272}
273
274func (m MCPs) Sorted() []MCP {
275	sorted := make([]MCP, 0, len(m))
276	for k, v := range m {
277		sorted = append(sorted, MCP{
278			Name: k,
279			MCP:  v,
280		})
281	}
282	slices.SortFunc(sorted, func(a, b MCP) int {
283		return strings.Compare(a.Name, b.Name)
284	})
285	return sorted
286}
287
288type LSPs map[string]LSPConfig
289
290type LSP struct {
291	Name string    `json:"name"`
292	LSP  LSPConfig `json:"lsp"`
293}
294
295func (l LSPs) Sorted() []LSP {
296	sorted := make([]LSP, 0, len(l))
297	for k, v := range l {
298		sorted = append(sorted, LSP{
299			Name: k,
300			LSP:  v,
301		})
302	}
303	slices.SortFunc(sorted, func(a, b LSP) int {
304		return strings.Compare(a.Name, b.Name)
305	})
306	return sorted
307}
308
309func (l LSPConfig) ResolvedEnv() []string {
310	return resolveEnvs(l.Env)
311}
312
313func (m MCPConfig) ResolvedEnv() []string {
314	return resolveEnvs(m.Env)
315}
316
317func (m MCPConfig) ResolvedHeaders() map[string]string {
318	resolver := NewShellVariableResolver(env.New())
319	for e, v := range m.Headers {
320		var err error
321		m.Headers[e], err = resolver.ResolveValue(v)
322		if err != nil {
323			slog.Error("Error resolving header variable", "error", err, "variable", e, "value", v)
324			continue
325		}
326	}
327	return m.Headers
328}
329
330type Agent struct {
331	ID          string `json:"id,omitempty"`
332	Name        string `json:"name,omitempty"`
333	Description string `json:"description,omitempty"`
334	// This is the id of the system prompt used by the agent
335	Disabled bool `json:"disabled,omitempty"`
336
337	Model SelectedModelType `json:"model" jsonschema:"required,description=The model type to use for this agent,enum=large,enum=small,default=large"`
338
339	// The available tools for the agent
340	//  if this is nil, all tools are available
341	AllowedTools []string `json:"allowed_tools,omitempty"`
342
343	// this tells us which MCPs are available for this agent
344	//  if this is empty all mcps are available
345	//  the string array is the list of tools from the AllowedMCP the agent has available
346	//  if the string array is nil, all tools from the AllowedMCP are available
347	AllowedMCP map[string][]string `json:"allowed_mcp,omitempty"`
348
349	// Overrides the context paths for this agent
350	ContextPaths []string `json:"context_paths,omitempty"`
351}
352
353type Tools struct {
354	Ls   ToolLs   `json:"ls,omitzero"`
355	Grep ToolGrep `json:"grep,omitzero"`
356}
357
358type ToolLs struct {
359	MaxDepth *int `json:"max_depth,omitempty" jsonschema:"description=Maximum depth for the ls tool,default=0,example=10"`
360	MaxItems *int `json:"max_items,omitempty" jsonschema:"description=Maximum number of items to return for the ls tool,default=1000,example=100"`
361}
362
363// Limits returns the user-defined max-depth and max-items, or their defaults.
364func (t ToolLs) Limits() (depth, items int) {
365	return ptrValOr(t.MaxDepth, 0), ptrValOr(t.MaxItems, 0)
366}
367
368type ToolGrep struct {
369	Timeout *time.Duration `json:"timeout,omitempty" jsonschema:"description=Timeout for the grep tool call,default=5s,example=10s"`
370}
371
372// GetTimeout returns the user-defined timeout or the default.
373func (t ToolGrep) GetTimeout() time.Duration {
374	return ptrValOr(t.Timeout, 5*time.Second)
375}
376
377// Config holds the configuration for crush.
378type Config struct {
379	Schema string `json:"$schema,omitempty"`
380
381	// We currently only support large/small as values here.
382	Models map[SelectedModelType]SelectedModel `json:"models,omitempty" jsonschema:"description=Model configurations for different model types,example={\"large\":{\"model\":\"gpt-4o\",\"provider\":\"openai\"}}"`
383
384	// Recently used models stored in the data directory config.
385	RecentModels map[SelectedModelType][]SelectedModel `json:"recent_models,omitempty" jsonschema:"-"`
386
387	// The providers that are configured
388	Providers *csync.Map[string, ProviderConfig] `json:"providers,omitempty" jsonschema:"description=AI provider configurations"`
389
390	MCP MCPs `json:"mcp,omitempty" jsonschema:"description=Model Context Protocol server configurations"`
391
392	LSP LSPs `json:"lsp,omitempty" jsonschema:"description=Language Server Protocol configurations"`
393
394	Options *Options `json:"options,omitempty" jsonschema:"description=General application options"`
395
396	Permissions *Permissions `json:"permissions,omitempty" jsonschema:"description=Permission settings for tool usage"`
397
398	Tools Tools `json:"tools,omitzero" jsonschema:"description=Tool configurations"`
399
400	Agents map[string]Agent `json:"-"`
401
402	// Internal
403	workingDir string `json:"-"`
404	// TODO: find a better way to do this this should probably not be part of the config
405	resolver       VariableResolver
406	dataConfigDir  string             `json:"-"`
407	knownProviders []catwalk.Provider `json:"-"`
408}
409
410func (c *Config) WorkingDir() string {
411	return c.workingDir
412}
413
414func (c *Config) EnabledProviders() []ProviderConfig {
415	var enabled []ProviderConfig
416	for p := range c.Providers.Seq() {
417		if !p.Disable {
418			enabled = append(enabled, p)
419		}
420	}
421	return enabled
422}
423
424// IsConfigured  return true if at least one provider is configured
425func (c *Config) IsConfigured() bool {
426	return len(c.EnabledProviders()) > 0
427}
428
429func (c *Config) GetModel(provider, model string) *catwalk.Model {
430	if providerConfig, ok := c.Providers.Get(provider); ok {
431		for _, m := range providerConfig.Models {
432			if m.ID == model {
433				return &m
434			}
435		}
436	}
437	return nil
438}
439
440func (c *Config) GetProviderForModel(modelType SelectedModelType) *ProviderConfig {
441	model, ok := c.Models[modelType]
442	if !ok {
443		return nil
444	}
445	if providerConfig, ok := c.Providers.Get(model.Provider); ok {
446		return &providerConfig
447	}
448	return nil
449}
450
451func (c *Config) GetModelByType(modelType SelectedModelType) *catwalk.Model {
452	model, ok := c.Models[modelType]
453	if !ok {
454		return nil
455	}
456	return c.GetModel(model.Provider, model.Model)
457}
458
459func (c *Config) LargeModel() *catwalk.Model {
460	model, ok := c.Models[SelectedModelTypeLarge]
461	if !ok {
462		return nil
463	}
464	return c.GetModel(model.Provider, model.Model)
465}
466
467func (c *Config) SmallModel() *catwalk.Model {
468	model, ok := c.Models[SelectedModelTypeSmall]
469	if !ok {
470		return nil
471	}
472	return c.GetModel(model.Provider, model.Model)
473}
474
475func (c *Config) SetCompactMode(enabled bool) error {
476	if c.Options == nil {
477		c.Options = &Options{}
478	}
479	c.Options.TUI.CompactMode = enabled
480	return c.SetConfigField("options.tui.compact_mode", enabled)
481}
482
483func (c *Config) Resolve(key string) (string, error) {
484	if c.resolver == nil {
485		return "", fmt.Errorf("no variable resolver configured")
486	}
487	return c.resolver.ResolveValue(key)
488}
489
490func (c *Config) UpdatePreferredModel(modelType SelectedModelType, model SelectedModel) error {
491	c.Models[modelType] = model
492	if err := c.SetConfigField(fmt.Sprintf("models.%s", modelType), model); err != nil {
493		return fmt.Errorf("failed to update preferred model: %w", err)
494	}
495	if err := c.recordRecentModel(modelType, model); err != nil {
496		return err
497	}
498	return nil
499}
500
501func (c *Config) HasConfigField(key string) bool {
502	data, err := os.ReadFile(c.dataConfigDir)
503	if err != nil {
504		return false
505	}
506	return gjson.Get(string(data), key).Exists()
507}
508
509func (c *Config) SetConfigField(key string, value any) error {
510	data, err := os.ReadFile(c.dataConfigDir)
511	if err != nil {
512		if os.IsNotExist(err) {
513			data = []byte("{}")
514		} else {
515			return fmt.Errorf("failed to read config file: %w", err)
516		}
517	}
518
519	newValue, err := sjson.Set(string(data), key, value)
520	if err != nil {
521		return fmt.Errorf("failed to set config field %s: %w", key, err)
522	}
523	if err := os.MkdirAll(filepath.Dir(c.dataConfigDir), 0o755); err != nil {
524		return fmt.Errorf("failed to create config directory %q: %w", c.dataConfigDir, err)
525	}
526	if err := os.WriteFile(c.dataConfigDir, []byte(newValue), 0o600); err != nil {
527		return fmt.Errorf("failed to write config file: %w", err)
528	}
529	return nil
530}
531
532func (c *Config) RemoveConfigField(key string) error {
533	data, err := os.ReadFile(c.dataConfigDir)
534	if err != nil {
535		return fmt.Errorf("failed to read config file: %w", err)
536	}
537
538	newValue, err := sjson.Delete(string(data), key)
539	if err != nil {
540		return fmt.Errorf("failed to delete config field %s: %w", key, err)
541	}
542	if err := os.MkdirAll(filepath.Dir(c.dataConfigDir), 0o755); err != nil {
543		return fmt.Errorf("failed to create config directory %q: %w", c.dataConfigDir, err)
544	}
545	if err := os.WriteFile(c.dataConfigDir, []byte(newValue), 0o600); err != nil {
546		return fmt.Errorf("failed to write config file: %w", err)
547	}
548	return nil
549}
550
551// RefreshOAuthToken refreshes the OAuth token for the given provider.
552func (c *Config) RefreshOAuthToken(ctx context.Context, providerID string) error {
553	providerConfig, exists := c.Providers.Get(providerID)
554	if !exists {
555		return fmt.Errorf("provider %s not found", providerID)
556	}
557
558	if providerConfig.OAuthToken == nil {
559		return fmt.Errorf("provider %s does not have an OAuth token", providerID)
560	}
561
562	var newToken *oauth.Token
563	var refreshErr error
564	switch providerID {
565	case string(catwalk.InferenceProviderCopilot):
566		newToken, refreshErr = copilot.RefreshToken(ctx, providerConfig.OAuthToken.RefreshToken)
567	case hyperp.Name:
568		newToken, refreshErr = hyper.ExchangeToken(ctx, providerConfig.OAuthToken.RefreshToken)
569	default:
570		return fmt.Errorf("OAuth refresh not supported for provider %s", providerID)
571	}
572	if refreshErr != nil {
573		return fmt.Errorf("failed to refresh OAuth token for provider %s: %w", providerID, refreshErr)
574	}
575
576	slog.Info("Successfully refreshed OAuth token", "provider", providerID)
577	providerConfig.OAuthToken = newToken
578	providerConfig.APIKey = newToken.AccessToken
579
580	switch providerID {
581	case string(catwalk.InferenceProviderCopilot):
582		providerConfig.SetupGitHubCopilot()
583	}
584
585	c.Providers.Set(providerID, providerConfig)
586
587	if err := cmp.Or(
588		c.SetConfigField(fmt.Sprintf("providers.%s.api_key", providerID), newToken.AccessToken),
589		c.SetConfigField(fmt.Sprintf("providers.%s.oauth", providerID), newToken),
590	); err != nil {
591		return fmt.Errorf("failed to persist refreshed token: %w", err)
592	}
593
594	return nil
595}
596
597func (c *Config) SetProviderAPIKey(providerID string, apiKey any) error {
598	var providerConfig ProviderConfig
599	var exists bool
600	var setKeyOrToken func()
601
602	switch v := apiKey.(type) {
603	case string:
604		if err := c.SetConfigField(fmt.Sprintf("providers.%s.api_key", providerID), v); err != nil {
605			return fmt.Errorf("failed to save api key to config file: %w", err)
606		}
607		setKeyOrToken = func() { providerConfig.APIKey = v }
608	case *oauth.Token:
609		if err := cmp.Or(
610			c.SetConfigField(fmt.Sprintf("providers.%s.api_key", providerID), v.AccessToken),
611			c.SetConfigField(fmt.Sprintf("providers.%s.oauth", providerID), v),
612		); err != nil {
613			return err
614		}
615		setKeyOrToken = func() {
616			providerConfig.APIKey = v.AccessToken
617			providerConfig.OAuthToken = v
618			switch providerID {
619			case string(catwalk.InferenceProviderCopilot):
620				providerConfig.SetupGitHubCopilot()
621			}
622		}
623	}
624
625	providerConfig, exists = c.Providers.Get(providerID)
626	if exists {
627		setKeyOrToken()
628		c.Providers.Set(providerID, providerConfig)
629		return nil
630	}
631
632	var foundProvider *catwalk.Provider
633	for _, p := range c.knownProviders {
634		if string(p.ID) == providerID {
635			foundProvider = &p
636			break
637		}
638	}
639
640	if foundProvider != nil {
641		// Create new provider config based on known provider
642		providerConfig = ProviderConfig{
643			ID:           providerID,
644			Name:         foundProvider.Name,
645			BaseURL:      foundProvider.APIEndpoint,
646			Type:         foundProvider.Type,
647			Disable:      false,
648			ExtraHeaders: make(map[string]string),
649			ExtraParams:  make(map[string]string),
650			Models:       foundProvider.Models,
651		}
652		setKeyOrToken()
653	} else {
654		return fmt.Errorf("provider with ID %s not found in known providers", providerID)
655	}
656	// Store the updated provider config
657	c.Providers.Set(providerID, providerConfig)
658	return nil
659}
660
661const maxRecentModelsPerType = 5
662
663func (c *Config) recordRecentModel(modelType SelectedModelType, model SelectedModel) error {
664	if model.Provider == "" || model.Model == "" {
665		return nil
666	}
667
668	if c.RecentModels == nil {
669		c.RecentModels = make(map[SelectedModelType][]SelectedModel)
670	}
671
672	eq := func(a, b SelectedModel) bool {
673		return a.Provider == b.Provider && a.Model == b.Model
674	}
675
676	entry := SelectedModel{
677		Provider: model.Provider,
678		Model:    model.Model,
679	}
680
681	current := c.RecentModels[modelType]
682	withoutCurrent := slices.DeleteFunc(slices.Clone(current), func(existing SelectedModel) bool {
683		return eq(existing, entry)
684	})
685
686	updated := append([]SelectedModel{entry}, withoutCurrent...)
687	if len(updated) > maxRecentModelsPerType {
688		updated = updated[:maxRecentModelsPerType]
689	}
690
691	if slices.EqualFunc(current, updated, eq) {
692		return nil
693	}
694
695	c.RecentModels[modelType] = updated
696
697	if err := c.SetConfigField(fmt.Sprintf("recent_models.%s", modelType), updated); err != nil {
698		return fmt.Errorf("failed to persist recent models: %w", err)
699	}
700
701	return nil
702}
703
704func allToolNames() []string {
705	return []string{
706		"agent",
707		"bash",
708		"job_output",
709		"job_kill",
710		"download",
711		"edit",
712		"multiedit",
713		"lsp_diagnostics",
714		"lsp_references",
715		"lsp_restart",
716		"fetch",
717		"agentic_fetch",
718		"glob",
719		"grep",
720		"ls",
721		"sourcegraph",
722		"todos",
723		"view",
724		"write",
725		"list_mcp_resources",
726		"read_mcp_resource",
727	}
728}
729
730func resolveAllowedTools(allTools []string, disabledTools []string) []string {
731	if disabledTools == nil {
732		return allTools
733	}
734	// filter out disabled tools (exclude mode)
735	return filterSlice(allTools, disabledTools, false)
736}
737
738func resolveReadOnlyTools(tools []string) []string {
739	readOnlyTools := []string{"glob", "grep", "ls", "sourcegraph", "view"}
740	// filter to only include tools that are in allowedtools (include mode)
741	return filterSlice(tools, readOnlyTools, true)
742}
743
744func filterSlice(data []string, mask []string, include bool) []string {
745	var filtered []string
746	for _, s := range data {
747		// if include is true, we include items that ARE in the mask
748		// if include is false, we include items that are NOT in the mask
749		if include == slices.Contains(mask, s) {
750			filtered = append(filtered, s)
751		}
752	}
753	return filtered
754}
755
756func (c *Config) SetupAgents() {
757	allowedTools := resolveAllowedTools(allToolNames(), c.Options.DisabledTools)
758
759	agents := map[string]Agent{
760		AgentCoder: {
761			ID:           AgentCoder,
762			Name:         "Coder",
763			Description:  "An agent that helps with executing coding tasks.",
764			Model:        SelectedModelTypeLarge,
765			ContextPaths: c.Options.ContextPaths,
766			AllowedTools: allowedTools,
767		},
768
769		AgentTask: {
770			ID:           AgentTask,
771			Name:         "Task",
772			Description:  "An agent that helps with searching for context and finding implementation details.",
773			Model:        SelectedModelTypeLarge,
774			ContextPaths: c.Options.ContextPaths,
775			AllowedTools: resolveReadOnlyTools(allowedTools),
776			// NO MCPs or LSPs by default
777			AllowedMCP: map[string][]string{},
778		},
779	}
780	c.Agents = agents
781}
782
783func (c *Config) Resolver() VariableResolver {
784	return c.resolver
785}
786
787func (c *ProviderConfig) TestConnection(resolver VariableResolver) error {
788	var (
789		providerID = catwalk.InferenceProvider(c.ID)
790		testURL    = ""
791		headers    = make(map[string]string)
792		apiKey, _  = resolver.ResolveValue(c.APIKey)
793	)
794
795	switch providerID {
796	case catwalk.InferenceProviderMiniMax, catwalk.InferenceProviderMiniMaxChina:
797		// NOTE: MiniMax has no good endpoint we can use to validate the API key.
798		// Let's at least check the pattern.
799		if !strings.HasPrefix(apiKey, "sk-") {
800			return fmt.Errorf("invalid API key format for provider %s", c.ID)
801		}
802		return nil
803	}
804
805	switch c.Type {
806	case catwalk.TypeOpenAI, catwalk.TypeOpenAICompat, catwalk.TypeOpenRouter:
807		baseURL, _ := resolver.ResolveValue(c.BaseURL)
808		baseURL = cmp.Or(baseURL, "https://api.openai.com/v1")
809
810		switch providerID {
811		case catwalk.InferenceProviderOpenRouter:
812			testURL = baseURL + "/credits"
813		default:
814			testURL = baseURL + "/models"
815		}
816
817		headers["Authorization"] = "Bearer " + apiKey
818	case catwalk.TypeAnthropic:
819		baseURL, _ := resolver.ResolveValue(c.BaseURL)
820		baseURL = cmp.Or(baseURL, "https://api.anthropic.com/v1")
821
822		switch providerID {
823		case catwalk.InferenceKimiCoding:
824			testURL = baseURL + "/v1/models"
825		default:
826			testURL = baseURL + "/models"
827		}
828
829		headers["x-api-key"] = apiKey
830		headers["anthropic-version"] = "2023-06-01"
831	case catwalk.TypeGoogle:
832		baseURL, _ := resolver.ResolveValue(c.BaseURL)
833		baseURL = cmp.Or(baseURL, "https://generativelanguage.googleapis.com")
834		testURL = baseURL + "/v1beta/models?key=" + url.QueryEscape(apiKey)
835	}
836
837	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
838	defer cancel()
839
840	client := &http.Client{}
841	req, err := http.NewRequestWithContext(ctx, "GET", testURL, nil)
842	if err != nil {
843		return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
844	}
845	for k, v := range headers {
846		req.Header.Set(k, v)
847	}
848	for k, v := range c.ExtraHeaders {
849		req.Header.Set(k, v)
850	}
851
852	resp, err := client.Do(req)
853	if err != nil {
854		return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
855	}
856	defer resp.Body.Close()
857
858	switch providerID {
859	case catwalk.InferenceProviderZAI:
860		if resp.StatusCode == http.StatusUnauthorized {
861			return fmt.Errorf("failed to connect to provider %s: %s", c.ID, resp.Status)
862		}
863	default:
864		if resp.StatusCode != http.StatusOK {
865			return fmt.Errorf("failed to connect to provider %s: %s", c.ID, resp.Status)
866		}
867	}
868	return nil
869}
870
871func resolveEnvs(envs map[string]string) []string {
872	resolver := NewShellVariableResolver(env.New())
873	for e, v := range envs {
874		var err error
875		envs[e], err = resolver.ResolveValue(v)
876		if err != nil {
877			slog.Error("Error resolving environment variable", "error", err, "variable", e, "value", v)
878			continue
879		}
880	}
881
882	res := make([]string, 0, len(envs))
883	for k, v := range envs {
884		res = append(res, fmt.Sprintf("%s=%s", k, v))
885	}
886	return res
887}
888
889func ptrValOr[T any](t *T, el T) T {
890	if t == nil {
891		return el
892	}
893	return *t
894}