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