config.go

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