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