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