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