1package config
2
3import (
4 "cmp"
5 "context"
6 "errors"
7 "fmt"
8 "maps"
9 "net/http"
10 "net/url"
11 "slices"
12 "strings"
13 "time"
14
15 "charm.land/catwalk/pkg/catwalk"
16 "github.com/charmbracelet/crush/internal/csync"
17 "github.com/charmbracelet/crush/internal/oauth"
18 "github.com/charmbracelet/crush/internal/oauth/copilot"
19 "github.com/invopop/jsonschema"
20)
21
22const (
23 appName = "crush"
24 defaultDataDirectory = ".crush"
25 defaultInitializeAs = "AGENTS.md"
26)
27
28var defaultContextPaths = []string{
29 ".github/copilot-instructions.md",
30 ".cursorrules",
31 ".cursor/rules/",
32 "CLAUDE.md",
33 "CLAUDE.local.md",
34 "GEMINI.md",
35 "gemini.md",
36 "crush.md",
37 "crush.local.md",
38 "Crush.md",
39 "Crush.local.md",
40 "CRUSH.md",
41 "CRUSH.local.md",
42 "AGENTS.md",
43 "agents.md",
44 "Agents.md",
45}
46
47type SelectedModelType string
48
49// String returns the string representation of the [SelectedModelType].
50func (s SelectedModelType) String() string {
51 return string(s)
52}
53
54const (
55 SelectedModelTypeLarge SelectedModelType = "large"
56 SelectedModelTypeSmall SelectedModelType = "small"
57)
58
59const (
60 AgentCoder string = "coder"
61 AgentTask string = "task"
62)
63
64type SelectedModel struct {
65 // The model id as used by the provider API.
66 // Required.
67 Model string `json:"model" jsonschema:"required,description=The model ID as used by the provider API,example=gpt-4o"`
68 // The model provider, same as the key/id used in the providers config.
69 // Required.
70 Provider string `json:"provider" jsonschema:"required,description=The model provider ID that matches a key in the providers config,example=openai"`
71
72 // Only used by models that use the openai provider and need this set.
73 ReasoningEffort string `json:"reasoning_effort,omitempty" jsonschema:"description=Reasoning effort level for OpenAI models that support it,enum=low,enum=medium,enum=high"`
74
75 // Used by anthropic models that can reason to indicate if the model should think.
76 Think bool `json:"think,omitempty" jsonschema:"description=Enable thinking mode for Anthropic models that support reasoning"`
77
78 // Overrides the default model configuration.
79 MaxTokens int64 `json:"max_tokens,omitempty" jsonschema:"description=Maximum number of tokens for model responses,maximum=200000,example=4096"`
80 Temperature *float64 `json:"temperature,omitempty" jsonschema:"description=Sampling temperature,minimum=0,maximum=1,example=0.7"`
81 TopP *float64 `json:"top_p,omitempty" jsonschema:"description=Top-p (nucleus) sampling parameter,minimum=0,maximum=1,example=0.9"`
82 TopK *int64 `json:"top_k,omitempty" jsonschema:"description=Top-k sampling parameter"`
83 FrequencyPenalty *float64 `json:"frequency_penalty,omitempty" jsonschema:"description=Frequency penalty to reduce repetition"`
84 PresencePenalty *float64 `json:"presence_penalty,omitempty" jsonschema:"description=Presence penalty to increase topic diversity"`
85
86 // Override provider specific options.
87 ProviderOptions map[string]any `json:"provider_options,omitempty" jsonschema:"description=Additional provider-specific options for the model"`
88}
89
90type ProviderConfig struct {
91 // The provider's id.
92 ID string `json:"id,omitempty" jsonschema:"description=Unique identifier for the provider,example=openai"`
93 // The provider's name, used for display purposes.
94 Name string `json:"name,omitempty" jsonschema:"description=Human-readable name for the provider,example=OpenAI"`
95 // The provider's API endpoint.
96 BaseURL string `json:"base_url,omitempty" jsonschema:"description=Base URL for the provider's API,format=uri,example=https://api.openai.com/v1"`
97 // The provider type, e.g. "openai", "anthropic", etc. if empty it defaults to openai.
98 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"`
99 // The provider's API key.
100 APIKey string `json:"api_key,omitempty" jsonschema:"description=API key for authentication with the provider,example=$OPENAI_API_KEY"`
101 // The original API key template before resolution (for re-resolution on auth errors).
102 APIKeyTemplate string `json:"-"`
103 // OAuthToken for providers that use OAuth2 authentication.
104 OAuthToken *oauth.Token `json:"oauth,omitempty" jsonschema:"description=OAuth2 token for authentication with the provider"`
105 // Marks the provider as disabled.
106 Disable bool `json:"disable,omitempty" jsonschema:"description=Whether this provider is disabled,default=false"`
107
108 // Custom system prompt prefix.
109 SystemPromptPrefix string `json:"system_prompt_prefix,omitempty" jsonschema:"description=Custom prefix to add to system prompts for this provider"`
110
111 // Extra headers to send with each request to the provider.
112 ExtraHeaders map[string]string `json:"extra_headers,omitempty" jsonschema:"description=Additional HTTP headers to send with requests"`
113 // Extra body
114 ExtraBody map[string]any `json:"extra_body,omitempty" jsonschema:"description=Additional fields to include in request bodies, only works with openai-compatible providers"`
115
116 ProviderOptions map[string]any `json:"provider_options,omitempty" jsonschema:"description=Additional provider-specific options for this provider"`
117
118 // Used to pass extra parameters to the provider.
119 ExtraParams map[string]string `json:"-"`
120
121 // The provider models
122 Models []catwalk.Model `json:"models,omitempty" jsonschema:"description=List of models available from this provider"`
123}
124
125// ToProvider converts the [ProviderConfig] to a [catwalk.Provider].
126func (c *ProviderConfig) ToProvider() catwalk.Provider {
127 // Convert config provider to provider.Provider format
128 provider := catwalk.Provider{
129 Name: c.Name,
130 ID: catwalk.InferenceProvider(c.ID),
131 Models: make([]catwalk.Model, len(c.Models)),
132 }
133
134 // Convert models
135 for i, model := range c.Models {
136 provider.Models[i] = catwalk.Model{
137 ID: model.ID,
138 Name: model.Name,
139 CostPer1MIn: model.CostPer1MIn,
140 CostPer1MOut: model.CostPer1MOut,
141 CostPer1MInCached: model.CostPer1MInCached,
142 CostPer1MOutCached: model.CostPer1MOutCached,
143 ContextWindow: model.ContextWindow,
144 DefaultMaxTokens: model.DefaultMaxTokens,
145 CanReason: model.CanReason,
146 ReasoningLevels: model.ReasoningLevels,
147 DefaultReasoningEffort: model.DefaultReasoningEffort,
148 SupportsImages: model.SupportsImages,
149 }
150 }
151
152 return provider
153}
154
155func (c *ProviderConfig) SetupGitHubCopilot() {
156 maps.Copy(c.ExtraHeaders, copilot.Headers())
157}
158
159type MCPType string
160
161const (
162 MCPStdio MCPType = "stdio"
163 MCPSSE MCPType = "sse"
164 MCPHttp MCPType = "http"
165)
166
167type MCPConfig struct {
168 Command string `json:"command,omitempty" jsonschema:"description=Command to execute for stdio MCP servers,example=npx"`
169 Env map[string]string `json:"env,omitempty" jsonschema:"description=Environment variables to set for the MCP server"`
170 Args []string `json:"args,omitempty" jsonschema:"description=Arguments to pass to the MCP server command"`
171 Type MCPType `json:"type" jsonschema:"required,description=Type of MCP connection,enum=stdio,enum=sse,enum=http,default=stdio"`
172 URL string `json:"url,omitempty" jsonschema:"description=URL for HTTP or SSE MCP servers,format=uri,example=http://localhost:3000/mcp"`
173 Disabled bool `json:"disabled,omitempty" jsonschema:"description=Whether this MCP server is disabled,default=false"`
174 DisabledTools []string `json:"disabled_tools,omitempty" jsonschema:"description=List of tools from this MCP server to disable,example=get-library-doc"`
175 Timeout int `json:"timeout,omitempty" jsonschema:"description=Timeout in seconds for MCP server connections,default=15,example=30,example=60,example=120"`
176
177 // TODO: maybe make it possible to get the value from the env
178 Headers map[string]string `json:"headers,omitempty" jsonschema:"description=HTTP headers for HTTP/SSE MCP servers"`
179}
180
181type LSPConfig struct {
182 Disabled bool `json:"disabled,omitempty" jsonschema:"description=Whether this LSP server is disabled,default=false"`
183 Command string `json:"command,omitempty" jsonschema:"description=Command to execute for the LSP server,example=gopls"`
184 Args []string `json:"args,omitempty" jsonschema:"description=Arguments to pass to the LSP server command"`
185 Env map[string]string `json:"env,omitempty" jsonschema:"description=Environment variables to set to the LSP server command"`
186 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"`
187 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"`
188 InitOptions map[string]any `json:"init_options,omitempty" jsonschema:"description=Initialization options passed to the LSP server during initialize request"`
189 Options map[string]any `json:"options,omitempty" jsonschema:"description=LSP server-specific settings passed during initialization"`
190 Timeout int `json:"timeout,omitempty" jsonschema:"description=Timeout in seconds for LSP server initialization,default=30,example=60,example=120"`
191}
192
193type TUIOptions struct {
194 CompactMode bool `json:"compact_mode,omitempty" jsonschema:"description=Enable compact mode for the TUI interface,default=false"`
195 DiffMode string `json:"diff_mode,omitempty" jsonschema:"description=Diff mode for the TUI interface,enum=unified,enum=split"`
196 // Here we can add themes later or any TUI related options
197 //
198
199 Completions Completions `json:"completions,omitzero" jsonschema:"description=Completions UI options"`
200 Transparent *bool `json:"transparent,omitempty" jsonschema:"description=Enable transparent background for the TUI interface,default=false"`
201}
202
203// Completions defines options for the completions UI.
204type Completions struct {
205 MaxDepth *int `json:"max_depth,omitempty" jsonschema:"description=Maximum depth for the ls tool,default=0,example=10"`
206 MaxItems *int `json:"max_items,omitempty" jsonschema:"description=Maximum number of items to return for the ls tool,default=1000,example=100"`
207}
208
209func (c Completions) Limits() (depth, items int) {
210 return ptrValOr(c.MaxDepth, 0), ptrValOr(c.MaxItems, 0)
211}
212
213type Permissions struct {
214 AllowedTools []string `json:"allowed_tools,omitempty" jsonschema:"description=List of tools that don't require permission prompts,example=bash,example=view"`
215}
216
217type TrailerStyle string
218
219const (
220 TrailerStyleNone TrailerStyle = "none"
221 TrailerStyleCoAuthoredBy TrailerStyle = "co-authored-by"
222 TrailerStyleAssistedBy TrailerStyle = "assisted-by"
223)
224
225type Attribution struct {
226 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"`
227 CoAuthoredBy *bool `json:"co_authored_by,omitempty" jsonschema:"description=Deprecated: use trailer_style instead"`
228 GeneratedWith bool `json:"generated_with,omitempty" jsonschema:"description=Add Generated with Crush line to commit messages and issues and PRs,default=true"`
229}
230
231// JSONSchemaExtend marks the co_authored_by field as deprecated in the schema.
232func (Attribution) JSONSchemaExtend(schema *jsonschema.Schema) {
233 if schema.Properties != nil {
234 if prop, ok := schema.Properties.Get("co_authored_by"); ok {
235 prop.Deprecated = true
236 }
237 }
238}
239
240type Options struct {
241 ContextPaths []string `json:"context_paths,omitempty" jsonschema:"description=Paths to files containing context information for the AI,example=.cursorrules,example=CRUSH.md"`
242 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"`
243 TUI *TUIOptions `json:"tui,omitempty" jsonschema:"description=Terminal user interface options"`
244 Debug bool `json:"debug,omitempty" jsonschema:"description=Enable debug logging,default=false"`
245 DebugLSP bool `json:"debug_lsp,omitempty" jsonschema:"description=Enable debug logging for LSP servers,default=false"`
246 DisableAutoSummarize bool `json:"disable_auto_summarize,omitempty" jsonschema:"description=Disable automatic conversation summarization,default=false"`
247 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
248 DisabledTools []string `json:"disabled_tools,omitempty" jsonschema:"description=List of built-in tools to disable and hide from the agent,example=bash,example=sourcegraph"`
249 DisableProviderAutoUpdate bool `json:"disable_provider_auto_update,omitempty" jsonschema:"description=Disable providers auto-update,default=false"`
250 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"`
251 Attribution *Attribution `json:"attribution,omitempty" jsonschema:"description=Attribution settings for generated content"`
252 DisableMetrics bool `json:"disable_metrics,omitempty" jsonschema:"description=Disable sending metrics,default=false"`
253 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"`
254 AutoLSP *bool `json:"auto_lsp,omitempty" jsonschema:"description=Automatically setup LSPs based on root markers,default=true"`
255 Progress *bool `json:"progress,omitempty" jsonschema:"description=Show indeterminate progress updates during long operations,default=true"`
256 DisableNotifications bool `json:"disable_notifications,omitempty" jsonschema:"description=Disable desktop notifications,default=false"`
257 DisabledSkills []string `json:"disabled_skills,omitempty" jsonschema:"description=List of skill names to disable and hide from the agent,example=crush-config"`
258}
259
260type MCPs map[string]MCPConfig
261
262type MCP struct {
263 Name string `json:"name"`
264 MCP MCPConfig `json:"mcp"`
265}
266
267func (m MCPs) Sorted() []MCP {
268 sorted := make([]MCP, 0, len(m))
269 for k, v := range m {
270 sorted = append(sorted, MCP{
271 Name: k,
272 MCP: v,
273 })
274 }
275 slices.SortFunc(sorted, func(a, b MCP) int {
276 return strings.Compare(a.Name, b.Name)
277 })
278 return sorted
279}
280
281type LSPs map[string]LSPConfig
282
283type LSP struct {
284 Name string `json:"name"`
285 LSP LSPConfig `json:"lsp"`
286}
287
288func (l LSPs) Sorted() []LSP {
289 sorted := make([]LSP, 0, len(l))
290 for k, v := range l {
291 sorted = append(sorted, LSP{
292 Name: k,
293 LSP: v,
294 })
295 }
296 slices.SortFunc(sorted, func(a, b LSP) int {
297 return strings.Compare(a.Name, b.Name)
298 })
299 return sorted
300}
301
302// ResolvedEnv returns m.Env with every value expanded through the
303// given resolver. The returned slice is of the form "KEY=value" sorted
304// by key so callers get deterministic output; the receiver's Env map is
305// not mutated. On the first resolution failure it returns nil and an
306// error that identifies the offending key; the inner resolver error is
307// already sanitized by ResolveValue and is wrapped with %w so
308// errors.Is/As continues to work. Callers are expected to surface it
309// (for MCP, via StateError on the status card) rather than silently
310// spawn the server with an empty credential.
311//
312// The resolver choice matters: in server mode pass the shell resolver
313// so $VAR / $(cmd) expand; in client mode pass IdentityResolver so the
314// template is forwarded verbatim and expansion happens on the server.
315func (m MCPConfig) ResolvedEnv(r VariableResolver) ([]string, error) {
316 return resolveEnvs(m.Env, r)
317}
318
319// ResolvedArgs returns m.Args with every element expanded through the
320// given resolver. A fresh slice is allocated; m.Args is never mutated.
321// On the first resolution failure it returns nil and an error
322// identifying the offending positional index; the inner resolver error
323// is already sanitized by ResolveValue and is wrapped with %w so
324// errors.Is/As continues to work.
325//
326// See ResolvedEnv for guidance on picking a resolver.
327func (m MCPConfig) ResolvedArgs(r VariableResolver) ([]string, error) {
328 if len(m.Args) == 0 {
329 return nil, nil
330 }
331 out := make([]string, len(m.Args))
332 for i, a := range m.Args {
333 v, err := r.ResolveValue(a)
334 if err != nil {
335 return nil, fmt.Errorf("arg %d: %w", i, err)
336 }
337 out[i] = v
338 }
339 return out, nil
340}
341
342// ResolvedURL returns m.URL expanded through the given resolver. The
343// receiver is not mutated. Errors from the resolver are already
344// sanitized by ResolveValue and are wrapped with %w for errors.Is/As.
345//
346// URLs run through the same shell-expansion pipeline as the other
347// fields, so a literal '$' (e.g. OData query strings containing
348// $filter/$select) must be escaped as '\$' or '${DOLLAR:-$}' to avoid
349// being interpreted as a variable reference. Same constraint already
350// applies to command, args, env, and headers.
351//
352// See ResolvedEnv for guidance on picking a resolver.
353func (m MCPConfig) ResolvedURL(r VariableResolver) (string, error) {
354 if m.URL == "" {
355 return "", nil
356 }
357 v, err := r.ResolveValue(m.URL)
358 if err != nil {
359 return "", fmt.Errorf("url: %w", err)
360 }
361 return v, nil
362}
363
364// ResolvedHeaders returns m.Headers with every value expanded through
365// the given resolver. A fresh map is allocated; m.Headers is never
366// mutated. On the first resolution failure it returns nil and an error
367// identifying the offending header name; the inner resolver error is
368// already sanitized by ResolveValue and is wrapped with %w so
369// errors.Is/As continues to work.
370//
371// A header whose value resolves to the empty string (unset bare $VAR
372// under lenient nounset, $(echo), or literal "") is omitted from the
373// returned map — sending "X-Auth:" with an empty value is rejected by
374// some providers and the user's intent in "optional, env-gated
375// header" is clearly "absent when the var isn't set." See PLAN.md
376// Phase 2 design decision #18.
377//
378// See ResolvedEnv for guidance on picking a resolver.
379func (m MCPConfig) ResolvedHeaders(r VariableResolver) (map[string]string, error) {
380 if len(m.Headers) == 0 {
381 return map[string]string{}, nil
382 }
383 out := make(map[string]string, len(m.Headers))
384 // Sort keys so failures are reported deterministically when more
385 // than one header would fail.
386 keys := make([]string, 0, len(m.Headers))
387 for k := range m.Headers {
388 keys = append(keys, k)
389 }
390 slices.Sort(keys)
391 for _, k := range keys {
392 v, err := r.ResolveValue(m.Headers[k])
393 if err != nil {
394 return nil, fmt.Errorf("header %s: %w", k, err)
395 }
396 if v == "" {
397 continue
398 }
399 out[k] = v
400 }
401 return out, nil
402}
403
404type Agent struct {
405 ID string `json:"id,omitempty"`
406 Name string `json:"name,omitempty"`
407 Description string `json:"description,omitempty"`
408 // This is the id of the system prompt used by the agent
409 Disabled bool `json:"disabled,omitempty"`
410
411 Model SelectedModelType `json:"model" jsonschema:"required,description=The model type to use for this agent,enum=large,enum=small,default=large"`
412
413 // The available tools for the agent
414 // if this is nil, all tools are available
415 AllowedTools []string `json:"allowed_tools,omitempty"`
416
417 // this tells us which MCPs are available for this agent
418 // if this is empty all mcps are available
419 // the string array is the list of tools from the AllowedMCP the agent has available
420 // if the string array is nil, all tools from the AllowedMCP are available
421 AllowedMCP map[string][]string `json:"allowed_mcp,omitempty"`
422
423 // Overrides the context paths for this agent
424 ContextPaths []string `json:"context_paths,omitempty"`
425}
426
427type Tools struct {
428 Ls ToolLs `json:"ls,omitzero"`
429 Grep ToolGrep `json:"grep,omitzero"`
430}
431
432type ToolLs struct {
433 MaxDepth *int `json:"max_depth,omitempty" jsonschema:"description=Maximum depth for the ls tool,default=0,example=10"`
434 MaxItems *int `json:"max_items,omitempty" jsonschema:"description=Maximum number of items to return for the ls tool,default=1000,example=100"`
435}
436
437// Limits returns the user-defined max-depth and max-items, or their defaults.
438func (t ToolLs) Limits() (depth, items int) {
439 return ptrValOr(t.MaxDepth, 0), ptrValOr(t.MaxItems, 0)
440}
441
442type ToolGrep struct {
443 Timeout *time.Duration `json:"timeout,omitempty" jsonschema:"description=Timeout for the grep tool call,default=5s,example=10s"`
444}
445
446// GetTimeout returns the user-defined timeout or the default.
447func (t ToolGrep) GetTimeout() time.Duration {
448 return ptrValOr(t.Timeout, 5*time.Second)
449}
450
451// HookConfig defines a user-configured shell command that fires on a hook
452// event (e.g. PreToolUse). This is a pure-data struct: matcher compilation
453// is owned by hooks.Runner so a JSON round-trip, merge, or reload can't
454// silently drop compiled state.
455type HookConfig struct {
456 // Regex pattern tested against the tool name. Empty means match all.
457 Matcher string `json:"matcher,omitempty" jsonschema:"description=Regex pattern tested against the tool name. Empty means match all tools."`
458 // Shell command to execute.
459 Command string `json:"command" jsonschema:"required,description=Shell command to execute when the hook fires"`
460 // Timeout in seconds. Default 30.
461 Timeout int `json:"timeout,omitempty" jsonschema:"description=Timeout in seconds for the hook command,default=30"`
462}
463
464// TimeoutDuration returns the hook timeout as a time.Duration, defaulting
465// to 30s.
466func (h *HookConfig) TimeoutDuration() time.Duration {
467 if h.Timeout <= 0 {
468 return 30 * time.Second
469 }
470 return time.Duration(h.Timeout) * time.Second
471}
472
473// Config holds the configuration for crush.
474type Config struct {
475 Schema string `json:"$schema,omitempty"`
476
477 // We currently only support large/small as values here.
478 Models map[SelectedModelType]SelectedModel `json:"models,omitempty" jsonschema:"description=Model configurations for different model types,example={\"large\":{\"model\":\"gpt-4o\",\"provider\":\"openai\"}}"`
479
480 // Recently used models stored in the data directory config.
481 RecentModels map[SelectedModelType][]SelectedModel `json:"recent_models,omitempty" jsonschema:"-"`
482
483 // The providers that are configured
484 Providers *csync.Map[string, ProviderConfig] `json:"providers,omitempty" jsonschema:"description=AI provider configurations"`
485
486 MCP MCPs `json:"mcp,omitempty" jsonschema:"description=Model Context Protocol server configurations"`
487
488 LSP LSPs `json:"lsp,omitempty" jsonschema:"description=Language Server Protocol configurations"`
489
490 Options *Options `json:"options,omitempty" jsonschema:"description=General application options"`
491
492 Permissions *Permissions `json:"permissions,omitempty" jsonschema:"description=Permission settings for tool usage"`
493
494 Tools Tools `json:"tools,omitzero" jsonschema:"description=Tool configurations"`
495
496 Hooks map[string][]HookConfig `json:"hooks,omitempty" jsonschema:"description=User-defined shell commands that fire on hook events (e.g. PreToolUse)"`
497
498 Agents map[string]Agent `json:"-"`
499}
500
501func (c *Config) EnabledProviders() []ProviderConfig {
502 var enabled []ProviderConfig
503 for p := range c.Providers.Seq() {
504 if !p.Disable {
505 enabled = append(enabled, p)
506 }
507 }
508 return enabled
509}
510
511// IsConfigured return true if at least one provider is configured
512func (c *Config) IsConfigured() bool {
513 return len(c.EnabledProviders()) > 0
514}
515
516func (c *Config) GetModel(provider, model string) *catwalk.Model {
517 if providerConfig, ok := c.Providers.Get(provider); ok {
518 for _, m := range providerConfig.Models {
519 if m.ID == model {
520 return &m
521 }
522 }
523 }
524 return nil
525}
526
527func (c *Config) GetProviderForModel(modelType SelectedModelType) *ProviderConfig {
528 model, ok := c.Models[modelType]
529 if !ok {
530 return nil
531 }
532 if providerConfig, ok := c.Providers.Get(model.Provider); ok {
533 return &providerConfig
534 }
535 return nil
536}
537
538func (c *Config) GetModelByType(modelType SelectedModelType) *catwalk.Model {
539 model, ok := c.Models[modelType]
540 if !ok {
541 return nil
542 }
543 return c.GetModel(model.Provider, model.Model)
544}
545
546func (c *Config) LargeModel() *catwalk.Model {
547 model, ok := c.Models[SelectedModelTypeLarge]
548 if !ok {
549 return nil
550 }
551 return c.GetModel(model.Provider, model.Model)
552}
553
554func (c *Config) SmallModel() *catwalk.Model {
555 model, ok := c.Models[SelectedModelTypeSmall]
556 if !ok {
557 return nil
558 }
559 return c.GetModel(model.Provider, model.Model)
560}
561
562const maxRecentModelsPerType = 5
563
564func allToolNames() []string {
565 return []string{
566 "agent",
567 "bash",
568 "crush_info",
569 "crush_logs",
570 "job_output",
571 "job_kill",
572 "download",
573 "edit",
574 "multiedit",
575 "lsp_diagnostics",
576 "lsp_references",
577 "lsp_restart",
578 "fetch",
579 "agentic_fetch",
580 "glob",
581 "grep",
582 "ls",
583 "sourcegraph",
584 "todos",
585 "view",
586 "write",
587 "list_mcp_resources",
588 "read_mcp_resource",
589 }
590}
591
592func resolveAllowedTools(allTools []string, disabledTools []string) []string {
593 if disabledTools == nil {
594 return allTools
595 }
596 // filter out disabled tools (exclude mode)
597 return filterSlice(allTools, disabledTools, false)
598}
599
600func resolveReadOnlyTools(tools []string) []string {
601 readOnlyTools := []string{"glob", "grep", "ls", "sourcegraph", "view"}
602 // filter to only include tools that are in allowedtools (include mode)
603 return filterSlice(tools, readOnlyTools, true)
604}
605
606func filterSlice(data []string, mask []string, include bool) []string {
607 var filtered []string
608 for _, s := range data {
609 // if include is true, we include items that ARE in the mask
610 // if include is false, we include items that are NOT in the mask
611 if include == slices.Contains(mask, s) {
612 filtered = append(filtered, s)
613 }
614 }
615 return filtered
616}
617
618func (c *Config) SetupAgents() {
619 allowedTools := resolveAllowedTools(allToolNames(), c.Options.DisabledTools)
620
621 agents := map[string]Agent{
622 AgentCoder: {
623 ID: AgentCoder,
624 Name: "Coder",
625 Description: "An agent that helps with executing coding tasks.",
626 Model: SelectedModelTypeLarge,
627 ContextPaths: c.Options.ContextPaths,
628 AllowedTools: allowedTools,
629 },
630
631 AgentTask: {
632 ID: AgentTask,
633 Name: "Task",
634 Description: "An agent that helps with searching for context and finding implementation details.",
635 Model: SelectedModelTypeLarge,
636 ContextPaths: c.Options.ContextPaths,
637 AllowedTools: resolveReadOnlyTools(allowedTools),
638 // NO MCPs or LSPs by default
639 AllowedMCP: map[string][]string{},
640 },
641 }
642 c.Agents = agents
643}
644
645func (c *ProviderConfig) TestConnection(resolver VariableResolver) error {
646 var (
647 providerID = catwalk.InferenceProvider(c.ID)
648 testURL = ""
649 headers = make(map[string]string)
650 apiKey, _ = resolver.ResolveValue(c.APIKey)
651 )
652
653 switch providerID {
654 case catwalk.InferenceProviderMiniMax, catwalk.InferenceProviderMiniMaxChina:
655 // NOTE: MiniMax has no good endpoint we can use to validate the API key.
656 return nil
657 }
658
659 switch c.Type {
660 case catwalk.TypeOpenAI, catwalk.TypeOpenAICompat, catwalk.TypeOpenRouter:
661 baseURL, _ := resolver.ResolveValue(c.BaseURL)
662 baseURL = cmp.Or(baseURL, "https://api.openai.com/v1")
663
664 switch providerID {
665 case catwalk.InferenceProviderOpenRouter:
666 testURL = baseURL + "/credits"
667 case catwalk.InferenceProviderOpenCodeGo:
668 testURL = strings.Replace(baseURL, "/go", "", 1) + "/models"
669 default:
670 testURL = baseURL + "/models"
671 }
672
673 headers["Authorization"] = "Bearer " + apiKey
674 case catwalk.TypeAnthropic:
675 baseURL, _ := resolver.ResolveValue(c.BaseURL)
676 baseURL = cmp.Or(baseURL, "https://api.anthropic.com/v1")
677
678 switch providerID {
679 case catwalk.InferenceKimiCoding:
680 testURL = baseURL + "/v1/models"
681 default:
682 testURL = baseURL + "/models"
683 }
684
685 headers["x-api-key"] = apiKey
686 headers["anthropic-version"] = "2023-06-01"
687 case catwalk.TypeGoogle:
688 baseURL, _ := resolver.ResolveValue(c.BaseURL)
689 baseURL = cmp.Or(baseURL, "https://generativelanguage.googleapis.com")
690 testURL = baseURL + "/v1beta/models?key=" + url.QueryEscape(apiKey)
691 case catwalk.TypeBedrock:
692 // NOTE: Bedrock has a `/foundation-models` endpoint that we could in
693 // theory use, but apparently the authorization is region-specific,
694 // so it's not so trivial.
695 if strings.HasPrefix(apiKey, "ABSK") { // Bedrock API keys
696 return nil
697 }
698 return errors.New("not a valid bedrock api key")
699 case catwalk.TypeVercel:
700 // NOTE: Vercel does not validate API keys on the `/models` endpoint.
701 if strings.HasPrefix(apiKey, "vck_") { // Vercel API keys
702 return nil
703 }
704 return errors.New("not a valid vercel api key")
705 }
706
707 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
708 defer cancel()
709
710 client := &http.Client{}
711 req, err := http.NewRequestWithContext(ctx, "GET", testURL, nil)
712 if err != nil {
713 return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
714 }
715 for k, v := range headers {
716 req.Header.Set(k, v)
717 }
718 for k, v := range c.ExtraHeaders {
719 req.Header.Set(k, v)
720 }
721
722 resp, err := client.Do(req)
723 if err != nil {
724 return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
725 }
726 defer resp.Body.Close()
727
728 switch providerID {
729 case catwalk.InferenceProviderZAI:
730 if resp.StatusCode == http.StatusUnauthorized {
731 return fmt.Errorf("failed to connect to provider %s: %s", c.ID, resp.Status)
732 }
733 default:
734 if resp.StatusCode != http.StatusOK {
735 return fmt.Errorf("failed to connect to provider %s: %s", c.ID, resp.Status)
736 }
737 }
738 return nil
739}
740
741// resolveEnvs expands every value in envs through the given resolver
742// and returns a fresh "KEY=value" slice sorted by key. The input map is
743// not mutated. On the first resolution failure it returns nil and an
744// error identifying the offending variable; the inner resolver error is
745// already sanitized by ResolveValue and is wrapped with %w.
746func resolveEnvs(envs map[string]string, r VariableResolver) ([]string, error) {
747 if len(envs) == 0 {
748 return nil, nil
749 }
750 keys := make([]string, 0, len(envs))
751 for k := range envs {
752 keys = append(keys, k)
753 }
754 slices.Sort(keys)
755 res := make([]string, 0, len(envs))
756 for _, k := range keys {
757 v, err := r.ResolveValue(envs[k])
758 if err != nil {
759 return nil, fmt.Errorf("env %s: %w", k, err)
760 }
761 res = append(res, fmt.Sprintf("%s=%s", k, v))
762 }
763 return res, nil
764}
765
766func ptrValOr[T any](t *T, el T) T {
767 if t == nil {
768 return el
769 }
770 return *t
771}