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	"github.com/charmbracelet/crush/internal/csync"
 17	"github.com/charmbracelet/crush/internal/env"
 18	"github.com/charmbracelet/crush/internal/oauth"
 19	"github.com/charmbracelet/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,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	TUI                       *TUIOptions  `json:"tui,omitempty" jsonschema:"description=Terminal user interface options"`
218	Debug                     bool         `json:"debug,omitempty" jsonschema:"description=Enable debug logging,default=false"`
219	DebugLSP                  bool         `json:"debug_lsp,omitempty" jsonschema:"description=Enable debug logging for LSP servers,default=false"`
220	DisableAutoSummarize      bool         `json:"disable_auto_summarize,omitempty" jsonschema:"description=Disable automatic conversation summarization,default=false"`
221	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
222	DisabledTools             []string     `json:"disabled_tools" jsonschema:"description=Tools to disable"`
223	DisableProviderAutoUpdate bool         `json:"disable_provider_auto_update,omitempty" jsonschema:"description=Disable providers auto-update,default=false"`
224	Attribution               *Attribution `json:"attribution,omitempty" jsonschema:"description=Attribution settings for generated content"`
225	DisableMetrics            bool         `json:"disable_metrics,omitempty" jsonschema:"description=Disable sending metrics,default=false"`
226	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"`
227}
228
229type MCPs map[string]MCPConfig
230
231type MCP struct {
232	Name string    `json:"name"`
233	MCP  MCPConfig `json:"mcp"`
234}
235
236func (m MCPs) Sorted() []MCP {
237	sorted := make([]MCP, 0, len(m))
238	for k, v := range m {
239		sorted = append(sorted, MCP{
240			Name: k,
241			MCP:  v,
242		})
243	}
244	slices.SortFunc(sorted, func(a, b MCP) int {
245		return strings.Compare(a.Name, b.Name)
246	})
247	return sorted
248}
249
250type LSPs map[string]LSPConfig
251
252type LSP struct {
253	Name string    `json:"name"`
254	LSP  LSPConfig `json:"lsp"`
255}
256
257func (l LSPs) Sorted() []LSP {
258	sorted := make([]LSP, 0, len(l))
259	for k, v := range l {
260		sorted = append(sorted, LSP{
261			Name: k,
262			LSP:  v,
263		})
264	}
265	slices.SortFunc(sorted, func(a, b LSP) int {
266		return strings.Compare(a.Name, b.Name)
267	})
268	return sorted
269}
270
271func (l LSPConfig) ResolvedEnv() []string {
272	return resolveEnvs(l.Env)
273}
274
275func (m MCPConfig) ResolvedEnv() []string {
276	return resolveEnvs(m.Env)
277}
278
279func (m MCPConfig) ResolvedHeaders() map[string]string {
280	resolver := NewShellVariableResolver(env.New())
281	for e, v := range m.Headers {
282		var err error
283		m.Headers[e], err = resolver.ResolveValue(v)
284		if err != nil {
285			slog.Error("error resolving header variable", "error", err, "variable", e, "value", v)
286			continue
287		}
288	}
289	return m.Headers
290}
291
292type Agent struct {
293	ID          string `json:"id,omitempty"`
294	Name        string `json:"name,omitempty"`
295	Description string `json:"description,omitempty"`
296	// This is the id of the system prompt used by the agent
297	Disabled bool `json:"disabled,omitempty"`
298
299	Model SelectedModelType `json:"model" jsonschema:"required,description=The model type to use for this agent,enum=large,enum=small,default=large"`
300
301	// The available tools for the agent
302	//  if this is nil, all tools are available
303	AllowedTools []string `json:"allowed_tools,omitempty"`
304
305	// this tells us which MCPs are available for this agent
306	//  if this is empty all mcps are available
307	//  the string array is the list of tools from the AllowedMCP the agent has available
308	//  if the string array is nil, all tools from the AllowedMCP are available
309	AllowedMCP map[string][]string `json:"allowed_mcp,omitempty"`
310
311	// Overrides the context paths for this agent
312	ContextPaths []string `json:"context_paths,omitempty"`
313}
314
315type Tools struct {
316	Ls ToolLs `json:"ls,omitzero"`
317}
318
319type ToolLs struct {
320	MaxDepth *int `json:"max_depth,omitempty" jsonschema:"description=Maximum depth for the ls tool,default=0,example=10"`
321	MaxItems *int `json:"max_items,omitempty" jsonschema:"description=Maximum number of items to return for the ls tool,default=1000,example=100"`
322}
323
324func (t ToolLs) Limits() (depth, items int) {
325	return ptrValOr(t.MaxDepth, 0), ptrValOr(t.MaxItems, 0)
326}
327
328// Config holds the configuration for crush.
329type Config struct {
330	Schema string `json:"$schema,omitempty"`
331
332	// We currently only support large/small as values here.
333	Models map[SelectedModelType]SelectedModel `json:"models,omitempty" jsonschema:"description=Model configurations for different model types,example={\"large\":{\"model\":\"gpt-4o\",\"provider\":\"openai\"}}"`
334	// Recently used models stored in the data directory config.
335	RecentModels map[SelectedModelType][]SelectedModel `json:"recent_models,omitempty" jsonschema:"description=Recently used models sorted by most recent first"`
336
337	// The providers that are configured
338	Providers *csync.Map[string, ProviderConfig] `json:"providers,omitempty" jsonschema:"description=AI provider configurations"`
339
340	MCP MCPs `json:"mcp,omitempty" jsonschema:"description=Model Context Protocol server configurations"`
341
342	LSP LSPs `json:"lsp,omitempty" jsonschema:"description=Language Server Protocol configurations"`
343
344	Options *Options `json:"options,omitempty" jsonschema:"description=General application options"`
345
346	Permissions *Permissions `json:"permissions,omitempty" jsonschema:"description=Permission settings for tool usage"`
347
348	Tools Tools `json:"tools,omitzero" jsonschema:"description=Tool configurations"`
349
350	Agents map[string]Agent `json:"-"`
351
352	// Internal
353	workingDir string `json:"-"`
354	// TODO: find a better way to do this this should probably not be part of the config
355	resolver       VariableResolver
356	dataConfigDir  string             `json:"-"`
357	knownProviders []catwalk.Provider `json:"-"`
358}
359
360func (c *Config) WorkingDir() string {
361	return c.workingDir
362}
363
364func (c *Config) EnabledProviders() []ProviderConfig {
365	var enabled []ProviderConfig
366	for p := range c.Providers.Seq() {
367		if !p.Disable {
368			enabled = append(enabled, p)
369		}
370	}
371	return enabled
372}
373
374// IsConfigured  return true if at least one provider is configured
375func (c *Config) IsConfigured() bool {
376	return len(c.EnabledProviders()) > 0
377}
378
379func (c *Config) GetModel(provider, model string) *catwalk.Model {
380	if providerConfig, ok := c.Providers.Get(provider); ok {
381		for _, m := range providerConfig.Models {
382			if m.ID == model {
383				return &m
384			}
385		}
386	}
387	return nil
388}
389
390func (c *Config) GetProviderForModel(modelType SelectedModelType) *ProviderConfig {
391	model, ok := c.Models[modelType]
392	if !ok {
393		return nil
394	}
395	if providerConfig, ok := c.Providers.Get(model.Provider); ok {
396		return &providerConfig
397	}
398	return nil
399}
400
401func (c *Config) GetModelByType(modelType SelectedModelType) *catwalk.Model {
402	model, ok := c.Models[modelType]
403	if !ok {
404		return nil
405	}
406	return c.GetModel(model.Provider, model.Model)
407}
408
409func (c *Config) LargeModel() *catwalk.Model {
410	model, ok := c.Models[SelectedModelTypeLarge]
411	if !ok {
412		return nil
413	}
414	return c.GetModel(model.Provider, model.Model)
415}
416
417func (c *Config) SmallModel() *catwalk.Model {
418	model, ok := c.Models[SelectedModelTypeSmall]
419	if !ok {
420		return nil
421	}
422	return c.GetModel(model.Provider, model.Model)
423}
424
425func (c *Config) SetCompactMode(enabled bool) error {
426	if c.Options == nil {
427		c.Options = &Options{}
428	}
429	c.Options.TUI.CompactMode = enabled
430	return c.SetConfigField("options.tui.compact_mode", enabled)
431}
432
433func (c *Config) Resolve(key string) (string, error) {
434	if c.resolver == nil {
435		return "", fmt.Errorf("no variable resolver configured")
436	}
437	return c.resolver.ResolveValue(key)
438}
439
440func (c *Config) UpdatePreferredModel(modelType SelectedModelType, model SelectedModel) error {
441	c.Models[modelType] = model
442	if err := c.SetConfigField(fmt.Sprintf("models.%s", modelType), model); err != nil {
443		return fmt.Errorf("failed to update preferred model: %w", err)
444	}
445	if err := c.recordRecentModel(modelType, model); err != nil {
446		return err
447	}
448	return nil
449}
450
451func (c *Config) SetConfigField(key string, value any) error {
452	// read the data
453	data, err := os.ReadFile(c.dataConfigDir)
454	if err != nil {
455		if os.IsNotExist(err) {
456			data = []byte("{}")
457		} else {
458			return fmt.Errorf("failed to read config file: %w", err)
459		}
460	}
461
462	newValue, err := sjson.Set(string(data), key, value)
463	if err != nil {
464		return fmt.Errorf("failed to set config field %s: %w", key, err)
465	}
466	if err := os.WriteFile(c.dataConfigDir, []byte(newValue), 0o600); err != nil {
467		return fmt.Errorf("failed to write config file: %w", err)
468	}
469	return nil
470}
471
472func (c *Config) RefreshOAuthToken(ctx context.Context, providerID string) error {
473	providerConfig, exists := c.Providers.Get(providerID)
474	if !exists {
475		return fmt.Errorf("provider %s not found", providerID)
476	}
477
478	if providerConfig.OAuthToken == nil {
479		return fmt.Errorf("provider %s does not have an OAuth token", providerID)
480	}
481
482	// Only Anthropic provider uses OAuth for now
483	if providerID != string(catwalk.InferenceProviderAnthropic) {
484		return fmt.Errorf("OAuth refresh not supported for provider %s", providerID)
485	}
486
487	newToken, err := claude.RefreshToken(ctx, providerConfig.OAuthToken.RefreshToken)
488	if err != nil {
489		return fmt.Errorf("failed to refresh OAuth token for provider %s: %w", providerID, err)
490	}
491
492	slog.Info("Successfully refreshed OAuth token in background", "provider", providerID)
493	providerConfig.OAuthToken = newToken
494	providerConfig.APIKey = fmt.Sprintf("Bearer %s", newToken.AccessToken)
495	providerConfig.SetupClaudeCode()
496
497	c.Providers.Set(providerID, providerConfig)
498
499	if err := cmp.Or(
500		c.SetConfigField(fmt.Sprintf("providers.%s.api_key", providerID), newToken.AccessToken),
501		c.SetConfigField(fmt.Sprintf("providers.%s.oauth", providerID), newToken),
502	); err != nil {
503		return fmt.Errorf("failed to persist refreshed token: %w", err)
504	}
505
506	return nil
507}
508
509func (c *Config) SetProviderAPIKey(providerID string, apiKey any) error {
510	var providerConfig ProviderConfig
511	var exists bool
512	var setKeyOrToken func()
513
514	switch v := apiKey.(type) {
515	case string:
516		if err := c.SetConfigField(fmt.Sprintf("providers.%s.api_key", providerID), v); err != nil {
517			return fmt.Errorf("failed to save api key to config file: %w", err)
518		}
519		setKeyOrToken = func() { providerConfig.APIKey = v }
520	case *oauth.Token:
521		if err := cmp.Or(
522			c.SetConfigField(fmt.Sprintf("providers.%s.api_key", providerID), v.AccessToken),
523			c.SetConfigField(fmt.Sprintf("providers.%s.oauth", providerID), v),
524		); err != nil {
525			return err
526		}
527		setKeyOrToken = func() {
528			providerConfig.APIKey = v.AccessToken
529			providerConfig.OAuthToken = v
530			providerConfig.SetupClaudeCode()
531		}
532	}
533
534	providerConfig, exists = c.Providers.Get(providerID)
535	if exists {
536		setKeyOrToken()
537		c.Providers.Set(providerID, providerConfig)
538		return nil
539	}
540
541	var foundProvider *catwalk.Provider
542	for _, p := range c.knownProviders {
543		if string(p.ID) == providerID {
544			foundProvider = &p
545			break
546		}
547	}
548
549	if foundProvider != nil {
550		// Create new provider config based on known provider
551		providerConfig = ProviderConfig{
552			ID:           providerID,
553			Name:         foundProvider.Name,
554			BaseURL:      foundProvider.APIEndpoint,
555			Type:         foundProvider.Type,
556			Disable:      false,
557			ExtraHeaders: make(map[string]string),
558			ExtraParams:  make(map[string]string),
559			Models:       foundProvider.Models,
560		}
561		setKeyOrToken()
562	} else {
563		return fmt.Errorf("provider with ID %s not found in known providers", providerID)
564	}
565	// Store the updated provider config
566	c.Providers.Set(providerID, providerConfig)
567	return nil
568}
569
570const maxRecentModelsPerType = 5
571
572func (c *Config) recordRecentModel(modelType SelectedModelType, model SelectedModel) error {
573	if model.Provider == "" || model.Model == "" {
574		return nil
575	}
576
577	if c.RecentModels == nil {
578		c.RecentModels = make(map[SelectedModelType][]SelectedModel)
579	}
580
581	eq := func(a, b SelectedModel) bool {
582		return a.Provider == b.Provider && a.Model == b.Model
583	}
584
585	entry := SelectedModel{
586		Provider: model.Provider,
587		Model:    model.Model,
588	}
589
590	current := c.RecentModels[modelType]
591	withoutCurrent := slices.DeleteFunc(slices.Clone(current), func(existing SelectedModel) bool {
592		return eq(existing, entry)
593	})
594
595	updated := append([]SelectedModel{entry}, withoutCurrent...)
596	if len(updated) > maxRecentModelsPerType {
597		updated = updated[:maxRecentModelsPerType]
598	}
599
600	if slices.EqualFunc(current, updated, eq) {
601		return nil
602	}
603
604	c.RecentModels[modelType] = updated
605
606	if err := c.SetConfigField(fmt.Sprintf("recent_models.%s", modelType), updated); err != nil {
607		return fmt.Errorf("failed to persist recent models: %w", err)
608	}
609
610	return nil
611}
612
613func allToolNames() []string {
614	return []string{
615		"agent",
616		"bash",
617		"job_output",
618		"job_kill",
619		"download",
620		"edit",
621		"multiedit",
622		"lsp_diagnostics",
623		"lsp_references",
624		"fetch",
625		"agentic_fetch",
626		"glob",
627		"grep",
628		"ls",
629		"sourcegraph",
630		"view",
631		"write",
632	}
633}
634
635func resolveAllowedTools(allTools []string, disabledTools []string) []string {
636	if disabledTools == nil {
637		return allTools
638	}
639	// filter out disabled tools (exclude mode)
640	return filterSlice(allTools, disabledTools, false)
641}
642
643func resolveReadOnlyTools(tools []string) []string {
644	readOnlyTools := []string{"glob", "grep", "ls", "sourcegraph", "view"}
645	// filter to only include tools that are in allowedtools (include mode)
646	return filterSlice(tools, readOnlyTools, true)
647}
648
649func filterSlice(data []string, mask []string, include bool) []string {
650	filtered := []string{}
651	for _, s := range data {
652		// if include is true, we include items that ARE in the mask
653		// if include is false, we include items that are NOT in the mask
654		if include == slices.Contains(mask, s) {
655			filtered = append(filtered, s)
656		}
657	}
658	return filtered
659}
660
661func (c *Config) SetupAgents() {
662	allowedTools := resolveAllowedTools(allToolNames(), c.Options.DisabledTools)
663
664	agents := map[string]Agent{
665		AgentCoder: {
666			ID:           AgentCoder,
667			Name:         "Coder",
668			Description:  "An agent that helps with executing coding tasks.",
669			Model:        SelectedModelTypeLarge,
670			ContextPaths: c.Options.ContextPaths,
671			AllowedTools: allowedTools,
672		},
673
674		AgentTask: {
675			ID:           AgentCoder,
676			Name:         "Task",
677			Description:  "An agent that helps with searching for context and finding implementation details.",
678			Model:        SelectedModelTypeLarge,
679			ContextPaths: c.Options.ContextPaths,
680			AllowedTools: resolveReadOnlyTools(allowedTools),
681			// NO MCPs or LSPs by default
682			AllowedMCP: map[string][]string{},
683		},
684	}
685	c.Agents = agents
686}
687
688func (c *Config) Resolver() VariableResolver {
689	return c.resolver
690}
691
692func (c *ProviderConfig) TestConnection(resolver VariableResolver) error {
693	testURL := ""
694	headers := make(map[string]string)
695	apiKey, _ := resolver.ResolveValue(c.APIKey)
696	switch c.Type {
697	case catwalk.TypeOpenAI, catwalk.TypeOpenAICompat, catwalk.TypeOpenRouter:
698		baseURL, _ := resolver.ResolveValue(c.BaseURL)
699		if baseURL == "" {
700			baseURL = "https://api.openai.com/v1"
701		}
702		if c.ID == string(catwalk.InferenceProviderOpenRouter) {
703			testURL = baseURL + "/credits"
704		} else {
705			testURL = baseURL + "/models"
706		}
707		headers["Authorization"] = "Bearer " + apiKey
708	case catwalk.TypeAnthropic:
709		baseURL, _ := resolver.ResolveValue(c.BaseURL)
710		if baseURL == "" {
711			baseURL = "https://api.anthropic.com/v1"
712		}
713		testURL = baseURL + "/models"
714		// TODO: replace with const when catwalk is released
715		if c.ID == "kimi-coding" {
716			testURL = baseURL + "/v1/models"
717		}
718		headers["x-api-key"] = apiKey
719		headers["anthropic-version"] = "2023-06-01"
720	case catwalk.TypeGoogle:
721		baseURL, _ := resolver.ResolveValue(c.BaseURL)
722		if baseURL == "" {
723			baseURL = "https://generativelanguage.googleapis.com"
724		}
725		testURL = baseURL + "/v1beta/models?key=" + url.QueryEscape(apiKey)
726	}
727	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
728	defer cancel()
729	client := &http.Client{}
730	req, err := http.NewRequestWithContext(ctx, "GET", testURL, nil)
731	if err != nil {
732		return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
733	}
734	for k, v := range headers {
735		req.Header.Set(k, v)
736	}
737	for k, v := range c.ExtraHeaders {
738		req.Header.Set(k, v)
739	}
740	b, err := client.Do(req)
741	if err != nil {
742		return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
743	}
744	if c.ID == string(catwalk.InferenceProviderZAI) {
745		if b.StatusCode == http.StatusUnauthorized {
746			// for z.ai just check if the http response is not 401
747			return fmt.Errorf("failed to connect to provider %s: %s", c.ID, b.Status)
748		}
749	} else {
750		if b.StatusCode != http.StatusOK {
751			return fmt.Errorf("failed to connect to provider %s: %s", c.ID, b.Status)
752		}
753	}
754	_ = b.Body.Close()
755	return nil
756}
757
758func resolveEnvs(envs map[string]string) []string {
759	resolver := NewShellVariableResolver(env.New())
760	for e, v := range envs {
761		var err error
762		envs[e], err = resolver.ResolveValue(v)
763		if err != nil {
764			slog.Error("error resolving environment variable", "error", err, "variable", e, "value", v)
765			continue
766		}
767	}
768
769	res := make([]string, 0, len(envs))
770	for k, v := range envs {
771		res = append(res, fmt.Sprintf("%s=%s", k, v))
772	}
773	return res
774}
775
776func ptrValOr[T any](t *T, el T) T {
777	if t == nil {
778		return el
779	}
780	return *t
781}