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