config.go

  1package config
  2
  3import (
  4	"cmp"
  5	"context"
  6	"fmt"
  7	"log/slog"
  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 (pc *ProviderConfig) ToProvider() catwalk.Provider {
128	// Convert config provider to provider.Provider format
129	provider := catwalk.Provider{
130		Name:   pc.Name,
131		ID:     catwalk.InferenceProvider(pc.ID),
132		Models: make([]catwalk.Model, len(pc.Models)),
133	}
134
135	// Convert models
136	for i, model := range pc.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 (pc *ProviderConfig) SetupGitHubCopilot() {
157	maps.Copy(pc.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"` // Tools that don't require permission prompts
216	SkipRequests bool     `json:"-"`                                                                                                                              // Automatically accept all permissions (YOLO mode)
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}
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
303func (l LSPConfig) ResolvedEnv() []string {
304	return resolveEnvs(l.Env)
305}
306
307func (m MCPConfig) ResolvedEnv() []string {
308	return resolveEnvs(m.Env)
309}
310
311func (m MCPConfig) ResolvedHeaders() map[string]string {
312	resolver := NewShellVariableResolver(env.New())
313	for e, v := range m.Headers {
314		var err error
315		m.Headers[e], err = resolver.ResolveValue(v)
316		if err != nil {
317			slog.Error("Error resolving header variable", "error", err, "variable", e, "value", v)
318			continue
319		}
320	}
321	return m.Headers
322}
323
324type Agent struct {
325	ID          string `json:"id,omitempty"`
326	Name        string `json:"name,omitempty"`
327	Description string `json:"description,omitempty"`
328	// This is the id of the system prompt used by the agent
329	Disabled bool `json:"disabled,omitempty"`
330
331	Model SelectedModelType `json:"model" jsonschema:"required,description=The model type to use for this agent,enum=large,enum=small,default=large"`
332
333	// The available tools for the agent
334	//  if this is nil, all tools are available
335	AllowedTools []string `json:"allowed_tools,omitempty"`
336
337	// this tells us which MCPs are available for this agent
338	//  if this is empty all mcps are available
339	//  the string array is the list of tools from the AllowedMCP the agent has available
340	//  if the string array is nil, all tools from the AllowedMCP are available
341	AllowedMCP map[string][]string `json:"allowed_mcp,omitempty"`
342
343	// Overrides the context paths for this agent
344	ContextPaths []string `json:"context_paths,omitempty"`
345}
346
347type Tools struct {
348	Ls   ToolLs   `json:"ls,omitzero"`
349	Grep ToolGrep `json:"grep,omitzero"`
350}
351
352type ToolLs struct {
353	MaxDepth *int `json:"max_depth,omitempty" jsonschema:"description=Maximum depth for the ls tool,default=0,example=10"`
354	MaxItems *int `json:"max_items,omitempty" jsonschema:"description=Maximum number of items to return for the ls tool,default=1000,example=100"`
355}
356
357// Limits returns the user-defined max-depth and max-items, or their defaults.
358func (t ToolLs) Limits() (depth, items int) {
359	return ptrValOr(t.MaxDepth, 0), ptrValOr(t.MaxItems, 0)
360}
361
362type ToolGrep struct {
363	Timeout *time.Duration `json:"timeout,omitempty" jsonschema:"description=Timeout for the grep tool call,default=5s,example=10s"`
364}
365
366// GetTimeout returns the user-defined timeout or the default.
367func (t ToolGrep) GetTimeout() time.Duration {
368	return ptrValOr(t.Timeout, 5*time.Second)
369}
370
371// Config holds the configuration for crush.
372type Config struct {
373	Schema string `json:"$schema,omitempty"`
374
375	// We currently only support large/small as values here.
376	Models map[SelectedModelType]SelectedModel `json:"models,omitempty" jsonschema:"description=Model configurations for different model types,example={\"large\":{\"model\":\"gpt-4o\",\"provider\":\"openai\"}}"`
377
378	// Recently used models stored in the data directory config.
379	RecentModels map[SelectedModelType][]SelectedModel `json:"recent_models,omitempty" jsonschema:"-"`
380
381	// The providers that are configured
382	Providers *csync.Map[string, ProviderConfig] `json:"providers,omitempty" jsonschema:"description=AI provider configurations"`
383
384	MCP MCPs `json:"mcp,omitempty" jsonschema:"description=Model Context Protocol server configurations"`
385
386	LSP LSPs `json:"lsp,omitempty" jsonschema:"description=Language Server Protocol configurations"`
387
388	Options *Options `json:"options,omitempty" jsonschema:"description=General application options"`
389
390	Permissions *Permissions `json:"permissions,omitempty" jsonschema:"description=Permission settings for tool usage"`
391
392	Tools Tools `json:"tools,omitzero" jsonschema:"description=Tool configurations"`
393
394	Agents map[string]Agent `json:"-"`
395}
396
397func (c *Config) EnabledProviders() []ProviderConfig {
398	var enabled []ProviderConfig
399	for p := range c.Providers.Seq() {
400		if !p.Disable {
401			enabled = append(enabled, p)
402		}
403	}
404	return enabled
405}
406
407// IsConfigured  return true if at least one provider is configured
408func (c *Config) IsConfigured() bool {
409	return len(c.EnabledProviders()) > 0
410}
411
412func (c *Config) GetModel(provider, model string) *catwalk.Model {
413	if providerConfig, ok := c.Providers.Get(provider); ok {
414		for _, m := range providerConfig.Models {
415			if m.ID == model {
416				return &m
417			}
418		}
419	}
420	return nil
421}
422
423func (c *Config) GetProviderForModel(modelType SelectedModelType) *ProviderConfig {
424	model, ok := c.Models[modelType]
425	if !ok {
426		return nil
427	}
428	if providerConfig, ok := c.Providers.Get(model.Provider); ok {
429		return &providerConfig
430	}
431	return nil
432}
433
434func (c *Config) GetModelByType(modelType SelectedModelType) *catwalk.Model {
435	model, ok := c.Models[modelType]
436	if !ok {
437		return nil
438	}
439	return c.GetModel(model.Provider, model.Model)
440}
441
442func (c *Config) LargeModel() *catwalk.Model {
443	model, ok := c.Models[SelectedModelTypeLarge]
444	if !ok {
445		return nil
446	}
447	return c.GetModel(model.Provider, model.Model)
448}
449
450func (c *Config) SmallModel() *catwalk.Model {
451	model, ok := c.Models[SelectedModelTypeSmall]
452	if !ok {
453		return nil
454	}
455	return c.GetModel(model.Provider, model.Model)
456}
457
458const maxRecentModelsPerType = 5
459
460func allToolNames() []string {
461	return []string{
462		"agent",
463		"bash",
464		"job_output",
465		"job_kill",
466		"download",
467		"edit",
468		"multiedit",
469		"lsp_diagnostics",
470		"lsp_references",
471		"lsp_restart",
472		"fetch",
473		"agentic_fetch",
474		"glob",
475		"grep",
476		"ls",
477		"sourcegraph",
478		"todos",
479		"view",
480		"write",
481		"list_mcp_resources",
482		"read_mcp_resource",
483	}
484}
485
486func resolveAllowedTools(allTools []string, disabledTools []string) []string {
487	if disabledTools == nil {
488		return allTools
489	}
490	// filter out disabled tools (exclude mode)
491	return filterSlice(allTools, disabledTools, false)
492}
493
494func resolveReadOnlyTools(tools []string) []string {
495	readOnlyTools := []string{"glob", "grep", "ls", "sourcegraph", "view"}
496	// filter to only include tools that are in allowedtools (include mode)
497	return filterSlice(tools, readOnlyTools, true)
498}
499
500func filterSlice(data []string, mask []string, include bool) []string {
501	var filtered []string
502	for _, s := range data {
503		// if include is true, we include items that ARE in the mask
504		// if include is false, we include items that are NOT in the mask
505		if include == slices.Contains(mask, s) {
506			filtered = append(filtered, s)
507		}
508	}
509	return filtered
510}
511
512func (c *Config) SetupAgents() {
513	allowedTools := resolveAllowedTools(allToolNames(), c.Options.DisabledTools)
514
515	agents := map[string]Agent{
516		AgentCoder: {
517			ID:           AgentCoder,
518			Name:         "Coder",
519			Description:  "An agent that helps with executing coding tasks.",
520			Model:        SelectedModelTypeLarge,
521			ContextPaths: c.Options.ContextPaths,
522			AllowedTools: allowedTools,
523		},
524
525		AgentTask: {
526			ID:           AgentTask,
527			Name:         "Task",
528			Description:  "An agent that helps with searching for context and finding implementation details.",
529			Model:        SelectedModelTypeLarge,
530			ContextPaths: c.Options.ContextPaths,
531			AllowedTools: resolveReadOnlyTools(allowedTools),
532			// NO MCPs or LSPs by default
533			AllowedMCP: map[string][]string{},
534		},
535	}
536	c.Agents = agents
537}
538
539func (c *ProviderConfig) TestConnection(resolver VariableResolver) error {
540	var (
541		providerID = catwalk.InferenceProvider(c.ID)
542		testURL    = ""
543		headers    = make(map[string]string)
544		apiKey, _  = resolver.ResolveValue(c.APIKey)
545	)
546
547	switch providerID {
548	case catwalk.InferenceProviderMiniMax, catwalk.InferenceProviderMiniMaxChina:
549		// NOTE: MiniMax has no good endpoint we can use to validate the API key.
550		// Let's at least check the pattern.
551		if !strings.HasPrefix(apiKey, "sk-") {
552			return fmt.Errorf("invalid API key format for provider %s", c.ID)
553		}
554		return nil
555	}
556
557	switch c.Type {
558	case catwalk.TypeOpenAI, catwalk.TypeOpenAICompat, catwalk.TypeOpenRouter:
559		baseURL, _ := resolver.ResolveValue(c.BaseURL)
560		baseURL = cmp.Or(baseURL, "https://api.openai.com/v1")
561
562		switch providerID {
563		case catwalk.InferenceProviderOpenRouter:
564			testURL = baseURL + "/credits"
565		default:
566			testURL = baseURL + "/models"
567		}
568
569		headers["Authorization"] = "Bearer " + apiKey
570	case catwalk.TypeAnthropic:
571		baseURL, _ := resolver.ResolveValue(c.BaseURL)
572		baseURL = cmp.Or(baseURL, "https://api.anthropic.com/v1")
573
574		switch providerID {
575		case catwalk.InferenceKimiCoding:
576			testURL = baseURL + "/v1/models"
577		default:
578			testURL = baseURL + "/models"
579		}
580
581		headers["x-api-key"] = apiKey
582		headers["anthropic-version"] = "2023-06-01"
583	case catwalk.TypeGoogle:
584		baseURL, _ := resolver.ResolveValue(c.BaseURL)
585		baseURL = cmp.Or(baseURL, "https://generativelanguage.googleapis.com")
586		testURL = baseURL + "/v1beta/models?key=" + url.QueryEscape(apiKey)
587	}
588
589	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
590	defer cancel()
591
592	client := &http.Client{}
593	req, err := http.NewRequestWithContext(ctx, "GET", testURL, nil)
594	if err != nil {
595		return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
596	}
597	for k, v := range headers {
598		req.Header.Set(k, v)
599	}
600	for k, v := range c.ExtraHeaders {
601		req.Header.Set(k, v)
602	}
603
604	resp, err := client.Do(req)
605	if err != nil {
606		return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
607	}
608	defer resp.Body.Close()
609
610	switch providerID {
611	case catwalk.InferenceProviderZAI:
612		if resp.StatusCode == http.StatusUnauthorized {
613			return fmt.Errorf("failed to connect to provider %s: %s", c.ID, resp.Status)
614		}
615	default:
616		if resp.StatusCode != http.StatusOK {
617			return fmt.Errorf("failed to connect to provider %s: %s", c.ID, resp.Status)
618		}
619	}
620	return nil
621}
622
623func resolveEnvs(envs map[string]string) []string {
624	resolver := NewShellVariableResolver(env.New())
625	for e, v := range envs {
626		var err error
627		envs[e], err = resolver.ResolveValue(v)
628		if err != nil {
629			slog.Error("Error resolving environment variable", "error", err, "variable", e, "value", v)
630			continue
631		}
632	}
633
634	res := make([]string, 0, len(envs))
635	for k, v := range envs {
636		res = append(res, fmt.Sprintf("%s=%s", k, v))
637	}
638	return res
639}
640
641func ptrValOr[T any](t *T, el T) T {
642	if t == nil {
643		return el
644	}
645	return *t
646}