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