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