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