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"`
103
104 // Used to pass extra parameters to the provider.
105 ExtraParams map[string]string `json:"-"`
106
107 // The provider models
108 Models []catwalk.Model `json:"models,omitempty" jsonschema:"description=List of models available from this provider"`
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 // Overrides the context paths for this agent
268 ContextPaths []string `json:"context_paths,omitempty"`
269}
270
271type Tools struct {
272 Ls ToolLs `json:"ls,omitzero"`
273}
274
275type ToolLs struct {
276 MaxDepth *int `json:"max_depth,omitempty" jsonschema:"description=Maximum depth for the ls tool,default=0,example=10"`
277 MaxItems *int `json:"max_items,omitempty" jsonschema:"description=Maximum number of items to return for the ls tool,default=1000,example=100"`
278}
279
280func (t ToolLs) Limits() (depth, items int) {
281 return ptrValOr(t.MaxDepth, -1), ptrValOr(t.MaxItems, -1)
282}
283
284// Config holds the configuration for crush.
285type Config struct {
286 Schema string `json:"$schema,omitempty"`
287
288 // We currently only support large/small as values here.
289 Models map[SelectedModelType]SelectedModel `json:"models,omitempty" jsonschema:"description=Model configurations for different model types,example={\"large\":{\"model\":\"gpt-4o\",\"provider\":\"openai\"}}"`
290
291 // The providers that are configured
292 Providers *csync.Map[string, ProviderConfig] `json:"providers,omitempty" jsonschema:"description=AI provider configurations"`
293
294 MCP MCPs `json:"mcp,omitempty" jsonschema:"description=Model Context Protocol server configurations"`
295
296 LSP LSPs `json:"lsp,omitempty" jsonschema:"description=Language Server Protocol configurations"`
297
298 Options *Options `json:"options,omitempty" jsonschema:"description=General application options"`
299
300 Permissions *Permissions `json:"permissions,omitempty" jsonschema:"description=Permission settings for tool usage"`
301
302 Tools Tools `json:"tools,omitzero" jsonschema:"description=Tool configurations"`
303
304 // Internal
305 workingDir string `json:"-"`
306 // TODO: most likely remove this concept when I come back to it
307 Agents map[string]Agent `json:"-"`
308 // TODO: find a better way to do this this should probably not be part of the config
309 resolver VariableResolver
310 dataConfigDir string `json:"-"`
311 knownProviders []catwalk.Provider `json:"-"`
312}
313
314func (c *Config) WorkingDir() string {
315 return c.workingDir
316}
317
318func (c *Config) EnabledProviders() []ProviderConfig {
319 var enabled []ProviderConfig
320 for p := range c.Providers.Seq() {
321 if !p.Disable {
322 enabled = append(enabled, p)
323 }
324 }
325 return enabled
326}
327
328// IsConfigured return true if at least one provider is configured
329func (c *Config) IsConfigured() bool {
330 return len(c.EnabledProviders()) > 0
331}
332
333func (c *Config) GetModel(provider, model string) *catwalk.Model {
334 if providerConfig, ok := c.Providers.Get(provider); ok {
335 for _, m := range providerConfig.Models {
336 if m.ID == model {
337 return &m
338 }
339 }
340 }
341 return nil
342}
343
344func (c *Config) GetProviderForModel(modelType SelectedModelType) *ProviderConfig {
345 model, ok := c.Models[modelType]
346 if !ok {
347 return nil
348 }
349 if providerConfig, ok := c.Providers.Get(model.Provider); ok {
350 return &providerConfig
351 }
352 return nil
353}
354
355func (c *Config) GetModelByType(modelType SelectedModelType) *catwalk.Model {
356 model, ok := c.Models[modelType]
357 if !ok {
358 return nil
359 }
360 return c.GetModel(model.Provider, model.Model)
361}
362
363func (c *Config) LargeModel() *catwalk.Model {
364 model, ok := c.Models[SelectedModelTypeLarge]
365 if !ok {
366 return nil
367 }
368 return c.GetModel(model.Provider, model.Model)
369}
370
371func (c *Config) SmallModel() *catwalk.Model {
372 model, ok := c.Models[SelectedModelTypeSmall]
373 if !ok {
374 return nil
375 }
376 return c.GetModel(model.Provider, model.Model)
377}
378
379func (c *Config) SetCompactMode(enabled bool) error {
380 if c.Options == nil {
381 c.Options = &Options{}
382 }
383 c.Options.TUI.CompactMode = enabled
384 return c.SetConfigField("options.tui.compact_mode", enabled)
385}
386
387func (c *Config) Resolve(key string) (string, error) {
388 if c.resolver == nil {
389 return "", fmt.Errorf("no variable resolver configured")
390 }
391 return c.resolver.ResolveValue(key)
392}
393
394func (c *Config) UpdatePreferredModel(modelType SelectedModelType, model SelectedModel) error {
395 c.Models[modelType] = model
396 if err := c.SetConfigField(fmt.Sprintf("models.%s", modelType), model); err != nil {
397 return fmt.Errorf("failed to update preferred model: %w", err)
398 }
399 return nil
400}
401
402func (c *Config) SetConfigField(key string, value any) error {
403 // read the data
404 data, err := os.ReadFile(c.dataConfigDir)
405 if err != nil {
406 if os.IsNotExist(err) {
407 data = []byte("{}")
408 } else {
409 return fmt.Errorf("failed to read config file: %w", err)
410 }
411 }
412
413 newValue, err := sjson.Set(string(data), key, value)
414 if err != nil {
415 return fmt.Errorf("failed to set config field %s: %w", key, err)
416 }
417 if err := os.WriteFile(c.dataConfigDir, []byte(newValue), 0o600); err != nil {
418 return fmt.Errorf("failed to write config file: %w", err)
419 }
420 return nil
421}
422
423func (c *Config) SetProviderAPIKey(providerID, apiKey string) error {
424 // First save to the config file
425 err := c.SetConfigField("providers."+providerID+".api_key", apiKey)
426 if err != nil {
427 return fmt.Errorf("failed to save API key to config file: %w", err)
428 }
429
430 providerConfig, exists := c.Providers.Get(providerID)
431 if exists {
432 providerConfig.APIKey = apiKey
433 c.Providers.Set(providerID, providerConfig)
434 return nil
435 }
436
437 var foundProvider *catwalk.Provider
438 for _, p := range c.knownProviders {
439 if string(p.ID) == providerID {
440 foundProvider = &p
441 break
442 }
443 }
444
445 if foundProvider != nil {
446 // Create new provider config based on known provider
447 providerConfig = ProviderConfig{
448 ID: providerID,
449 Name: foundProvider.Name,
450 BaseURL: foundProvider.APIEndpoint,
451 Type: foundProvider.Type,
452 APIKey: apiKey,
453 Disable: false,
454 ExtraHeaders: make(map[string]string),
455 ExtraParams: make(map[string]string),
456 Models: foundProvider.Models,
457 }
458 } else {
459 return fmt.Errorf("provider with ID %s not found in known providers", providerID)
460 }
461 // Store the updated provider config
462 c.Providers.Set(providerID, providerConfig)
463 return nil
464}
465
466func allToolNames() []string {
467 return []string{
468 "agent",
469 "bash",
470 "download",
471 "edit",
472 "multiedit",
473 "fetch",
474 "glob",
475 "grep",
476 "ls",
477 "sourcegraph",
478 "view",
479 "write",
480 }
481}
482
483func resolveAllowedTools(allTools []string, disabledTools []string) []string {
484 if disabledTools == nil {
485 return allTools
486 }
487 // filter out disabled tools (exclude mode)
488 return filterSlice(allTools, disabledTools, false)
489}
490
491func resolveReadOnlyTools(tools []string) []string {
492 readOnlyTools := []string{"glob", "grep", "ls", "sourcegraph", "view"}
493 // filter to only include tools that are in allowedtools (include mode)
494 return filterSlice(tools, readOnlyTools, true)
495}
496
497func filterSlice(data []string, mask []string, include bool) []string {
498 filtered := []string{}
499 for _, s := range data {
500 // if include is true, we include items that ARE in the mask
501 // if include is false, we include items that are NOT in the mask
502 if include == slices.Contains(mask, s) {
503 filtered = append(filtered, s)
504 }
505 }
506 return filtered
507}
508
509func (c *Config) SetupAgents() {
510 allowedTools := resolveAllowedTools(allToolNames(), c.Options.DisabledTools)
511
512 agents := map[string]Agent{
513 AgentCoder: {
514 ID: AgentCoder,
515 Name: "Coder",
516 Description: "An agent that helps with executing coding tasks.",
517 Model: SelectedModelTypeLarge,
518 ContextPaths: c.Options.ContextPaths,
519 AllowedTools: allowedTools,
520 },
521
522 AgentTask: {
523 ID: AgentCoder,
524 Name: "Task",
525 Description: "An agent that helps with searching for context and finding implementation details.",
526 Model: SelectedModelTypeLarge,
527 ContextPaths: c.Options.ContextPaths,
528 AllowedTools: resolveReadOnlyTools(allowedTools),
529 // NO MCPs or LSPs by default
530 AllowedMCP: map[string][]string{},
531 },
532 }
533 c.Agents = agents
534}
535
536func (c *Config) Resolver() VariableResolver {
537 return c.resolver
538}
539
540func (c *ProviderConfig) TestConnection(resolver VariableResolver) error {
541 testURL := ""
542 headers := make(map[string]string)
543 apiKey, _ := resolver.ResolveValue(c.APIKey)
544 switch c.Type {
545 case catwalk.TypeOpenAI:
546 baseURL, _ := resolver.ResolveValue(c.BaseURL)
547 if baseURL == "" {
548 baseURL = "https://api.openai.com/v1"
549 }
550 if c.ID == string(catwalk.InferenceProviderOpenRouter) {
551 testURL = baseURL + "/credits"
552 } else {
553 testURL = baseURL + "/models"
554 }
555 headers["Authorization"] = "Bearer " + apiKey
556 case catwalk.TypeAnthropic:
557 baseURL, _ := resolver.ResolveValue(c.BaseURL)
558 if baseURL == "" {
559 baseURL = "https://api.anthropic.com/v1"
560 }
561 testURL = baseURL + "/models"
562 headers["x-api-key"] = apiKey
563 headers["anthropic-version"] = "2023-06-01"
564 case catwalk.TypeGoogle:
565 baseURL, _ := resolver.ResolveValue(c.BaseURL)
566 if baseURL == "" {
567 baseURL = "https://generativelanguage.googleapis.com"
568 }
569 testURL = baseURL + "/v1beta/models?key=" + url.QueryEscape(apiKey)
570 }
571 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
572 defer cancel()
573 client := &http.Client{}
574 req, err := http.NewRequestWithContext(ctx, "GET", testURL, nil)
575 if err != nil {
576 return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
577 }
578 for k, v := range headers {
579 req.Header.Set(k, v)
580 }
581 for k, v := range c.ExtraHeaders {
582 req.Header.Set(k, v)
583 }
584 b, err := client.Do(req)
585 if err != nil {
586 return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
587 }
588 if c.ID == string(catwalk.InferenceProviderZAI) {
589 if b.StatusCode == http.StatusUnauthorized {
590 // for z.ai just check if the http response is not 401
591 return fmt.Errorf("failed to connect to provider %s: %s", c.ID, b.Status)
592 }
593 } else {
594 if b.StatusCode != http.StatusOK {
595 return fmt.Errorf("failed to connect to provider %s: %s", c.ID, b.Status)
596 }
597 }
598 _ = b.Body.Close()
599 return nil
600}
601
602func resolveEnvs(envs map[string]string) []string {
603 resolver := NewShellVariableResolver(env.New())
604 for e, v := range envs {
605 var err error
606 envs[e], err = resolver.ResolveValue(v)
607 if err != nil {
608 slog.Error("error resolving environment variable", "error", err, "variable", e, "value", v)
609 continue
610 }
611 }
612
613 res := make([]string, 0, len(envs))
614 for k, v := range envs {
615 res = append(res, fmt.Sprintf("%s=%s", k, v))
616 }
617 return res
618}
619
620func ptrValOr[T any](t *T, el T) T {
621 if t == nil {
622 return el
623 }
624 return *t
625}