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