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