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