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