config.go

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