config.go

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