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