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