config.go

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