config.go

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