config.go

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