config.go

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