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