config.go

  1package config
  2
  3import (
  4	"cmp"
  5	"context"
  6	"errors"
  7	"fmt"
  8	"maps"
  9	"net/http"
 10	"net/url"
 11	"slices"
 12	"strings"
 13	"time"
 14
 15	"charm.land/catwalk/pkg/catwalk"
 16	"github.com/charmbracelet/crush/internal/csync"
 17	"github.com/charmbracelet/crush/internal/oauth"
 18	"github.com/charmbracelet/crush/internal/oauth/copilot"
 19	"github.com/invopop/jsonschema"
 20)
 21
 22const (
 23	appName              = "crush"
 24	defaultDataDirectory = ".crush"
 25	defaultInitializeAs  = "AGENTS.md"
 26)
 27
 28var defaultContextPaths = []string{
 29	".github/copilot-instructions.md",
 30	".cursorrules",
 31	".cursor/rules/",
 32	"CLAUDE.md",
 33	"CLAUDE.local.md",
 34	"GEMINI.md",
 35	"gemini.md",
 36	"crush.md",
 37	"crush.local.md",
 38	"Crush.md",
 39	"Crush.local.md",
 40	"CRUSH.md",
 41	"CRUSH.local.md",
 42	"AGENTS.md",
 43	"agents.md",
 44	"Agents.md",
 45}
 46
 47type SelectedModelType string
 48
 49// String returns the string representation of the [SelectedModelType].
 50func (s SelectedModelType) String() string {
 51	return string(s)
 52}
 53
 54const (
 55	SelectedModelTypeLarge SelectedModelType = "large"
 56	SelectedModelTypeSmall SelectedModelType = "small"
 57)
 58
 59const (
 60	AgentCoder string = "coder"
 61	AgentTask  string = "task"
 62)
 63
 64type SelectedModel struct {
 65	// The model id as used by the provider API.
 66	// Required.
 67	Model string `json:"model" jsonschema:"required,description=The model ID as used by the provider API,example=gpt-4o"`
 68	// The model provider, same as the key/id used in the providers config.
 69	// Required.
 70	Provider string `json:"provider" jsonschema:"required,description=The model provider ID that matches a key in the providers config,example=openai"`
 71
 72	// Only used by models that use the openai provider and need this set.
 73	ReasoningEffort string `json:"reasoning_effort,omitempty" jsonschema:"description=Reasoning effort level for OpenAI models that support it,enum=low,enum=medium,enum=high"`
 74
 75	// Used by anthropic models that can reason to indicate if the model should think.
 76	Think bool `json:"think,omitempty" jsonschema:"description=Enable thinking mode for Anthropic models that support reasoning"`
 77
 78	// Overrides the default model configuration.
 79	MaxTokens        int64    `json:"max_tokens,omitempty" jsonschema:"description=Maximum number of tokens for model responses,maximum=200000,example=4096"`
 80	Temperature      *float64 `json:"temperature,omitempty" jsonschema:"description=Sampling temperature,minimum=0,maximum=1,example=0.7"`
 81	TopP             *float64 `json:"top_p,omitempty" jsonschema:"description=Top-p (nucleus) sampling parameter,minimum=0,maximum=1,example=0.9"`
 82	TopK             *int64   `json:"top_k,omitempty" jsonschema:"description=Top-k sampling parameter"`
 83	FrequencyPenalty *float64 `json:"frequency_penalty,omitempty" jsonschema:"description=Frequency penalty to reduce repetition"`
 84	PresencePenalty  *float64 `json:"presence_penalty,omitempty" jsonschema:"description=Presence penalty to increase topic diversity"`
 85
 86	// Override provider specific options.
 87	ProviderOptions map[string]any `json:"provider_options,omitempty" jsonschema:"description=Additional provider-specific options for the model"`
 88}
 89
 90type ProviderConfig struct {
 91	// The provider's id.
 92	ID string `json:"id,omitempty" jsonschema:"description=Unique identifier for the provider,example=openai"`
 93	// The provider's name, used for display purposes.
 94	Name string `json:"name,omitempty" jsonschema:"description=Human-readable name for the provider,example=OpenAI"`
 95	// The provider's API endpoint.
 96	BaseURL string `json:"base_url,omitempty" jsonschema:"description=Base URL for the provider's API,format=uri,example=https://api.openai.com/v1"`
 97	// The provider type, e.g. "openai", "anthropic", etc. if empty it defaults to openai.
 98	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"`
 99	// The provider's API key.
100	APIKey string `json:"api_key,omitempty" jsonschema:"description=API key for authentication with the provider,example=$OPENAI_API_KEY"`
101	// The original API key template before resolution (for re-resolution on auth errors).
102	APIKeyTemplate string `json:"-"`
103	// OAuthToken for providers that use OAuth2 authentication.
104	OAuthToken *oauth.Token `json:"oauth,omitempty" jsonschema:"description=OAuth2 token for authentication with the provider"`
105	// Marks the provider as disabled.
106	Disable bool `json:"disable,omitempty" jsonschema:"description=Whether this provider is disabled,default=false"`
107
108	// Custom system prompt prefix.
109	SystemPromptPrefix string `json:"system_prompt_prefix,omitempty" jsonschema:"description=Custom prefix to add to system prompts for this provider"`
110
111	// Extra headers to send with each request to the provider. Values
112	// run through shell expansion at config-load time, so $VAR and
113	// $(cmd) work the same way they do in MCP headers. A header whose
114	// value resolves to the empty string (unset bare $VAR under
115	// lenient nounset, $(echo), or literal "") is omitted from the
116	// outgoing request rather than sent as "Header:".
117	ExtraHeaders map[string]string `json:"extra_headers,omitempty" jsonschema:"description=Additional HTTP headers to send with requests"`
118	// ExtraBody is merged verbatim into OpenAI-compatible request
119	// bodies. String values are NOT shell-expanded: this is a plain
120	// JSON passthrough so that arbitrary provider-extension fields
121	// (numbers, nested objects, booleans) round-trip without a
122	// recursive walker guessing at intent. If you need an env-var-
123	// driven value at request time, put it in extra_headers, or in
124	// the provider's top-level api_key / base_url, all of which do
125	// expand.
126	ExtraBody map[string]any `json:"extra_body,omitempty" jsonschema:"description=Additional fields to include in request bodies\\, only works with openai-compatible providers"`
127
128	ProviderOptions map[string]any `json:"provider_options,omitempty" jsonschema:"description=Additional provider-specific options for this provider"`
129
130	// Used to pass extra parameters to the provider.
131	ExtraParams map[string]string `json:"-"`
132
133	// Skip cost accumulation for this provider when using subscription or flat rate billing.
134	FlatRate bool `json:"flat_rate,omitempty" jsonschema:"description=Flat-rate mode for this provider"`
135
136	// The provider models
137	Models []catwalk.Model `json:"models,omitempty" jsonschema:"description=List of models available from this provider"`
138}
139
140// ToProvider converts the [ProviderConfig] to a [catwalk.Provider].
141func (c *ProviderConfig) ToProvider() catwalk.Provider {
142	// Convert config provider to provider.Provider format
143	provider := catwalk.Provider{
144		Name:   c.Name,
145		ID:     catwalk.InferenceProvider(c.ID),
146		Models: make([]catwalk.Model, len(c.Models)),
147	}
148
149	// Convert models
150	for i, model := range c.Models {
151		provider.Models[i] = catwalk.Model{
152			ID:                     model.ID,
153			Name:                   model.Name,
154			CostPer1MIn:            model.CostPer1MIn,
155			CostPer1MOut:           model.CostPer1MOut,
156			CostPer1MInCached:      model.CostPer1MInCached,
157			CostPer1MOutCached:     model.CostPer1MOutCached,
158			ContextWindow:          model.ContextWindow,
159			DefaultMaxTokens:       model.DefaultMaxTokens,
160			CanReason:              model.CanReason,
161			ReasoningLevels:        model.ReasoningLevels,
162			DefaultReasoningEffort: model.DefaultReasoningEffort,
163			SupportsImages:         model.SupportsImages,
164		}
165	}
166
167	return provider
168}
169
170func (c *ProviderConfig) SetupGitHubCopilot() {
171	maps.Copy(c.ExtraHeaders, copilot.Headers())
172}
173
174type MCPType string
175
176const (
177	MCPStdio MCPType = "stdio"
178	MCPSSE   MCPType = "sse"
179	MCPHttp  MCPType = "http"
180)
181
182type MCPConfig struct {
183	Command       string            `json:"command,omitempty" jsonschema:"description=Command to execute for stdio MCP servers,example=npx"`
184	Env           map[string]string `json:"env,omitempty" jsonschema:"description=Environment variables to set for the MCP server"`
185	Args          []string          `json:"args,omitempty" jsonschema:"description=Arguments to pass to the MCP server command"`
186	Type          MCPType           `json:"type" jsonschema:"required,description=Type of MCP connection,enum=stdio,enum=sse,enum=http,default=stdio"`
187	URL           string            `json:"url,omitempty" jsonschema:"description=URL for HTTP or SSE MCP servers,format=uri,example=http://localhost:3000/mcp"`
188	Disabled      bool              `json:"disabled,omitempty" jsonschema:"description=Whether this MCP server is disabled,default=false"`
189	DisabledTools []string          `json:"disabled_tools,omitempty" jsonschema:"description=List of tools from this MCP server to disable,example=get-library-doc"`
190	EnabledTools  []string          `json:"enabled_tools,omitempty" jsonschema:"description=Allow list of tools from this MCP server,example=get-library-doc"`
191	Timeout       int               `json:"timeout,omitempty" jsonschema:"description=Timeout in seconds for MCP server connections,default=15,example=30,example=60,example=120"`
192
193	// Headers are HTTP headers for HTTP/SSE MCP servers. Values run
194	// through shell expansion at MCP startup, so $VAR and $(cmd)
195	// work. A header whose value resolves to the empty string (unset
196	// bare $VAR under lenient nounset, $(echo), or literal "") is
197	// omitted from the outgoing request rather than sent as
198	// "Header:".
199	Headers map[string]string `json:"headers,omitempty" jsonschema:"description=HTTP headers for HTTP/SSE MCP servers"`
200}
201
202type LSPConfig struct {
203	Disabled    bool              `json:"disabled,omitempty" jsonschema:"description=Whether this LSP server is disabled,default=false"`
204	Command     string            `json:"command,omitempty" jsonschema:"description=Command to execute for the LSP server,example=gopls"`
205	Args        []string          `json:"args,omitempty" jsonschema:"description=Arguments to pass to the LSP server command"`
206	Env         map[string]string `json:"env,omitempty" jsonschema:"description=Environment variables to set to the LSP server command"`
207	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"`
208	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"`
209	InitOptions map[string]any    `json:"init_options,omitempty" jsonschema:"description=Initialization options passed to the LSP server during initialize request"`
210	Options     map[string]any    `json:"options,omitempty" jsonschema:"description=LSP server-specific settings passed during initialization"`
211	Timeout     int               `json:"timeout,omitempty" jsonschema:"description=Timeout in seconds for LSP server initialization,default=30,example=60,example=120"`
212}
213
214type TUIOptions struct {
215	CompactMode bool   `json:"compact_mode,omitempty" jsonschema:"description=Enable compact mode for the TUI interface,default=false"`
216	DiffMode    string `json:"diff_mode,omitempty" jsonschema:"description=Diff mode for the TUI interface,enum=unified,enum=split"`
217	// Here we can add themes later or any TUI related options
218	//
219
220	Completions Completions `json:"completions,omitzero" jsonschema:"description=Completions UI options"`
221	Transparent *bool       `json:"transparent,omitempty" jsonschema:"description=Enable transparent background for the TUI interface,default=false"`
222}
223
224// Completions defines options for the completions UI.
225type Completions struct {
226	MaxDepth *int `json:"max_depth,omitempty" jsonschema:"description=Maximum depth for the ls tool,default=0,example=10"`
227	MaxItems *int `json:"max_items,omitempty" jsonschema:"description=Maximum number of items to return for the ls tool,default=1000,example=100"`
228}
229
230func (c Completions) Limits() (depth, items int) {
231	return ptrValOr(c.MaxDepth, 0), ptrValOr(c.MaxItems, 0)
232}
233
234type Permissions struct {
235	AllowedTools []string `json:"allowed_tools,omitempty" jsonschema:"description=List of tools that don't require permission prompts,example=bash,example=view"`
236}
237
238type TrailerStyle string
239
240const (
241	TrailerStyleNone         TrailerStyle = "none"
242	TrailerStyleCoAuthoredBy TrailerStyle = "co-authored-by"
243	TrailerStyleAssistedBy   TrailerStyle = "assisted-by"
244)
245
246type Attribution struct {
247	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"`
248	CoAuthoredBy  *bool        `json:"co_authored_by,omitempty" jsonschema:"description=Deprecated: use trailer_style instead"`
249	GeneratedWith bool         `json:"generated_with,omitempty" jsonschema:"description=Add Generated with Crush line to commit messages and issues and PRs,default=true"`
250}
251
252// JSONSchemaExtend marks the co_authored_by field as deprecated in the schema.
253func (Attribution) JSONSchemaExtend(schema *jsonschema.Schema) {
254	if schema.Properties != nil {
255		if prop, ok := schema.Properties.Get("co_authored_by"); ok {
256			prop.Deprecated = true
257		}
258	}
259}
260
261type Options struct {
262	ContextPaths         []string    `json:"context_paths,omitempty" jsonschema:"description=Paths to files containing context information for the AI,example=.cursorrules,example=CRUSH.md"`
263	GlobalContextPaths   []string    `json:"global_context_paths,omitempty" jsonschema:"description=Paths to files containing global context information for the AI,default=~/.config/crush/CRUSH.md,default=~/.config/AGENTS.md"`
264	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"`
265	TUI                  *TUIOptions `json:"tui,omitempty" jsonschema:"description=Terminal user interface options"`
266	Debug                bool        `json:"debug,omitempty" jsonschema:"description=Enable debug logging,default=false"`
267	DebugLSP             bool        `json:"debug_lsp,omitempty" jsonschema:"description=Enable debug logging for LSP servers,default=false"`
268	DisableAutoSummarize bool        `json:"disable_auto_summarize,omitempty" jsonschema:"description=Disable automatic conversation summarization,default=false"`
269	// DataDirectory is where Crush keeps per-project state such as
270	// the SQLite database and workspace overrides. Relative paths are
271	// resolved against the working directory; absolute paths are used
272	// verbatim. After defaulting the stored value is always absolute.
273	DataDirectory             string       `json:"data_directory,omitempty" jsonschema:"description=Directory for storing application data. Relative paths are resolved against the working directory; absolute paths are used as-is.,default=.crush,example=.crush"`
274	DisabledTools             []string     `json:"disabled_tools,omitempty" jsonschema:"description=List of built-in tools to disable and hide from the agent,example=bash,example=sourcegraph"`
275	DisableProviderAutoUpdate bool         `json:"disable_provider_auto_update,omitempty" jsonschema:"description=Disable providers auto-update,default=false"`
276	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"`
277	Attribution               *Attribution `json:"attribution,omitempty" jsonschema:"description=Attribution settings for generated content"`
278	DisableMetrics            bool         `json:"disable_metrics,omitempty" jsonschema:"description=Disable sending metrics,default=false"`
279	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"`
280	AutoLSP                   *bool        `json:"auto_lsp,omitempty" jsonschema:"description=Automatically setup LSPs based on root markers,default=true"`
281	Progress                  *bool        `json:"progress,omitempty" jsonschema:"description=Show indeterminate progress updates during long operations,default=true"`
282	DisableNotifications      bool         `json:"disable_notifications,omitempty" jsonschema:"description=Deprecated: Use notification_style instead. Disable desktop notifications,default=false"`
283	NotificationStyle         string       `json:"notification_style,omitempty" jsonschema:"description=Notification style to use. Options: auto (default), native, osc, bell, disabled. Auto selects based on environment: native for local sessions, osc for SSH (with automatic OSC 99/777 detection).,enum=auto,enum=native,enum=osc,enum=bell,enum=disabled,default=auto"`
284	DisabledSkills            []string     `json:"disabled_skills,omitempty" jsonschema:"description=List of skill names to disable and hide from the agent,example=crush-config"`
285}
286
287type MCPs map[string]MCPConfig
288
289type MCP struct {
290	Name string    `json:"name"`
291	MCP  MCPConfig `json:"mcp"`
292}
293
294func (m MCPs) Sorted() []MCP {
295	sorted := make([]MCP, 0, len(m))
296	for k, v := range m {
297		sorted = append(sorted, MCP{
298			Name: k,
299			MCP:  v,
300		})
301	}
302	slices.SortFunc(sorted, func(a, b MCP) int {
303		return strings.Compare(a.Name, b.Name)
304	})
305	return sorted
306}
307
308type LSPs map[string]LSPConfig
309
310type LSP struct {
311	Name string    `json:"name"`
312	LSP  LSPConfig `json:"lsp"`
313}
314
315func (l LSPs) Sorted() []LSP {
316	sorted := make([]LSP, 0, len(l))
317	for k, v := range l {
318		sorted = append(sorted, LSP{
319			Name: k,
320			LSP:  v,
321		})
322	}
323	slices.SortFunc(sorted, func(a, b LSP) int {
324		return strings.Compare(a.Name, b.Name)
325	})
326	return sorted
327}
328
329// ResolvedEnv returns m.Env with every value expanded through the
330// given resolver. The returned slice is of the form "KEY=value" sorted
331// by key so callers get deterministic output; the receiver's Env map is
332// not mutated. On the first resolution failure it returns nil and an
333// error that identifies the offending key; the inner resolver error is
334// already sanitized by ResolveValue and is wrapped with %w so
335// errors.Is/As continues to work. Callers are expected to surface it
336// (for MCP, via StateError on the status card) rather than silently
337// spawn the server with an empty credential.
338//
339// The resolver choice matters: in server mode pass the shell resolver
340// so $VAR / $(cmd) expand; in client mode pass IdentityResolver so the
341// template is forwarded verbatim and expansion happens on the server.
342func (m MCPConfig) ResolvedEnv(r VariableResolver) ([]string, error) {
343	return resolveEnvs(m.Env, r)
344}
345
346// ResolvedArgs returns m.Args with every element expanded through the
347// given resolver. A fresh slice is allocated; m.Args is never mutated.
348// On the first resolution failure it returns nil and an error
349// identifying the offending positional index; the inner resolver error
350// is already sanitized by ResolveValue and is wrapped with %w so
351// errors.Is/As continues to work.
352//
353// See ResolvedEnv for guidance on picking a resolver.
354func (m MCPConfig) ResolvedArgs(r VariableResolver) ([]string, error) {
355	if len(m.Args) == 0 {
356		return nil, nil
357	}
358	out := make([]string, len(m.Args))
359	for i, a := range m.Args {
360		v, err := r.ResolveValue(a)
361		if err != nil {
362			return nil, fmt.Errorf("arg %d: %w", i, err)
363		}
364		out[i] = v
365	}
366	return out, nil
367}
368
369// ResolvedURL returns m.URL expanded through the given resolver. The
370// receiver is not mutated. Errors from the resolver are already
371// sanitized by ResolveValue and are wrapped with %w for errors.Is/As.
372//
373// URLs run through the same shell-expansion pipeline as the other
374// fields, so a literal '$' (e.g. OData query strings containing
375// $filter/$select) must be escaped as '\$' or '${DOLLAR:-$}' to avoid
376// being interpreted as a variable reference. Same constraint already
377// applies to command, args, env, and headers.
378//
379// See ResolvedEnv for guidance on picking a resolver.
380func (m MCPConfig) ResolvedURL(r VariableResolver) (string, error) {
381	if m.URL == "" {
382		return "", nil
383	}
384	v, err := r.ResolveValue(m.URL)
385	if err != nil {
386		return "", fmt.Errorf("url: %w", err)
387	}
388	return v, nil
389}
390
391// ResolvedHeaders returns m.Headers with every value expanded through
392// the given resolver. A fresh map is allocated; m.Headers is never
393// mutated. On the first resolution failure it returns nil and an error
394// identifying the offending header name; the inner resolver error is
395// already sanitized by ResolveValue and is wrapped with %w so
396// errors.Is/As continues to work.
397//
398// A header whose value resolves to the empty string (unset bare $VAR
399// under lenient nounset, $(echo), or literal "") is omitted from the
400// returned map — sending "X-Auth:" with an empty value is rejected by
401// some providers and the user's intent in "optional, env-gated
402// header" is clearly "absent when the var isn't set."
403//
404// See ResolvedEnv for guidance on picking a resolver.
405func (m MCPConfig) ResolvedHeaders(r VariableResolver) (map[string]string, error) {
406	if len(m.Headers) == 0 {
407		return map[string]string{}, nil
408	}
409	out := make(map[string]string, len(m.Headers))
410	// Sort keys so failures are reported deterministically when more
411	// than one header would fail.
412	keys := make([]string, 0, len(m.Headers))
413	for k := range m.Headers {
414		keys = append(keys, k)
415	}
416	slices.Sort(keys)
417	for _, k := range keys {
418		v, err := r.ResolveValue(m.Headers[k])
419		if err != nil {
420			return nil, fmt.Errorf("header %s: %w", k, err)
421		}
422		if v == "" {
423			continue
424		}
425		out[k] = v
426	}
427	return out, nil
428}
429
430// ResolvedArgs returns l.Args with every element expanded through the
431// given resolver. A fresh slice is allocated; l.Args is never mutated.
432// On the first resolution failure it returns nil and an error
433// identifying the offending positional index; the inner resolver error
434// is already sanitized by ResolveValue and is wrapped with %w so
435// errors.Is/As continues to work.
436//
437// Empty resolved values are kept (a deliberate "empty positional arg"
438// like --flag "" is sometimes valid), matching MCPConfig.ResolvedArgs.
439//
440// The resolver choice matters: in server mode pass the shell resolver
441// so $VAR / $(cmd) expand; in client mode pass IdentityResolver so the
442// template is forwarded verbatim.
443func (l LSPConfig) ResolvedArgs(r VariableResolver) ([]string, error) {
444	if len(l.Args) == 0 {
445		return nil, nil
446	}
447	out := make([]string, len(l.Args))
448	for i, a := range l.Args {
449		v, err := r.ResolveValue(a)
450		if err != nil {
451			return nil, fmt.Errorf("arg %d: %w", i, err)
452		}
453		out[i] = v
454	}
455	return out, nil
456}
457
458// ResolvedEnv returns l.Env with every value expanded through the
459// given resolver. A fresh map is allocated; l.Env is never mutated.
460// On the first resolution failure it returns nil and an error that
461// identifies the offending key; the inner resolver error is already
462// sanitized by ResolveValue and is wrapped with %w so errors.Is/As
463// continues to work.
464//
465// Empty resolved values are kept ("FOO=" is a legitimate request;
466// opt out via ${VAR:+...}), matching MCPConfig.ResolvedEnv.
467//
468// Shape note: this returns map[string]string rather than the []string
469// shape MCPConfig.ResolvedEnv uses because the consumer
470// (powernap.ClientConfig.Environment in internal/lsp/client.go) takes
471// a map directly — returning a []string here would only force a
472// round-trip back to a map at the call site.
473//
474// See ResolvedArgs for guidance on picking a resolver.
475func (l LSPConfig) ResolvedEnv(r VariableResolver) (map[string]string, error) {
476	if len(l.Env) == 0 {
477		return map[string]string{}, nil
478	}
479	out := make(map[string]string, len(l.Env))
480	// Sort keys so failures are reported deterministically when more
481	// than one value would fail.
482	keys := make([]string, 0, len(l.Env))
483	for k := range l.Env {
484		keys = append(keys, k)
485	}
486	slices.Sort(keys)
487	for _, k := range keys {
488		v, err := r.ResolveValue(l.Env[k])
489		if err != nil {
490			return nil, fmt.Errorf("env %q: %w", k, err)
491		}
492		out[k] = v
493	}
494	return out, nil
495}
496
497type Agent struct {
498	ID          string `json:"id,omitempty"`
499	Name        string `json:"name,omitempty"`
500	Description string `json:"description,omitempty"`
501	// This is the id of the system prompt used by the agent
502	Disabled bool `json:"disabled,omitempty"`
503
504	Model SelectedModelType `json:"model" jsonschema:"required,description=The model type to use for this agent,enum=large,enum=small,default=large"`
505
506	// The available tools for the agent
507	//  if this is nil, all tools are available
508	AllowedTools []string `json:"allowed_tools,omitempty"`
509
510	// this tells us which MCPs are available for this agent
511	//  if this is empty all mcps are available
512	//  the string array is the list of tools from the AllowedMCP the agent has available
513	//  if the string array is nil, all tools from the AllowedMCP are available
514	AllowedMCP map[string][]string `json:"allowed_mcp,omitempty"`
515
516	// Overrides the context paths for this agent
517	ContextPaths []string `json:"context_paths,omitempty"`
518}
519
520type Tools struct {
521	Ls   ToolLs   `json:"ls,omitzero"`
522	Grep ToolGrep `json:"grep,omitzero"`
523}
524
525type ToolLs struct {
526	MaxDepth *int `json:"max_depth,omitempty" jsonschema:"description=Maximum depth for the ls tool,default=0,example=10"`
527	MaxItems *int `json:"max_items,omitempty" jsonschema:"description=Maximum number of items to return for the ls tool,default=1000,example=100"`
528}
529
530// Limits returns the user-defined max-depth and max-items, or their defaults.
531func (t ToolLs) Limits() (depth, items int) {
532	return ptrValOr(t.MaxDepth, 0), ptrValOr(t.MaxItems, 0)
533}
534
535type ToolGrep struct {
536	Timeout *time.Duration `json:"timeout,omitempty" jsonschema:"description=Timeout for the grep tool call,default=5s,example=10s"`
537}
538
539// GetTimeout returns the user-defined timeout or the default.
540func (t ToolGrep) GetTimeout() time.Duration {
541	return ptrValOr(t.Timeout, 5*time.Second)
542}
543
544// HookConfig defines a user-configured shell command that fires on a hook
545// event (e.g. PreToolUse). This is a pure-data struct: matcher compilation
546// is owned by hooks.Runner so a JSON round-trip, merge, or reload can't
547// silently drop compiled state.
548type HookConfig struct {
549	// Friendly display name shown in the TUI. Falls back to Command when empty.
550	Name string `json:"name,omitempty" jsonschema:"description=Friendly display name shown in the TUI for this hook"`
551	// Regex pattern tested against the tool name. Empty means match all.
552	Matcher string `json:"matcher,omitempty" jsonschema:"description=Regex pattern tested against the tool name. Empty means match all tools."`
553	// Shell command to execute.
554	Command string `json:"command" jsonschema:"required,description=Shell command to execute when the hook fires"`
555	// Timeout in seconds. Default 30.
556	Timeout int `json:"timeout,omitempty" jsonschema:"description=Timeout in seconds for the hook command,default=30"`
557}
558
559// DisplayName returns the hook name for display purposes. It returns Name
560// when set, otherwise falls back to Command.
561func (h *HookConfig) DisplayName() string {
562	if h.Name != "" {
563		return h.Name
564	}
565	return h.Command
566}
567
568// TimeoutDuration returns the hook timeout as a time.Duration, defaulting
569// to 30s.
570func (h *HookConfig) TimeoutDuration() time.Duration {
571	if h.Timeout <= 0 {
572		return 30 * time.Second
573	}
574	return time.Duration(h.Timeout) * time.Second
575}
576
577// Config holds the configuration for crush.
578type Config struct {
579	Schema string `json:"$schema,omitempty"`
580
581	// We currently only support large/small as values here.
582	Models map[SelectedModelType]SelectedModel `json:"models,omitempty" jsonschema:"description=Model configurations for different model types,example={\"large\":{\"model\":\"gpt-4o\",\"provider\":\"openai\"}}"`
583
584	// Recently used models stored in the data directory config.
585	RecentModels map[SelectedModelType][]SelectedModel `json:"recent_models,omitempty" jsonschema:"-"`
586
587	// The providers that are configured
588	Providers *csync.Map[string, ProviderConfig] `json:"providers,omitempty" jsonschema:"description=AI provider configurations"`
589
590	MCP MCPs `json:"mcp,omitempty" jsonschema:"description=Model Context Protocol server configurations"`
591
592	LSP LSPs `json:"lsp,omitempty" jsonschema:"description=Language Server Protocol configurations"`
593
594	Options *Options `json:"options,omitempty" jsonschema:"description=General application options"`
595
596	Permissions *Permissions `json:"permissions,omitempty" jsonschema:"description=Permission settings for tool usage"`
597
598	Tools Tools `json:"tools,omitzero" jsonschema:"description=Tool configurations"`
599
600	Hooks map[string][]HookConfig `json:"hooks,omitempty" jsonschema:"description=User-defined shell commands that fire on hook events (e.g. PreToolUse)"`
601
602	Agents map[string]Agent `json:"-"`
603}
604
605func (c *Config) EnabledProviders() []ProviderConfig {
606	var enabled []ProviderConfig
607	for p := range c.Providers.Seq() {
608		if !p.Disable {
609			enabled = append(enabled, p)
610		}
611	}
612	return enabled
613}
614
615// IsConfigured  return true if at least one provider is configured
616func (c *Config) IsConfigured() bool {
617	return len(c.EnabledProviders()) > 0
618}
619
620func (c *Config) GetModel(provider, model string) *catwalk.Model {
621	if providerConfig, ok := c.Providers.Get(provider); ok {
622		for _, m := range providerConfig.Models {
623			if m.ID == model {
624				return &m
625			}
626		}
627	}
628	return nil
629}
630
631func (c *Config) GetProviderForModel(modelType SelectedModelType) *ProviderConfig {
632	model, ok := c.Models[modelType]
633	if !ok {
634		return nil
635	}
636	if providerConfig, ok := c.Providers.Get(model.Provider); ok {
637		return &providerConfig
638	}
639	return nil
640}
641
642func (c *Config) GetModelByType(modelType SelectedModelType) *catwalk.Model {
643	model, ok := c.Models[modelType]
644	if !ok {
645		return nil
646	}
647	return c.GetModel(model.Provider, model.Model)
648}
649
650func (c *Config) LargeModel() *catwalk.Model {
651	model, ok := c.Models[SelectedModelTypeLarge]
652	if !ok {
653		return nil
654	}
655	return c.GetModel(model.Provider, model.Model)
656}
657
658func (c *Config) SmallModel() *catwalk.Model {
659	model, ok := c.Models[SelectedModelTypeSmall]
660	if !ok {
661		return nil
662	}
663	return c.GetModel(model.Provider, model.Model)
664}
665
666const maxRecentModelsPerType = 5
667
668func allToolNames() []string {
669	return []string{
670		"agent",
671		"bash",
672		"crush_info",
673		"crush_logs",
674		"job_output",
675		"job_kill",
676		"download",
677		"edit",
678		"multiedit",
679		"lsp_diagnostics",
680		"lsp_references",
681		"lsp_restart",
682		"fetch",
683		"agentic_fetch",
684		"glob",
685		"grep",
686		"ls",
687		"sourcegraph",
688		"todos",
689		"view",
690		"write",
691		"list_mcp_resources",
692		"read_mcp_resource",
693	}
694}
695
696func resolveAllowedTools(allTools []string, disabledTools []string) []string {
697	if disabledTools == nil {
698		return allTools
699	}
700	// filter out disabled tools (exclude mode)
701	return filterSlice(allTools, disabledTools, false)
702}
703
704func resolveReadOnlyTools(tools []string) []string {
705	readOnlyTools := []string{"glob", "grep", "ls", "sourcegraph", "view"}
706	// filter to only include tools that are in allowedtools (include mode)
707	return filterSlice(tools, readOnlyTools, true)
708}
709
710func filterSlice(data []string, mask []string, include bool) []string {
711	var filtered []string
712	for _, s := range data {
713		// if include is true, we include items that ARE in the mask
714		// if include is false, we include items that are NOT in the mask
715		if include == slices.Contains(mask, s) {
716			filtered = append(filtered, s)
717		}
718	}
719	return filtered
720}
721
722func (c *Config) SetupAgents() {
723	allowedTools := resolveAllowedTools(allToolNames(), c.Options.DisabledTools)
724
725	agents := map[string]Agent{
726		AgentCoder: {
727			ID:           AgentCoder,
728			Name:         "Coder",
729			Description:  "An agent that helps with executing coding tasks.",
730			Model:        SelectedModelTypeLarge,
731			ContextPaths: c.Options.ContextPaths,
732			AllowedTools: allowedTools,
733		},
734
735		AgentTask: {
736			ID:           AgentTask,
737			Name:         "Task",
738			Description:  "An agent that helps with searching for context and finding implementation details.",
739			Model:        SelectedModelTypeLarge,
740			ContextPaths: c.Options.ContextPaths,
741			AllowedTools: resolveReadOnlyTools(allowedTools),
742			// NO MCPs or LSPs by default
743			AllowedMCP: map[string][]string{},
744		},
745	}
746	c.Agents = agents
747}
748
749func (c *ProviderConfig) TestConnection(resolver VariableResolver) error {
750	var (
751		providerID = catwalk.InferenceProvider(c.ID)
752		testURL    = ""
753		headers    = make(map[string]string)
754		apiKey, _  = resolver.ResolveValue(c.APIKey)
755	)
756
757	switch providerID {
758	case catwalk.InferenceProviderMiniMax, catwalk.InferenceProviderMiniMaxChina:
759		// NOTE: MiniMax has no good endpoint we can use to validate the API key.
760		return nil
761	case catwalk.InferenceProviderAlibabaSingapore:
762		// NOTE: Alibaba has no good endpoint we can use to validate the API key.
763		// Let's at least check the pattern.
764		if !strings.HasPrefix(apiKey, "sk-") {
765			return fmt.Errorf("invalid API key format for provider %s", c.ID)
766		}
767		return nil
768	}
769
770	switch c.Type {
771	case catwalk.TypeOpenAI, catwalk.TypeOpenAICompat, catwalk.TypeOpenRouter:
772		baseURL, _ := resolver.ResolveValue(c.BaseURL)
773		baseURL = cmp.Or(baseURL, "https://api.openai.com/v1")
774
775		switch providerID {
776		case catwalk.InferenceProviderOpenRouter:
777			testURL = baseURL + "/credits"
778		case catwalk.InferenceProviderOpenCodeGo:
779			testURL = strings.Replace(baseURL, "/go", "", 1) + "/models"
780		default:
781			testURL = baseURL + "/models"
782		}
783
784		headers["Authorization"] = "Bearer " + apiKey
785	case catwalk.TypeAnthropic:
786		baseURL, _ := resolver.ResolveValue(c.BaseURL)
787		baseURL = cmp.Or(baseURL, "https://api.anthropic.com/v1")
788
789		switch providerID {
790		case catwalk.InferenceKimiCoding:
791			testURL = baseURL + "/v1/models"
792		default:
793			testURL = baseURL + "/models"
794		}
795
796		headers["x-api-key"] = apiKey
797		headers["anthropic-version"] = "2023-06-01"
798	case catwalk.TypeGoogle:
799		baseURL, _ := resolver.ResolveValue(c.BaseURL)
800		baseURL = cmp.Or(baseURL, "https://generativelanguage.googleapis.com")
801		testURL = baseURL + "/v1beta/models?key=" + url.QueryEscape(apiKey)
802	case catwalk.TypeBedrock:
803		// NOTE: Bedrock has a `/foundation-models` endpoint that we could in
804		// theory use, but apparently the authorization is region-specific,
805		// so it's not so trivial.
806		if strings.HasPrefix(apiKey, "ABSK") { // Bedrock API keys
807			return nil
808		}
809		return errors.New("not a valid bedrock api key")
810	case catwalk.TypeVercel:
811		// NOTE: Vercel does not validate API keys on the `/models` endpoint.
812		if strings.HasPrefix(apiKey, "vck_") { // Vercel API keys
813			return nil
814		}
815		return errors.New("not a valid vercel api key")
816	}
817
818	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
819	defer cancel()
820
821	client := &http.Client{}
822	req, err := http.NewRequestWithContext(ctx, "GET", testURL, nil)
823	if err != nil {
824		return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
825	}
826	for k, v := range headers {
827		req.Header.Set(k, v)
828	}
829	for k, v := range c.ExtraHeaders {
830		req.Header.Set(k, v)
831	}
832
833	resp, err := client.Do(req)
834	if err != nil {
835		return fmt.Errorf("failed to create request for provider %s: %w", c.ID, err)
836	}
837	defer resp.Body.Close()
838
839	switch providerID {
840	case catwalk.InferenceProviderZAI:
841		if resp.StatusCode == http.StatusUnauthorized {
842			return fmt.Errorf("failed to connect to provider %s: %s", c.ID, resp.Status)
843		}
844	default:
845		if resp.StatusCode != http.StatusOK {
846			return fmt.Errorf("failed to connect to provider %s: %s", c.ID, resp.Status)
847		}
848	}
849	return nil
850}
851
852// resolveEnvs expands every value in envs through the given resolver
853// and returns a fresh "KEY=value" slice sorted by key. The input map is
854// not mutated. On the first resolution failure it returns nil and an
855// error identifying the offending variable; the inner resolver error is
856// already sanitized by ResolveValue and is wrapped with %w.
857func resolveEnvs(envs map[string]string, r VariableResolver) ([]string, error) {
858	if len(envs) == 0 {
859		return nil, nil
860	}
861	keys := make([]string, 0, len(envs))
862	for k := range envs {
863		keys = append(keys, k)
864	}
865	slices.Sort(keys)
866	res := make([]string, 0, len(envs))
867	for _, k := range keys {
868		v, err := r.ResolveValue(envs[k])
869		if err != nil {
870			return nil, fmt.Errorf("env %s: %w", k, err)
871		}
872		res = append(res, fmt.Sprintf("%s=%s", k, v))
873	}
874	return res, nil
875}
876
877func ptrValOr[T any](t *T, el T) T {
878	if t == nil {
879		return el
880	}
881	return *t
882}