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