config.go

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