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