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