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	"charm.land/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:"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	DisableDefaultProviders   bool         `json:"disable_default_providers,omitempty" jsonschema:"description=Ignore all default/embedded providers. When enabled, providers must be fully specified in the config file with base_url, models, and api_key - no merging with defaults occurs,default=false"`
257	Attribution               *Attribution `json:"attribution,omitempty" jsonschema:"description=Attribution settings for generated content"`
258	DisableMetrics            bool         `json:"disable_metrics,omitempty" jsonschema:"description=Disable sending metrics,default=false"`
259	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"`
260	AutoLSP                   *bool        `json:"auto_lsp,omitempty" jsonschema:"description=Automatically setup LSPs based on root markers,default=true"`
261	Progress                  *bool        `json:"progress,omitempty" jsonschema:"description=Show indeterminate progress updates during long operations,default=true"`
262}
263
264type MCPs map[string]MCPConfig
265
266type MCP struct {
267	Name string    `json:"name"`
268	MCP  MCPConfig `json:"mcp"`
269}
270
271func (m MCPs) Sorted() []MCP {
272	sorted := make([]MCP, 0, len(m))
273	for k, v := range m {
274		sorted = append(sorted, MCP{
275			Name: k,
276			MCP:  v,
277		})
278	}
279	slices.SortFunc(sorted, func(a, b MCP) int {
280		return strings.Compare(a.Name, b.Name)
281	})
282	return sorted
283}
284
285type LSPs map[string]LSPConfig
286
287type LSP struct {
288	Name string    `json:"name"`
289	LSP  LSPConfig `json:"lsp"`
290}
291
292func (l LSPs) Sorted() []LSP {
293	sorted := make([]LSP, 0, len(l))
294	for k, v := range l {
295		sorted = append(sorted, LSP{
296			Name: k,
297			LSP:  v,
298		})
299	}
300	slices.SortFunc(sorted, func(a, b LSP) int {
301		return strings.Compare(a.Name, b.Name)
302	})
303	return sorted
304}
305
306func (l LSPConfig) ResolvedEnv() []string {
307	return resolveEnvs(l.Env)
308}
309
310func (m MCPConfig) ResolvedEnv() []string {
311	return resolveEnvs(m.Env)
312}
313
314func (m MCPConfig) ResolvedHeaders() map[string]string {
315	resolver := NewShellVariableResolver(env.New())
316	for e, v := range m.Headers {
317		var err error
318		m.Headers[e], err = resolver.ResolveValue(v)
319		if err != nil {
320			slog.Error("Error resolving header variable", "error", err, "variable", e, "value", v)
321			continue
322		}
323	}
324	return m.Headers
325}
326
327type Agent struct {
328	ID          string `json:"id,omitempty"`
329	Name        string `json:"name,omitempty"`
330	Description string `json:"description,omitempty"`
331	// This is the id of the system prompt used by the agent
332	Disabled bool `json:"disabled,omitempty"`
333
334	Model SelectedModelType `json:"model" jsonschema:"required,description=The model type to use for this agent,enum=large,enum=small,default=large"`
335
336	// The available tools for the agent
337	//  if this is nil, all tools are available
338	AllowedTools []string `json:"allowed_tools,omitempty"`
339
340	// this tells us which MCPs are available for this agent
341	//  if this is empty all mcps are available
342	//  the string array is the list of tools from the AllowedMCP the agent has available
343	//  if the string array is nil, all tools from the AllowedMCP are available
344	AllowedMCP map[string][]string `json:"allowed_mcp,omitempty"`
345
346	// Overrides the context paths for this agent
347	ContextPaths []string `json:"context_paths,omitempty"`
348}
349
350type Tools struct {
351	Ls ToolLs `json:"ls,omitempty"`
352}
353
354type ToolLs struct {
355	MaxDepth *int `json:"max_depth,omitempty" jsonschema:"description=Maximum depth for the ls tool,default=0,example=10"`
356	MaxItems *int `json:"max_items,omitempty" jsonschema:"description=Maximum number of items to return for the ls tool,default=1000,example=100"`
357}
358
359func (t ToolLs) Limits() (depth, items int) {
360	return ptrValOr(t.MaxDepth, 0), ptrValOr(t.MaxItems, 0)
361}
362
363// Config holds the configuration for crush.
364type Config struct {
365	Schema string `json:"$schema,omitempty"`
366
367	// We currently only support large/small as values here.
368	Models map[SelectedModelType]SelectedModel `json:"models,omitempty" jsonschema:"description=Model configurations for different model types,example={\"large\":{\"model\":\"gpt-4o\",\"provider\":\"openai\"}}"`
369
370	// Recently used models stored in the data directory config.
371	RecentModels map[SelectedModelType][]SelectedModel `json:"recent_models,omitempty" jsonschema:"-"`
372
373	// The providers that are configured
374	Providers *csync.Map[string, ProviderConfig] `json:"providers,omitempty" jsonschema:"description=AI provider configurations"`
375
376	MCP MCPs `json:"mcp,omitempty" jsonschema:"description=Model Context Protocol server configurations"`
377
378	LSP LSPs `json:"lsp,omitempty" jsonschema:"description=Language Server Protocol configurations"`
379
380	Options *Options `json:"options,omitempty" jsonschema:"description=General application options"`
381
382	Permissions *Permissions `json:"permissions,omitempty" jsonschema:"description=Permission settings for tool usage"`
383
384	Tools Tools `json:"tools,omitempty" jsonschema:"description=Tool configurations"`
385
386	Agents map[string]Agent `json:"-"`
387
388	// Internal
389	workingDir string `json:"-"`
390	// TODO: find a better way to do this this should probably not be part of the config
391	resolver       VariableResolver
392	dataConfigDir  string             `json:"-"`
393	knownProviders []catwalk.Provider `json:"-"`
394}
395
396func (c *Config) WorkingDir() string {
397	return c.workingDir
398}
399
400func (c *Config) EnabledProviders() []ProviderConfig {
401	var enabled []ProviderConfig
402	for p := range c.Providers.Seq() {
403		if !p.Disable {
404			enabled = append(enabled, p)
405		}
406	}
407	return enabled
408}
409
410// IsConfigured  return true if at least one provider is configured
411func (c *Config) IsConfigured() bool {
412	return len(c.EnabledProviders()) > 0
413}
414
415func (c *Config) GetModel(provider, model string) *catwalk.Model {
416	if providerConfig, ok := c.Providers.Get(provider); ok {
417		for _, m := range providerConfig.Models {
418			if m.ID == model {
419				return &m
420			}
421		}
422	}
423	return nil
424}
425
426func (c *Config) GetProviderForModel(modelType SelectedModelType) *ProviderConfig {
427	model, ok := c.Models[modelType]
428	if !ok {
429		return nil
430	}
431	if providerConfig, ok := c.Providers.Get(model.Provider); ok {
432		return &providerConfig
433	}
434	return nil
435}
436
437func (c *Config) GetModelByType(modelType SelectedModelType) *catwalk.Model {
438	model, ok := c.Models[modelType]
439	if !ok {
440		return nil
441	}
442	return c.GetModel(model.Provider, model.Model)
443}
444
445func (c *Config) LargeModel() *catwalk.Model {
446	model, ok := c.Models[SelectedModelTypeLarge]
447	if !ok {
448		return nil
449	}
450	return c.GetModel(model.Provider, model.Model)
451}
452
453func (c *Config) SmallModel() *catwalk.Model {
454	model, ok := c.Models[SelectedModelTypeSmall]
455	if !ok {
456		return nil
457	}
458	return c.GetModel(model.Provider, model.Model)
459}
460
461func (c *Config) SetCompactMode(enabled bool) error {
462	if c.Options == nil {
463		c.Options = &Options{}
464	}
465	c.Options.TUI.CompactMode = enabled
466	return c.SetConfigField("options.tui.compact_mode", enabled)
467}
468
469func (c *Config) Resolve(key string) (string, error) {
470	if c.resolver == nil {
471		return "", fmt.Errorf("no variable resolver configured")
472	}
473	return c.resolver.ResolveValue(key)
474}
475
476func (c *Config) UpdatePreferredModel(modelType SelectedModelType, model SelectedModel) error {
477	c.Models[modelType] = model
478	if err := c.SetConfigField(fmt.Sprintf("models.%s", modelType), model); err != nil {
479		return fmt.Errorf("failed to update preferred model: %w", err)
480	}
481	if err := c.recordRecentModel(modelType, model); err != nil {
482		return err
483	}
484	return nil
485}
486
487func (c *Config) HasConfigField(key string) bool {
488	data, err := os.ReadFile(c.dataConfigDir)
489	if err != nil {
490		return false
491	}
492	return gjson.Get(string(data), key).Exists()
493}
494
495func (c *Config) SetConfigField(key string, value any) error {
496	data, err := os.ReadFile(c.dataConfigDir)
497	if err != nil {
498		if os.IsNotExist(err) {
499			data = []byte("{}")
500		} else {
501			return fmt.Errorf("failed to read config file: %w", err)
502		}
503	}
504
505	newValue, err := sjson.Set(string(data), key, value)
506	if err != nil {
507		return fmt.Errorf("failed to set config field %s: %w", key, err)
508	}
509	if err := os.MkdirAll(filepath.Dir(c.dataConfigDir), 0o755); err != nil {
510		return fmt.Errorf("failed to create config directory %q: %w", c.dataConfigDir, err)
511	}
512	if err := os.WriteFile(c.dataConfigDir, []byte(newValue), 0o600); err != nil {
513		return fmt.Errorf("failed to write config file: %w", err)
514	}
515	return nil
516}
517
518func (c *Config) RemoveConfigField(key string) error {
519	data, err := os.ReadFile(c.dataConfigDir)
520	if err != nil {
521		return fmt.Errorf("failed to read config file: %w", err)
522	}
523
524	newValue, err := sjson.Delete(string(data), key)
525	if err != nil {
526		return fmt.Errorf("failed to delete config field %s: %w", key, err)
527	}
528	if err := os.MkdirAll(filepath.Dir(c.dataConfigDir), 0o755); err != nil {
529		return fmt.Errorf("failed to create config directory %q: %w", c.dataConfigDir, err)
530	}
531	if err := os.WriteFile(c.dataConfigDir, []byte(newValue), 0o600); err != nil {
532		return fmt.Errorf("failed to write config file: %w", err)
533	}
534	return nil
535}
536
537// RefreshOAuthToken refreshes the OAuth token for the given provider.
538func (c *Config) RefreshOAuthToken(ctx context.Context, providerID string) error {
539	providerConfig, exists := c.Providers.Get(providerID)
540	if !exists {
541		return fmt.Errorf("provider %s not found", providerID)
542	}
543
544	if providerConfig.OAuthToken == nil {
545		return fmt.Errorf("provider %s does not have an OAuth token", providerID)
546	}
547
548	var newToken *oauth.Token
549	var refreshErr error
550	switch providerID {
551	case string(catwalk.InferenceProviderCopilot):
552		newToken, refreshErr = copilot.RefreshToken(ctx, providerConfig.OAuthToken.RefreshToken)
553	case hyperp.Name:
554		newToken, refreshErr = hyper.ExchangeToken(ctx, providerConfig.OAuthToken.RefreshToken)
555	default:
556		return fmt.Errorf("OAuth refresh not supported for provider %s", providerID)
557	}
558	if refreshErr != nil {
559		return fmt.Errorf("failed to refresh OAuth token for provider %s: %w", providerID, refreshErr)
560	}
561
562	slog.Info("Successfully refreshed OAuth token", "provider", providerID)
563	providerConfig.OAuthToken = newToken
564	providerConfig.APIKey = newToken.AccessToken
565
566	switch providerID {
567	case string(catwalk.InferenceProviderCopilot):
568		providerConfig.SetupGitHubCopilot()
569	}
570
571	c.Providers.Set(providerID, providerConfig)
572
573	if err := cmp.Or(
574		c.SetConfigField(fmt.Sprintf("providers.%s.api_key", providerID), newToken.AccessToken),
575		c.SetConfigField(fmt.Sprintf("providers.%s.oauth", providerID), newToken),
576	); err != nil {
577		return fmt.Errorf("failed to persist refreshed token: %w", err)
578	}
579
580	return nil
581}
582
583func (c *Config) SetProviderAPIKey(providerID string, apiKey any) error {
584	var providerConfig ProviderConfig
585	var exists bool
586	var setKeyOrToken func()
587
588	switch v := apiKey.(type) {
589	case string:
590		if err := c.SetConfigField(fmt.Sprintf("providers.%s.api_key", providerID), v); err != nil {
591			return fmt.Errorf("failed to save api key to config file: %w", err)
592		}
593		setKeyOrToken = func() { providerConfig.APIKey = v }
594	case *oauth.Token:
595		if err := cmp.Or(
596			c.SetConfigField(fmt.Sprintf("providers.%s.api_key", providerID), v.AccessToken),
597			c.SetConfigField(fmt.Sprintf("providers.%s.oauth", providerID), v),
598		); err != nil {
599			return err
600		}
601		setKeyOrToken = func() {
602			providerConfig.APIKey = v.AccessToken
603			providerConfig.OAuthToken = v
604			switch providerID {
605			case string(catwalk.InferenceProviderCopilot):
606				providerConfig.SetupGitHubCopilot()
607			}
608		}
609	}
610
611	providerConfig, exists = c.Providers.Get(providerID)
612	if exists {
613		setKeyOrToken()
614		c.Providers.Set(providerID, providerConfig)
615		return nil
616	}
617
618	var foundProvider *catwalk.Provider
619	for _, p := range c.knownProviders {
620		if string(p.ID) == providerID {
621			foundProvider = &p
622			break
623		}
624	}
625
626	if foundProvider != nil {
627		// Create new provider config based on known provider
628		providerConfig = ProviderConfig{
629			ID:           providerID,
630			Name:         foundProvider.Name,
631			BaseURL:      foundProvider.APIEndpoint,
632			Type:         foundProvider.Type,
633			Disable:      false,
634			ExtraHeaders: make(map[string]string),
635			ExtraParams:  make(map[string]string),
636			Models:       foundProvider.Models,
637		}
638		setKeyOrToken()
639	} else {
640		return fmt.Errorf("provider with ID %s not found in known providers", providerID)
641	}
642	// Store the updated provider config
643	c.Providers.Set(providerID, providerConfig)
644	return nil
645}
646
647const maxRecentModelsPerType = 5
648
649func (c *Config) recordRecentModel(modelType SelectedModelType, model SelectedModel) error {
650	if model.Provider == "" || model.Model == "" {
651		return nil
652	}
653
654	if c.RecentModels == nil {
655		c.RecentModels = make(map[SelectedModelType][]SelectedModel)
656	}
657
658	eq := func(a, b SelectedModel) bool {
659		return a.Provider == b.Provider && a.Model == b.Model
660	}
661
662	entry := SelectedModel{
663		Provider: model.Provider,
664		Model:    model.Model,
665	}
666
667	current := c.RecentModels[modelType]
668	withoutCurrent := slices.DeleteFunc(slices.Clone(current), func(existing SelectedModel) bool {
669		return eq(existing, entry)
670	})
671
672	updated := append([]SelectedModel{entry}, withoutCurrent...)
673	if len(updated) > maxRecentModelsPerType {
674		updated = updated[:maxRecentModelsPerType]
675	}
676
677	if slices.EqualFunc(current, updated, eq) {
678		return nil
679	}
680
681	c.RecentModels[modelType] = updated
682
683	if err := c.SetConfigField(fmt.Sprintf("recent_models.%s", modelType), updated); err != nil {
684		return fmt.Errorf("failed to persist recent models: %w", err)
685	}
686
687	return nil
688}
689
690func allToolNames() []string {
691	return []string{
692		"agent",
693		"bash",
694		"job_output",
695		"job_kill",
696		"download",
697		"edit",
698		"multiedit",
699		"lsp_diagnostics",
700		"lsp_references",
701		"lsp_restart",
702		"fetch",
703		"agentic_fetch",
704		"glob",
705		"grep",
706		"ls",
707		"sourcegraph",
708		"todos",
709		"view",
710		"write",
711	}
712}
713
714func resolveAllowedTools(allTools []string, disabledTools []string) []string {
715	if disabledTools == nil {
716		return allTools
717	}
718	// filter out disabled tools (exclude mode)
719	return filterSlice(allTools, disabledTools, false)
720}
721
722func resolveReadOnlyTools(tools []string) []string {
723	readOnlyTools := []string{"glob", "grep", "ls", "sourcegraph", "view"}
724	// filter to only include tools that are in allowedtools (include mode)
725	return filterSlice(tools, readOnlyTools, true)
726}
727
728func filterSlice(data []string, mask []string, include bool) []string {
729	filtered := []string{}
730	for _, s := range data {
731		// if include is true, we include items that ARE in the mask
732		// if include is false, we include items that are NOT in the mask
733		if include == slices.Contains(mask, s) {
734			filtered = append(filtered, s)
735		}
736	}
737	return filtered
738}
739
740func (c *Config) SetupAgents() {
741	allowedTools := resolveAllowedTools(allToolNames(), c.Options.DisabledTools)
742
743	agents := map[string]Agent{
744		AgentCoder: {
745			ID:           AgentCoder,
746			Name:         "Coder",
747			Description:  "An agent that helps with executing coding tasks.",
748			Model:        SelectedModelTypeLarge,
749			ContextPaths: c.Options.ContextPaths,
750			AllowedTools: allowedTools,
751		},
752
753		AgentTask: {
754			ID:           AgentCoder,
755			Name:         "Task",
756			Description:  "An agent that helps with searching for context and finding implementation details.",
757			Model:        SelectedModelTypeLarge,
758			ContextPaths: c.Options.ContextPaths,
759			AllowedTools: resolveReadOnlyTools(allowedTools),
760			// NO MCPs or LSPs by default
761			AllowedMCP: map[string][]string{},
762		},
763	}
764	c.Agents = agents
765}
766
767func (c *Config) Resolver() VariableResolver {
768	return c.resolver
769}
770
771func (c *ProviderConfig) TestConnection(resolver VariableResolver) error {
772	testURL := ""
773	headers := make(map[string]string)
774	apiKey, _ := resolver.ResolveValue(c.APIKey)
775	switch c.Type {
776	case catwalk.TypeOpenAI, catwalk.TypeOpenAICompat, catwalk.TypeOpenRouter:
777		baseURL, _ := resolver.ResolveValue(c.BaseURL)
778		if baseURL == "" {
779			baseURL = "https://api.openai.com/v1"
780		}
781		if c.ID == string(catwalk.InferenceProviderOpenRouter) {
782			testURL = baseURL + "/credits"
783		} else {
784			testURL = baseURL + "/models"
785		}
786		headers["Authorization"] = "Bearer " + apiKey
787	case catwalk.TypeAnthropic:
788		baseURL, _ := resolver.ResolveValue(c.BaseURL)
789		if baseURL == "" {
790			baseURL = "https://api.anthropic.com/v1"
791		}
792		testURL = baseURL + "/models"
793		// TODO: replace with const when catwalk is released
794		if c.ID == "kimi-coding" {
795			testURL = baseURL + "/v1/models"
796		}
797		headers["x-api-key"] = apiKey
798		headers["anthropic-version"] = "2023-06-01"
799	case catwalk.TypeGoogle:
800		baseURL, _ := resolver.ResolveValue(c.BaseURL)
801		if baseURL == "" {
802			baseURL = "https://generativelanguage.googleapis.com"
803		}
804		testURL = baseURL + "/v1beta/models?key=" + url.QueryEscape(apiKey)
805	}
806	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
807	defer cancel()
808	client := &http.Client{}
809	req, err := http.NewRequestWithContext(ctx, "GET", testURL, nil)
810	if err != nil {
811		return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
812	}
813	for k, v := range headers {
814		req.Header.Set(k, v)
815	}
816	for k, v := range c.ExtraHeaders {
817		req.Header.Set(k, v)
818	}
819	resp, err := client.Do(req)
820	if err != nil {
821		return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
822	}
823	defer resp.Body.Close()
824	if c.ID == string(catwalk.InferenceProviderZAI) {
825		if resp.StatusCode == http.StatusUnauthorized {
826			// For z.ai just check if the http response is not 401.
827			return fmt.Errorf("failed to connect to provider %s: %s", c.ID, resp.Status)
828		}
829	} else {
830		if resp.StatusCode != http.StatusOK {
831			return fmt.Errorf("failed to connect to provider %s: %s", c.ID, resp.Status)
832		}
833	}
834	return nil
835}
836
837func resolveEnvs(envs map[string]string) []string {
838	resolver := NewShellVariableResolver(env.New())
839	for e, v := range envs {
840		var err error
841		envs[e], err = resolver.ResolveValue(v)
842		if err != nil {
843			slog.Error("Error resolving environment variable", "error", err, "variable", e, "value", v)
844			continue
845		}
846	}
847
848	res := make([]string, 0, len(envs))
849	for k, v := range envs {
850		res = append(res, fmt.Sprintf("%s=%s", k, v))
851	}
852	return res
853}
854
855func ptrValOr[T any](t *T, el T) T {
856	if t == nil {
857		return el
858	}
859	return *t
860}