v0.41.0 6084eb1

config.go RawHistoryFolder

1// Package agent wires the provider, core, tools, auth, and modes into a CLI.
2package agent
3
4import (
5	"context"
6	"encoding/json"
7	"errors"
8	"fmt"
9	"os"
10	"path/filepath"
11	"runtime"
12	"strings"
13	"time"
14
15	providerpkg "github.com/bnema/zut/packages/provider"
16	"github.com/bnema/zut/packages/provider/auth"
17)
18
19// QuickModelShortcut is one configured model profile slot.
20type QuickModelShortcut struct {
21	Provider  string `json:"provider"`
22	Model     string `json:"model"`
23	Reasoning string `json:"reasoning,omitempty"`
24	FastMode  bool   `json:"fast_mode,omitempty"`
25}
26
27// SubagentsConfig contains the resident manager policy. max_concurrent limits
28// simultaneous turns, queue_timeout bounds admission waits, allowed_tools
29// limits child capabilities and allowed_roots limits eligible workspaces.
30// Obsolete keys are ignored.
31type SubagentsConfig struct {
32	MaxConcurrent int      `json:"max_concurrent,omitempty"`
33	QueueTimeout  string   `json:"queue_timeout,omitempty"`
34	AllowedTools  []string `json:"allowed_tools,omitempty"`
35	AllowedRoots  []string `json:"allowed_roots,omitempty"`
36}
37
38// GoalsConfig controls optional resource limits for autonomous goals. A nil
39// MaxTokenBudget leaves goals unlimited; when set, it is the host-configured
40// cap applied to newly created goals.
41type GoalsConfig struct {
42	MaxTokenBudget *uint64 `json:"max_token_budget,omitempty"`
43}
44
45// Config is the persisted user configuration.
46type Config struct {
47	Provider    string   `json:"provider"`
48	Model       string   `json:"model"`
49	Reasoning   string   `json:"reasoning"`
50	Temperature *float32 `json:"temperature,omitempty"`
51	Theme       string   `json:"theme"`
52
53	// FastMode requests OpenAI's fast service tier. Off by default;
54	// nil/missing means disabled. An active model profile supplies its
55	// per-profile value at startup. Other providers reject fast-mode
56	// requests at the provider boundary.
57	FastMode *bool `json:"fast_mode,omitempty"`
58
59	// ToolRender selects how tool calls are drawn in interactive mode.
60	// "box" (default, or empty) wraps each call in a bordered panel;
61	// "flat" drops the frame for a quiet header line plus indented,
62	// frameless output. The ZUT_FLAT_TOOLS env var overrides this when
63	// set ("1"/"true" forces flat, "0"/"false" forces box).
64	ToolRender string `json:"tool_render,omitempty"`
65
66	// CompactInput renders sent user messages as a single quiet gutter
67	// line instead of a padded, background-tinted bubble. nil/false
68	// (the default) keeps the bubble. The ZUT_COMPACT_INPUT env var
69	// overrides this when set.
70	CompactInput *bool `json:"compact_input,omitempty"`
71
72	// QuickModelShortcuts maps slots 1-9 to model profiles used by
73	// Ctrl+1..9. Cmd+1..9 may also work on terminals that forward Super.
74	QuickModelShortcuts []QuickModelShortcut `json:"quick_model_shortcuts,omitempty"`
75	ActiveModelProfile  int                  `json:"active_model_profile,omitempty"`
76
77	// InlineImagesEnabled controls whether zut draws screenshots inline
78	// when the terminal supports an image protocol. nil/missing means
79	// auto (enabled when supported); false disables; true forces the
80	// detected protocol when available.
81	InlineImagesEnabled *bool `json:"inline_images_enabled,omitempty"`
82
83	// TerminalAlertsEnabled controls interactive terminal alerts from the
84	// main agent and extensions. nil/missing means enabled; false disables
85	// alerts. Toggle from /settings.
86	TerminalAlertsEnabled *bool `json:"terminal_alerts_enabled,omitempty"`
87
88	// TerminalTitleEnabled controls the hidden title request and OSC 0 title
89	// updates in interactive mode. nil/missing means enabled; false disables
90	// both so no extra provider request is made. Toggle from /settings.
91	TerminalTitleEnabled *bool `json:"terminal_title_enabled,omitempty"`
92
93	// Subagents controls manager-owned child lifecycle and resource policy.
94	Subagents SubagentsConfig `json:"subagents,omitempty"`
95
96	// Goals configures optional resource limits for autonomous goals. Missing
97	// configuration preserves unlimited autonomous execution.
98	Goals GoalsConfig `json:"goals,omitempty"`
99
100	// AutoSubagentsEnabled lets the interactive primary proactively delegate
101	// independent sidecar work through built-in subagent tools. Off by default;
102	// nil/missing means disabled. Toggle from /settings.
103	AutoSubagentsEnabled *bool `json:"auto_subagents_enabled,omitempty"`
104
105	// PonytailEnabled controls the compact coding-guidance addendum. On by
106	// default; nil/missing means enabled. Toggle from /settings.
107	PonytailEnabled *bool `json:"ponytail_enabled,omitempty"`
108
109	// WebSearchEnabled controls the built-in web_search capability for
110	// normal CLI sessions. nil/missing means enabled so existing config
111	// files retain the default-on behavior.
112	WebSearchEnabled *bool `json:"web_search_enabled,omitempty"`
113
114	// LSPEnabled controls the built-in lsp tool and write-time diagnostics
115	// for the main session. nil/missing means enabled. Toggle from
116	// /settings.
117	LSPEnabled *bool `json:"lsp_enabled,omitempty"`
118
119	// SubagentLSPEnabled controls LSP availability in resident child agents.
120	// nil/missing means enabled. Toggle from /settings.
121	SubagentLSPEnabled *bool `json:"subagent_lsp_enabled,omitempty"`
122
123	// LSPDiagnosticsOnWrite enables bounded diagnostics after a successful
124	// write. nil/missing means enabled when LSP itself is enabled.
125	LSPDiagnosticsOnWrite *bool `json:"lsp_diagnostics_on_write,omitempty"`
126
127	// LSPDiagnosticsOnEdit enables bounded diagnostics after a successful
128	// edit. nil/missing means enabled when LSP itself is enabled.
129	LSPDiagnosticsOnEdit *bool `json:"lsp_diagnostics_on_edit,omitempty"`
130
131	// AutoCompactThreshold is the percentage of the model context window
132	// that triggers automatic transcript compaction in interactive mode.
133	// nil/missing means 85; valid values are 0, 70, 80, 85, 90, or 95.
134	// zero disables percentage-based triggers.
135	AutoCompactThreshold *int `json:"auto_compact_threshold,omitempty"`
136
137	// JailByDefault confines tools to the session working directory when
138	// a new agent starts. Off by default; nil/missing means disabled.
139	// The live session can still override this with /jail or /unjail.
140	JailByDefault *bool `json:"jail_by_default,omitempty"`
141
142	// RecursiveFileSuggest controls the @-mention file picker. When true
143	// the picker fuzzy-searches the whole project tree below the working
144	// directory; nil/missing/false keeps the default directory-by-
145	// directory browse. Toggle from /settings.
146	RecursiveFileSuggest *bool `json:"recursive_file_suggest,omitempty"`
147
148	// RespectGitignore controls whether the @-mention file picker hides
149	// files and directories matched by the project's root .gitignore (in
150	// both flat and recursive modes). nil/missing means the default,
151	// which is on; false shows ignored entries. Toggle from /settings.
152	RespectGitignore *bool `json:"respect_gitignore,omitempty"`
153
154	// CompactMode renders the interactive transcript with less chrome:
155	// tool calls use flat headers instead of bordered panels, and sent
156	// user messages render without padded background bubbles. Off by
157	// default; nil/missing means disabled. Toggle from /settings.
158	CompactMode *bool `json:"compact_mode,omitempty"`
159
160	// ShowInstructionsAtStartup lists loaded context files, extensions,
161	// and user-installed skills above the transcript. Off by default;
162	// nil/missing means disabled. Toggle from /settings.
163	ShowInstructionsAtStartup *bool `json:"show_instructions_at_startup,omitempty"`
164
165	// TUIInputStyle controls the main input rendering. Supported values:
166	// "plain" (default), "lines", and "block".
167	TUIInputStyle string `json:"tui_input_style,omitempty"`
168
169	// TUIStatusPosition controls whether model, usage, and cwd information
170	// render above or below the main input. Supported values: "above_input"
171	// (default) and "below_input".
172	TUIStatusPosition string `json:"tui_status_position,omitempty"`
173
174	// TUIWorkingPosition controls whether the busy/working spinner renders
175	// above or below the main input. Supported values: "above_input"
176	// (default) and "below_input".
177	TUIWorkingPosition string `json:"tui_working_position,omitempty"`
178
179	// PythonInterpreter selects the Python 3 executable for the python tool.
180	// It is one executable path, not a command line: absolute paths are used
181	// directly, relative paths resolve against the session working directory.
182	// Empty means automatic discovery (VIRTUAL_ENV, ./.venv, then PATH).
183	// Zut never installs Python or packages; the environment must exist.
184	PythonInterpreter string `json:"python_interpreter,omitempty"`
185
186	// Insecure skips TLS verification for custom inference endpoints.
187	Insecure bool `json:"insecure,omitempty"`
188
189	// HTTPProxy is a global proxy URL used for HTTP and HTTPS requests when
190	// the corresponding standard proxy environment variable is not already set.
191	HTTPProxy string `json:"http_proxy,omitempty"`
192
193	// LastChangelogShown is the version whose release-notes
194	// dialog the user has already seen. When the running binary's
195	// version differs, the next interactive run shows the
196	// changelog (fetched from the GitHub release page) once and
197	// updates this field. Empty means "never shown".
198	LastChangelogShown string `json:"last_changelog_shown,omitempty"`
199}
200
201// ZutHome returns $ZUT_HOME or the OS-default data dir.
202//
203// All zut state (config.json, auth.json, sessions/, logs/) lives under
204// this directory.
205func ZutHome() string {
206	if v := os.Getenv("ZUT_HOME"); v != "" {
207		return v
208	}
209	if v := os.Getenv("XDG_STATE_HOME"); v != "" {
210		return filepath.Join(v, "zut")
211	}
212	switch runtime.GOOS {
213	case "darwin":
214		if home, err := os.UserHomeDir(); err == nil {
215			return filepath.Join(home, "Library", "Application Support", "zut")
216		}
217	case "windows":
218		if v := os.Getenv("LOCALAPPDATA"); v != "" {
219			return filepath.Join(v, "zut")
220		}
221	}
222	if home, err := os.UserHomeDir(); err == nil {
223		return filepath.Join(home, ".local", "state", "zut")
224	}
225	return ".zut"
226}
227
228// ConfigPath returns the path to config.json.
229func ConfigPath() string { return filepath.Join(ZutHome(), "config.json") }
230
231// FlatToolRender reports whether tool calls should render flat (no
232// bordered panel). The ZUT_FLAT_TOOLS env var takes precedence over
233// the config when set: "1"/"true"/"yes"/"on" force flat, "0"/"false"/
234// "no"/"off" force box. Otherwise the config's tool_render is
235// consulted; "flat" is flat, anything else (including empty) is box.
236func (c Config) FlatToolRender() bool {
237	if v := strings.TrimSpace(strings.ToLower(os.Getenv("ZUT_FLAT_TOOLS"))); v != "" {
238		switch v {
239		case "1", "true", "yes", "on", "flat":
240			return true
241		case "0", "false", "no", "off", "box":
242			return false
243		}
244	}
245	return strings.EqualFold(strings.TrimSpace(c.ToolRender), "flat")
246}
247
248// CompactUserInput reports whether sent user messages should render as
249// a single quiet gutter line instead of a padded, background-tinted
250// bubble. The ZUT_COMPACT_INPUT env var takes precedence over the
251// config when set: "1"/"true"/"yes"/"on" force compact, "0"/"false"/
252// "no"/"off" force the bubble. Otherwise the config's compact_input
253// is consulted (nil/false means the bubble).
254func (c Config) CompactUserInput() bool {
255	if v := strings.TrimSpace(strings.ToLower(os.Getenv("ZUT_COMPACT_INPUT"))); v != "" {
256		switch v {
257		case "1", "true", "yes", "on", "compact":
258			return true
259		case "0", "false", "no", "off", "bubble":
260			return false
261		}
262	}
263	return c.CompactInput != nil && *c.CompactInput
264}
265
266// LSPEnabledFor reports whether LSP is enabled for a main or subagent
267// sub-agent session. Both settings default to true so new installations
268// get code intelligence without a migration or generated config file.
269func (c Config) LSPEnabledFor(subagent bool) bool {
270	value := c.LSPEnabled
271	if subagent {
272		value = c.SubagentLSPEnabled
273	}
274	return value == nil || *value
275}
276
277// PonytailModeEnabled reports the default-on coding-guidance preference
278// without requiring a generated config entry.
279func (c Config) PonytailModeEnabled() bool {
280	return c.PonytailEnabled == nil || *c.PonytailEnabled
281}
282
283// WebSearchEnabledForCLI reports the default-on web-search preference
284// without requiring a generated config entry.
285func (c Config) WebSearchEnabledForCLI() bool {
286	return c.WebSearchEnabled == nil || *c.WebSearchEnabled
287}
288
289// LSPDiagnosticsOnWriteEnabled reports the default-on write diagnostics
290// preference without requiring a generated config entry.
291func (c Config) LSPDiagnosticsOnWriteEnabled(subagent bool) bool {
292	return c.LSPEnabledFor(subagent) && (c.LSPDiagnosticsOnWrite == nil || *c.LSPDiagnosticsOnWrite)
293}
294
295// LSPDiagnosticsOnEditEnabled reports the default-on edit diagnostics
296// preference without requiring a generated config entry.
297func (c Config) LSPDiagnosticsOnEditEnabled(subagent bool) bool {
298	return c.LSPEnabledFor(subagent) && (c.LSPDiagnosticsOnEdit == nil || *c.LSPDiagnosticsOnEdit)
299}
300
301// AuthPath returns the path to auth.json.
302func AuthPath() string { return filepath.Join(ZutHome(), "auth.json") }
303
304// KimiCLIFallbackDisabledPath returns a sentinel that disables falling
305// back to the official Kimi Code CLI token after `zut /logout kimi`.
306func KimiCLIFallbackDisabledPath() string {
307	return filepath.Join(ZutHome(), "kimi-cli-fallback-disabled")
308}
309
310// SessionsPath returns the directory holding session files.
311func SessionsPath() string { return filepath.Join(ZutHome(), "sessions") }
312
313// LogsPath returns the directory holding log files.
314func LogsPath() string { return filepath.Join(ZutHome(), "logs") }
315
316// LoadConfig reads the config file, returning defaults if missing.
317func LoadConfig() (Config, error) {
318	var c Config
319	b, err := os.ReadFile(ConfigPath())
320	if errors.Is(err, os.ErrNotExist) {
321		return c, nil
322	}
323	if err != nil {
324		return c, err
325	}
326	if err := json.Unmarshal(b, &c); err != nil {
327		return c, fmt.Errorf("parse config: %w", err)
328	}
329	if err := validateSubagentConfig(c.Subagents); err != nil {
330		return c, err
331	}
332	return c, nil
333}
334
335// normalizedModelProfile keeps startup defaults and the TUI's copy consistent.
336// Unknown/open-catalog models retain their configured reasoning until resolved.
337func normalizedModelProfile(p QuickModelShortcut) QuickModelShortcut {
338	p.Provider = canonicalProvider(p.Provider)
339	p.Reasoning = providerpkg.NormalizeReasoning(p.Reasoning)
340	if model, err := providerpkg.FindModel(p.Provider, p.Model); err == nil {
341		p.Reasoning = providerpkg.ClampReasoningForModel(model, p.Reasoning)
342	}
343	return p
344}
345
346// applyActiveModelProfile supplies defaults without rewriting the config and
347// returns their source slot (0 when none). Explicit flags retain precedence.
348func (c *Config) applyActiveModelProfile() int {
349	slot := c.ActiveModelProfile
350	if slot < 1 || slot > 9 {
351		slot = 1
352	}
353	if slot > len(c.QuickModelShortcuts) {
354		return 0
355	}
356	p := normalizedModelProfile(c.QuickModelShortcuts[slot-1])
357	if p.Provider == "" || p.Model == "" {
358		return 0
359	}
360	c.Provider, c.Model, c.Reasoning = p.Provider, p.Model, p.Reasoning
361	fastMode := p.FastMode
362	c.FastMode = &fastMode
363	return slot
364}
365
366func validateSubagentConfig(cfg SubagentsConfig) error {
367	values := []struct {
368		name  string
369		value string
370	}{
371		{"queue_timeout", cfg.QueueTimeout},
372	}
373	for _, item := range values {
374		value := strings.TrimSpace(item.value)
375		if value == "" {
376			continue
377		}
378		if _, err := time.ParseDuration(value); err != nil {
379			return fmt.Errorf("parse config: subagents.%s: %w", item.name, err)
380		}
381	}
382	return nil
383}
384
385// SaveConfig writes the config file, creating parent dirs.
386func SaveConfig(c Config) error {
387	if err := os.MkdirAll(ZutHome(), 0o755); err != nil {
388		return err
389	}
390	b, err := json.MarshalIndent(c, "", "  ")
391	if err != nil {
392		return err
393	}
394	return os.WriteFile(ConfigPath(), b, 0o644)
395}
396
397// applyConfiguredHTTPProxy makes the persisted proxy available to Go's
398// standard HTTP transport and to child processes. Explicit environment
399// variables take precedence over config.json.
400func applyConfiguredHTTPProxy() {
401	cfg, err := LoadConfig()
402	if err != nil {
403		return
404	}
405	proxy := strings.TrimSpace(cfg.HTTPProxy)
406	if proxy == "" {
407		return
408	}
409	if os.Getenv("HTTP_PROXY") == "" && os.Getenv("http_proxy") == "" {
410		_ = os.Setenv("HTTP_PROXY", proxy)
411	}
412	if os.Getenv("HTTPS_PROXY") == "" && os.Getenv("https_proxy") == "" {
413		_ = os.Setenv("HTTPS_PROXY", proxy)
414	}
415}
416
417// AuthStoreFor returns the auth.Store backed by AuthPath().
418func AuthStoreFor() *auth.Store { return auth.NewStore(AuthPath()) }
419
420// ResolveLlamaCPPConfig resolves the router URL and optional API key. The
421// environment overrides the credential stored through /login.
422func ResolveLlamaCPPConfig() (baseURL, apiKey string, err error) {
423	return resolveLlamaCPPConfig(context.Background(), apiKeyCommandExecute)
424}
425
426func resolveLlamaCPPConfig(ctx context.Context, commandMode apiKeyCommandMode) (baseURL, apiKey string, err error) {
427	baseURL = strings.TrimSpace(os.Getenv("LLAMA_BASE_URL"))
428	apiKey = strings.TrimSpace(os.Getenv("LLAMA_API_KEY"))
429	if baseURL == "" {
430		creds, loadErr := AuthStoreFor().Load()
431		if loadErr != nil {
432			return "", "", loadErr
433		}
434		if stored, ok := creds.AdditionalAPIKeyCreds[providerpkg.LlamaCPPProviderID]; ok {
435			baseURL = stored.BaseURL
436			if apiKey == "" {
437				if stored.APIKeyCommand != nil && commandMode == apiKeyCommandSkip {
438					return "", "", nil
439				}
440				if key, found, commandErr := resolveStoredAPIKey(ctx, providerpkg.LlamaCPPProviderID, stored, commandMode); found || commandErr != nil {
441					if commandErr != nil {
442						return "", "", commandErr
443					}
444					apiKey = key
445				}
446			}
447		}
448	}
449	if baseURL == "" {
450		return "", apiKey, nil
451	}
452	baseURL, err = providerpkg.NormalizeLlamaCPPURL(baseURL)
453	return baseURL, apiKey, err
454}
455
456// ResolveCredential returns the credential (api key or oauth access
457// token), the method ("apikey"/"oauth"), and an error when no
458// credential is available.
459//
460// Lookup order:
461//  1. explicit (e.g. --api-key): treated as API key
462//  2. provider-specific env var: treated as API key
463//  3. auth.json: api key OR oauth, whichever is present
464func ResolveCredential(provider, explicit string) (cred, method string, err error) {
465	cred, method, _, err = ResolveCredentialFull(provider, explicit)
466	return cred, method, err
467}
468
469// ResolveCredentialContext is ResolveCredential with caller cancellation.
470func ResolveCredentialContext(ctx context.Context, provider, explicit string) (cred, method string, err error) {
471	cred, method, _, err = ResolveCredentialFullContext(ctx, provider, explicit)
472	return cred, method, err
473}
474
475// ResolveCredentialFull is like ResolveCredential but also returns a
476// provider-specific accountID when the credential is an OpenAI OAuth
477// token (the ChatGPT account id extracted from the stored id_token).
478// accountID is "" for API-key auth and for anthropic.
479func ResolveCredentialFull(provider, explicit string) (cred, method, accountID string, err error) {
480	return ResolveCredentialFullContext(context.Background(), provider, explicit)
481}
482
483// ResolveCredentialFullContext is ResolveCredentialFull with caller cancellation.
484func ResolveCredentialFullContext(ctx context.Context, provider, explicit string) (cred, method, accountID string, err error) {
485	return resolveCredentialFull(ctx, provider, explicit, apiKeyCommandExecute)
486}
487
488type apiKeyCommandMode uint8
489
490const (
491	apiKeyCommandExecute apiKeyCommandMode = iota
492	apiKeyCommandAvailable
493	apiKeyCommandSkip
494)
495
496func resolveCredentialFull(ctx context.Context, provider, explicit string, commandMode apiKeyCommandMode) (cred, method, accountID string, err error) {
497	if explicit != "" {
498		return explicit, "apikey", "", nil
499	}
500	switch provider {
501	case "anthropic":
502		// ANTHROPIC_OAUTH_TOKEN takes precedence over ANTHROPIC_API_KEY.
503		// Useful when both are set and the user wants subscription auth
504		// without editing auth.json.
505		if v := os.Getenv("ANTHROPIC_OAUTH_TOKEN"); v != "" {
506			return v, "oauth", "", nil
507		}
508		if v := os.Getenv("ANTHROPIC_API_KEY"); v != "" {
509			return v, "apikey", "", nil
510		}
511	case "openai":
512		if v := os.Getenv("OPENAI_API_KEY"); v != "" {
513			return v, "apikey", "", nil
514		}
515	case "openai-codex":
516		// ChatGPT/Codex subscription route. It intentionally ignores
517		// OPENAI_API_KEY so users can keep both OpenAI API and Codex
518		// subscription credentials configured and choose by provider.
519	case "openai-responses":
520		// Public OpenAI Responses API. Same env var as the chat-completions
521		// `openai` provider; users pick the wire format by provider id.
522		if v := os.Getenv("OPENAI_API_KEY"); v != "" {
523			return v, "apikey", "", nil
524		}
525	case "kimi":
526		if v := os.Getenv("KIMI_API_KEY"); v != "" {
527			return v, "apikey", "", nil
528		}
529		if v := os.Getenv("MOONSHOT_API_KEY"); v != "" {
530			return v, "apikey", "", nil
531		}
532	case "google":
533		// Both env names are widely-used in the Google ecosystem;
534		// GEMINI_API_KEY is the AI Studio default, GOOGLE_API_KEY
535		// is the older / generic name. Either works.
536		if v := os.Getenv("GEMINI_API_KEY"); v != "" {
537			return v, "apikey", "", nil
538		}
539		if v := os.Getenv("GOOGLE_API_KEY"); v != "" {
540			return v, "apikey", "", nil
541		}
542	case "deepseek":
543		if v := os.Getenv("DEEPSEEK_API_KEY"); v != "" {
544			return v, "apikey", "", nil
545		}
546	// ollama needs no explicit case: the generic
547	// normalizeCustomProviderEnvVar fallback below already maps
548	// provider "ollama" to OLLAMA_API_KEY before auth.json.
549	case "llama.cpp":
550		baseURL, apiKey, resolveErr := resolveLlamaCPPConfig(ctx, commandMode)
551		if resolveErr != nil {
552			return "", "", "", resolveErr
553		}
554		if baseURL != "" {
555			return firstNonEmpty(apiKey, "local"), "apikey", "", nil
556		}
557	case "moonshotai", "moonshotai-cn":
558		// Moonshot direct API (separate from kimi-coding, which is the
559		// Anthropic-Messages-fronted /coding endpoint with subscription OAuth).
560		if v := os.Getenv("MOONSHOT_API_KEY"); v != "" {
561			return v, "apikey", "", nil
562		}
563	case "groq":
564		if v := os.Getenv("GROQ_API_KEY"); v != "" {
565			return v, "apikey", "", nil
566		}
567	case "xai":
568		if v := os.Getenv("XAI_API_KEY"); v != "" {
569			return v, "apikey", "", nil
570		}
571	case "cerebras":
572		if v := os.Getenv("CEREBRAS_API_KEY"); v != "" {
573			return v, "apikey", "", nil
574		}
575	case "together":
576		if v := os.Getenv("TOGETHER_API_KEY"); v != "" {
577			return v, "apikey", "", nil
578		}
579	case "huggingface":
580		if v := os.Getenv("HF_TOKEN"); v != "" {
581			return v, "apikey", "", nil
582		}
583	case "openrouter":
584		if v := os.Getenv("OPENROUTER_API_KEY"); v != "" {
585			return v, "apikey", "", nil
586		}
587	case "mistral":
588		if v := os.Getenv("MISTRAL_API_KEY"); v != "" {
589			return v, "apikey", "", nil
590		}
591	case "zai":
592		if v := os.Getenv("ZAI_API_KEY"); v != "" {
593			return v, "apikey", "", nil
594		}
595	case "xiaomi", "xiaomi-token-plan-ams", "xiaomi-token-plan-cn", "xiaomi-token-plan-sgp":
596		envVar := "XIAOMI_API_KEY"
597		switch provider {
598		case "xiaomi-token-plan-ams":
599			envVar = "XIAOMI_TOKEN_PLAN_AMS_API_KEY"
600		case "xiaomi-token-plan-cn":
601			envVar = "XIAOMI_TOKEN_PLAN_CN_API_KEY"
602		case "xiaomi-token-plan-sgp":
603			envVar = "XIAOMI_TOKEN_PLAN_SGP_API_KEY"
604		}
605		if v := os.Getenv(envVar); v != "" {
606			return v, "apikey", "", nil
607		}
608	case "minimax":
609		if v := os.Getenv("MINIMAX_API_KEY"); v != "" {
610			return v, "apikey", "", nil
611		}
612	case "minimax-cn":
613		if v := os.Getenv("MINIMAX_CN_API_KEY"); v != "" {
614			return v, "apikey", "", nil
615		}
616		if v := os.Getenv("MINIMAX_API_KEY"); v != "" {
617			return v, "apikey", "", nil
618		}
619	case "fireworks":
620		if v := os.Getenv("FIREWORKS_API_KEY"); v != "" {
621			return v, "apikey", "", nil
622		}
623	case "vercel-ai-gateway":
624		if v := os.Getenv("AI_GATEWAY_API_KEY"); v != "" {
625			return v, "apikey", "", nil
626		}
627	case "opencode", "opencode-go":
628		if v := os.Getenv("OPENCODE_API_KEY"); v != "" {
629			return v, "apikey", "", nil
630		}
631	case "github-copilot":
632		if v := os.Getenv("COPILOT_GITHUB_TOKEN"); v != "" {
633			return v, "apikey", "", nil
634		}
635		if v := os.Getenv("GITHUB_COPILOT_TOKEN"); v != "" {
636			return v, "apikey", "", nil
637		}
638	case "cloudflare-workers-ai", "cloudflare-ai-gateway":
639		if v := os.Getenv("CLOUDFLARE_API_KEY"); v != "" {
640			return v, "apikey", "", nil
641		}
642	case "amazon-bedrock":
643		// Bedrock has many credential sources (AWS_PROFILE, IAM keys,
644		// container creds, IRSA, bearer token). We surface a sentinel so
645		// Resolve doesn't error on missing key; the real client (when
646		// implemented) will resolve credentials through aws-sdk-go-v2.
647		if os.Getenv("AWS_ACCESS_KEY_ID") != "" || os.Getenv("AWS_PROFILE") != "" ||
648			os.Getenv("AWS_BEARER_TOKEN_BEDROCK") != "" {
649			return "<aws>", "apikey", "", nil
650		}
651	case "google-vertex":
652		if v := os.Getenv("GOOGLE_CLOUD_API_KEY"); v != "" {
653			return v, "apikey", "", nil
654		}
655		// Check for Application Default Credentials (gcloud auth application-default login)
656		// or service account JSON, matching the actual NewVertex client behavior.
657		if os.Getenv("GOOGLE_APPLICATION_CREDENTIALS") != "" {
658			return "<adc>", "apikey", "", nil
659		}
660		// Check for the platform-specific default ADC path that gcloud writes to.
661		if adcPath, err := auth.GoogleApplicationDefaultCredentialsPath(); err == nil {
662			if _, err := os.Stat(adcPath); err == nil {
663				return "<adc>", "apikey", "", nil
664			}
665		}
666	case "azure-openai-responses":
667		if v := os.Getenv("AZURE_OPENAI_API_KEY"); v != "" {
668			return v, "apikey", "", nil
669		}
670	}
671	// Generic env var fallback for custom providers: normalize the
672	// provider id to a shell-friendly env var name (hyphens to
673	// underscores) and check {NAME}_API_KEY before auth.json.
674	if v := os.Getenv(normalizeCustomProviderEnvVar(provider) + "_API_KEY"); v != "" {
675		return v, "apikey", "", nil
676	}
677	c, err := AuthStoreFor().Load()
678	if err != nil {
679		return "", "", "", err
680	}
681	if pc, ok := storedProviderCreds(c, provider); ok {
682		if key, found, commandErr := resolveStoredAPIKey(ctx, provider, pc, commandMode); found || commandErr != nil {
683			if commandErr != nil {
684				return "", "", "", commandErr
685			}
686			return key, "apikey", "", nil
687		}
688		if provider == "xai" && pc.OAuth != nil && pc.OAuth.AccessToken != "" {
689			tok, _ := refreshIfExpiredContext(ctx, provider, pc.OAuth)
690			return tok.AccessToken, "oauth", "", nil
691		}
692	}
693	switch provider {
694	case "anthropic":
695		if c.Anthropic.OAuth != nil && c.Anthropic.OAuth.AccessToken != "" {
696			tok, _ := refreshIfExpiredContext(ctx, "anthropic", c.Anthropic.OAuth)
697			return tok.AccessToken, "oauth", "", nil
698		}
699	case "openai-codex":
700		if c.OpenAI.OAuth != nil && c.OpenAI.OAuth.AccessToken != "" {
701			tok, _ := refreshIfExpiredContext(ctx, "openai", c.OpenAI.OAuth)
702			return tok.AccessToken, "oauth", tok.AccountID, nil
703		}
704	case "kimi":
705		if c.Kimi.OAuth != nil && c.Kimi.OAuth.AccessToken != "" {
706			tok, _ := refreshIfExpiredContext(ctx, "kimi", c.Kimi.OAuth)
707			return tok.AccessToken, "oauth", "", nil
708		}
709		if kimiCLIFallbackDisabled() {
710			break
711		}
712		if tok := loadKimiCodeCLIToken(); tok != nil && tok.AccessToken != "" {
713			tok, _ = refreshIfExpiredContext(ctx, "kimi", tok)
714			return tok.AccessToken, "oauth", "", nil
715		}
716	case "github-copilot":
717		if c.GithubCopilot.OAuth != nil && c.GithubCopilot.OAuth.AccessToken != "" {
718			return c.GithubCopilot.OAuth.AccessToken, "oauth", "", nil
719		}
720	}
721	return "", "", "", fmt.Errorf("no credential for %s", provider)
722}
723
724// CredentialAvailable reports whether a provider has a configured credential
725// without executing an api_key_command.
726func CredentialAvailable(provider string) bool {
727	_, _, _, err := resolveCredentialFull(context.Background(), provider, "", apiKeyCommandAvailable)
728	return err == nil
729}
730
731func resolveCredentialForBackground(ctx context.Context, provider string) (cred, method string, err error) {
732	cred, method, _, err = resolveCredentialFull(ctx, provider, "", apiKeyCommandSkip)
733	return cred, method, err
734}
735
736func storedProviderCreds(c auth.Credentials, provider string) (auth.ProviderCreds, bool) {
737	if pc, ok := c.AdditionalAPIKeyCreds[provider]; ok {
738		return pc, true
739	}
740	switch provider {
741	case "anthropic":
742		return c.Anthropic, true
743	case "openai":
744		return c.OpenAI, true
745	case "kimi":
746		return c.Kimi, true
747	case "google":
748		return c.Google, true
749	case "deepseek":
750		return c.DeepSeek, true
751	case "github-copilot":
752		return c.GithubCopilot, true
753	default:
754		return auth.ProviderCreds{}, false
755	}
756}
757
758func resolveStoredAPIKey(ctx context.Context, provider string, creds auth.ProviderCreds, mode apiKeyCommandMode) (key string, found bool, err error) {
759	if creds.APIKey != "" {
760		return creds.APIKey, true, nil
761	}
762	if creds.APIKeyCommand == nil {
763		return "", false, nil
764	}
765	switch mode {
766	case apiKeyCommandAvailable:
767		return "<api-key-command>", true, nil
768	case apiKeyCommandSkip:
769		return "", false, nil
770	default:
771		key, err := auth.ResolveAPIKeyCommand(ctx, *creds.APIKeyCommand)
772		if err != nil {
773			return "", true, fmt.Errorf("resolve api key for %s: %w", provider, err)
774		}
775		return key, true, nil
776	}
777}
778
779func kimiCLIFallbackDisabled() bool {
780	_, err := os.Stat(KimiCLIFallbackDisabledPath())
781	return err == nil
782}
783
784func SetKimiCLIFallbackDisabled(disabled bool) error {
785	path := KimiCLIFallbackDisabledPath()
786	if !disabled {
787		if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
788			return err
789		}
790		return nil
791	}
792	if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
793		return err
794	}
795	return os.WriteFile(path, []byte("disabled\n"), 0o600)
796}
797
798// normalizeCustomProviderEnvVar converts a provider id such as
799// "my-company" to "MY_COMPANY", matching the common convention for
800// shell environment variables.
801func normalizeCustomProviderEnvVar(provider string) string {
802	provider = strings.ToUpper(provider)
803	provider = strings.ReplaceAll(provider, "-", "_")
804	return provider
805}
806
807func loadKimiCodeCLIToken() *auth.OAuthToken {
808	home, err := os.UserHomeDir()
809	if err != nil {
810		return nil
811	}
812	b, err := os.ReadFile(filepath.Join(home, ".kimi", "credentials", "kimi-code.json"))
813	if err != nil {
814		return nil
815	}
816	var raw struct {
817		AccessToken  string  `json:"access_token"`
818		RefreshToken string  `json:"refresh_token"`
819		TokenType    string  `json:"token_type"`
820		ExpiresAt    float64 `json:"expires_at"`
821		Scope        string  `json:"scope"`
822		ExpiresIn    float64 `json:"expires_in"`
823	}
824	if err := json.Unmarshal(b, &raw); err != nil || raw.AccessToken == "" {
825		return nil
826	}
827	sec := int64(raw.ExpiresAt)
828	nsec := int64((raw.ExpiresAt - float64(sec)) * 1e9)
829	return &auth.OAuthToken{
830		AccessToken:  raw.AccessToken,
831		RefreshToken: raw.RefreshToken,
832		TokenType:    raw.TokenType,
833		Scope:        raw.Scope,
834		ClientID:     auth.KimiOAuth.ClientID,
835		Expiry:       time.Unix(sec, nsec),
836	}
837}
838
839// loadOAuthToken reads the current OAuth token from auth.json for the
840// given provider. Returns nil if no token is stored.
841func loadOAuthToken(providerName string) *auth.OAuthToken {
842	c, err := AuthStoreFor().Load()
843	if err != nil {
844		return nil
845	}
846	switch providerName {
847	case "anthropic":
848		if c.Anthropic.OAuth != nil {
849			return c.Anthropic.OAuth
850		}
851	case "openai":
852		if c.OpenAI.OAuth != nil {
853			return c.OpenAI.OAuth
854		}
855	case "kimi":
856		if c.Kimi.OAuth != nil {
857			return c.Kimi.OAuth
858		}
859		if kimiCLIFallbackDisabled() {
860			return nil
861		}
862		return loadKimiCodeCLIToken()
863	case "github-copilot":
864		if c.GithubCopilot.OAuth != nil {
865			return c.GithubCopilot.OAuth
866		}
867	}
868	if pc, ok := c.AdditionalAPIKeyCreds[providerName]; ok {
869		return pc.OAuth
870	}
871	return nil
872}
873
874// refreshIfExpired returns a usable OAuth token for the given provider,
875// refreshing it synchronously when it's past (or near) expiry. The
876// refreshed token is persisted to auth.json.
877//
878// Failures return the original token unchanged — the caller then makes
879// a request with the stale access_token, which will 401. That's still
880// better than crashing at credential-resolution time.
881func refreshIfExpired(providerName string, tok *auth.OAuthToken) (*auth.OAuthToken, error) {
882	return refreshIfExpiredContext(context.Background(), providerName, tok)
883}
884
885// refreshIfExpiredContext uses the caller's cancellation deadline while
886// refreshing an expired OAuth token.
887func refreshIfExpiredContext(parent context.Context, providerName string, tok *auth.OAuthToken) (*auth.OAuthToken, error) {
888	if tok == nil {
889		return &auth.OAuthToken{}, fmt.Errorf("nil token")
890	}
891	if !tok.Expired() {
892		return tok, nil
893	}
894	if tok.RefreshToken == "" {
895		return tok, fmt.Errorf("%s oauth token expired and no refresh_token available — run /login again", providerName)
896	}
897
898	if providerName == "xai" {
899		ctx, cancel := context.WithTimeout(parent, 30*time.Second)
900		defer cancel()
901		next, err := auth.RefreshXAIToken(ctx, tok.RefreshToken)
902		if err != nil {
903			return tok, fmt.Errorf("refresh %s: %w", providerName, err)
904		}
905		if next.RefreshToken == "" {
906			next.RefreshToken = tok.RefreshToken
907		}
908		if err := AuthStoreFor().SetOAuth(providerName, *next); err != nil {
909			return next, fmt.Errorf("persist refreshed token: %w", err)
910		}
911		return next, nil
912	}
913
914	var op auth.OAuthProvider
915	switch providerName {
916	case "anthropic":
917		op = auth.AnthropicOAuth
918	case "openai":
919		op = auth.OpenAIOAuth
920	case "kimi":
921		op = auth.KimiOAuth
922	default:
923		return tok, fmt.Errorf("unknown provider %q", providerName)
924	}
925
926	ctx, cancel := context.WithTimeout(parent, 30*time.Second)
927	defer cancel()
928	next, err := op.Refresh(ctx, tok.RefreshToken)
929	if err != nil {
930		return tok, fmt.Errorf("refresh %s: %w", providerName, err)
931	}
932	// Preserve the refresh token if the server omitted it (Anthropic often does).
933	if next.RefreshToken == "" {
934		next.RefreshToken = tok.RefreshToken
935	}
936	// Carry over account id (openai) / id_token across refreshes.
937	if next.AccountID == "" {
938		next.AccountID = tok.AccountID
939	}
940	if next.IDToken == "" {
941		next.IDToken = tok.IDToken
942	}
943	if err := AuthStoreFor().SetOAuth(providerName, *next); err != nil {
944		return next, fmt.Errorf("persist refreshed token: %w", err)
945	}
946	return next, nil
947}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 477

↑↓ moveenter openesc close