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 disabled to keep multi-edit sequences quiet.
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 // Insecure skips TLS verification for custom inference endpoints.
180 Insecure bool `json:"insecure,omitempty"`
181
182 // HTTPProxy is a global proxy URL used for HTTP and HTTPS requests when
183 // the corresponding standard proxy environment variable is not already set.
184 HTTPProxy string `json:"http_proxy,omitempty"`
185
186 // LastChangelogShown is the version whose release-notes
187 // dialog the user has already seen. When the running binary's
188 // version differs, the next interactive run shows the
189 // changelog (fetched from the GitHub release page) once and
190 // updates this field. Empty means "never shown".
191 LastChangelogShown string `json:"last_changelog_shown,omitempty"`
192}
193
194// ZutHome returns $ZUT_HOME or the OS-default data dir.
195//
196// All zut state (config.json, auth.json, sessions/, logs/) lives under
197// this directory.
198func ZutHome() string {
199 if v := os.Getenv("ZUT_HOME"); v != "" {
200 return v
201 }
202 if v := os.Getenv("XDG_STATE_HOME"); v != "" {
203 return filepath.Join(v, "zut")
204 }
205 switch runtime.GOOS {
206 case "darwin":
207 if home, err := os.UserHomeDir(); err == nil {
208 return filepath.Join(home, "Library", "Application Support", "zut")
209 }
210 case "windows":
211 if v := os.Getenv("LOCALAPPDATA"); v != "" {
212 return filepath.Join(v, "zut")
213 }
214 }
215 if home, err := os.UserHomeDir(); err == nil {
216 return filepath.Join(home, ".local", "state", "zut")
217 }
218 return ".zut"
219}
220
221// ConfigPath returns the path to config.json.
222func ConfigPath() string { return filepath.Join(ZutHome(), "config.json") }
223
224// FlatToolRender reports whether tool calls should render flat (no
225// bordered panel). The ZUT_FLAT_TOOLS env var takes precedence over
226// the config when set: "1"/"true"/"yes"/"on" force flat, "0"/"false"/
227// "no"/"off" force box. Otherwise the config's tool_render is
228// consulted; "flat" is flat, anything else (including empty) is box.
229func (c Config) FlatToolRender() bool {
230 if v := strings.TrimSpace(strings.ToLower(os.Getenv("ZUT_FLAT_TOOLS"))); v != "" {
231 switch v {
232 case "1", "true", "yes", "on", "flat":
233 return true
234 case "0", "false", "no", "off", "box":
235 return false
236 }
237 }
238 return strings.EqualFold(strings.TrimSpace(c.ToolRender), "flat")
239}
240
241// CompactUserInput reports whether sent user messages should render as
242// a single quiet gutter line instead of a padded, background-tinted
243// bubble. The ZUT_COMPACT_INPUT env var takes precedence over the
244// config when set: "1"/"true"/"yes"/"on" force compact, "0"/"false"/
245// "no"/"off" force the bubble. Otherwise the config's compact_input
246// is consulted (nil/false means the bubble).
247func (c Config) CompactUserInput() bool {
248 if v := strings.TrimSpace(strings.ToLower(os.Getenv("ZUT_COMPACT_INPUT"))); v != "" {
249 switch v {
250 case "1", "true", "yes", "on", "compact":
251 return true
252 case "0", "false", "no", "off", "bubble":
253 return false
254 }
255 }
256 return c.CompactInput != nil && *c.CompactInput
257}
258
259// LSPEnabledFor reports whether LSP is enabled for a main or subagent
260// sub-agent session. Both settings default to true so new installations
261// get code intelligence without a migration or generated config file.
262func (c Config) LSPEnabledFor(subagent bool) bool {
263 value := c.LSPEnabled
264 if subagent {
265 value = c.SubagentLSPEnabled
266 }
267 return value == nil || *value
268}
269
270// PonytailModeEnabled reports the default-on coding-guidance preference
271// without requiring a generated config entry.
272func (c Config) PonytailModeEnabled() bool {
273 return c.PonytailEnabled == nil || *c.PonytailEnabled
274}
275
276// WebSearchEnabledForCLI reports the default-on web-search preference
277// without requiring a generated config entry.
278func (c Config) WebSearchEnabledForCLI() bool {
279 return c.WebSearchEnabled == nil || *c.WebSearchEnabled
280}
281
282// LSPDiagnosticsOnWriteEnabled reports the default-on write diagnostics
283// preference without requiring a generated config entry.
284func (c Config) LSPDiagnosticsOnWriteEnabled(subagent bool) bool {
285 return c.LSPEnabledFor(subagent) && (c.LSPDiagnosticsOnWrite == nil || *c.LSPDiagnosticsOnWrite)
286}
287
288// LSPDiagnosticsOnEditEnabled reports the default-off edit diagnostics
289// preference without requiring a generated config entry.
290func (c Config) LSPDiagnosticsOnEditEnabled(subagent bool) bool {
291 return c.LSPEnabledFor(subagent) && c.LSPDiagnosticsOnEdit != nil && *c.LSPDiagnosticsOnEdit
292}
293
294// AuthPath returns the path to auth.json.
295func AuthPath() string { return filepath.Join(ZutHome(), "auth.json") }
296
297// KimiCLIFallbackDisabledPath returns a sentinel that disables falling
298// back to the official Kimi Code CLI token after `zut /logout kimi`.
299func KimiCLIFallbackDisabledPath() string {
300 return filepath.Join(ZutHome(), "kimi-cli-fallback-disabled")
301}
302
303// SessionsPath returns the directory holding session files.
304func SessionsPath() string { return filepath.Join(ZutHome(), "sessions") }
305
306// LogsPath returns the directory holding log files.
307func LogsPath() string { return filepath.Join(ZutHome(), "logs") }
308
309// LoadConfig reads the config file, returning defaults if missing.
310func LoadConfig() (Config, error) {
311 var c Config
312 b, err := os.ReadFile(ConfigPath())
313 if errors.Is(err, os.ErrNotExist) {
314 return c, nil
315 }
316 if err != nil {
317 return c, err
318 }
319 if err := json.Unmarshal(b, &c); err != nil {
320 return c, fmt.Errorf("parse config: %w", err)
321 }
322 if err := validateSubagentConfig(c.Subagents); err != nil {
323 return c, err
324 }
325 return c, nil
326}
327
328// normalizedModelProfile keeps startup defaults and the TUI's copy consistent.
329// Unknown/open-catalog models retain their configured reasoning until resolved.
330func normalizedModelProfile(p QuickModelShortcut) QuickModelShortcut {
331 p.Provider = canonicalProvider(p.Provider)
332 p.Reasoning = providerpkg.NormalizeReasoning(p.Reasoning)
333 if model, err := providerpkg.FindModel(p.Provider, p.Model); err == nil {
334 p.Reasoning = providerpkg.ClampReasoningForModel(model, p.Reasoning)
335 }
336 return p
337}
338
339// applyActiveModelProfile supplies defaults without rewriting the config and
340// returns their source slot (0 when none). Explicit flags retain precedence.
341func (c *Config) applyActiveModelProfile() int {
342 slot := c.ActiveModelProfile
343 if slot < 1 || slot > 9 {
344 slot = 1
345 }
346 if slot > len(c.QuickModelShortcuts) {
347 return 0
348 }
349 p := normalizedModelProfile(c.QuickModelShortcuts[slot-1])
350 if p.Provider == "" || p.Model == "" {
351 return 0
352 }
353 c.Provider, c.Model, c.Reasoning = p.Provider, p.Model, p.Reasoning
354 fastMode := p.FastMode
355 c.FastMode = &fastMode
356 return slot
357}
358
359func validateSubagentConfig(cfg SubagentsConfig) error {
360 values := []struct {
361 name string
362 value string
363 }{
364 {"queue_timeout", cfg.QueueTimeout},
365 }
366 for _, item := range values {
367 value := strings.TrimSpace(item.value)
368 if value == "" {
369 continue
370 }
371 if _, err := time.ParseDuration(value); err != nil {
372 return fmt.Errorf("parse config: subagents.%s: %w", item.name, err)
373 }
374 }
375 return nil
376}
377
378// SaveConfig writes the config file, creating parent dirs.
379func SaveConfig(c Config) error {
380 if err := os.MkdirAll(ZutHome(), 0o755); err != nil {
381 return err
382 }
383 b, err := json.MarshalIndent(c, "", " ")
384 if err != nil {
385 return err
386 }
387 return os.WriteFile(ConfigPath(), b, 0o644)
388}
389
390// applyConfiguredHTTPProxy makes the persisted proxy available to Go's
391// standard HTTP transport and to child processes. Explicit environment
392// variables take precedence over config.json.
393func applyConfiguredHTTPProxy() {
394 cfg, err := LoadConfig()
395 if err != nil {
396 return
397 }
398 proxy := strings.TrimSpace(cfg.HTTPProxy)
399 if proxy == "" {
400 return
401 }
402 if os.Getenv("HTTP_PROXY") == "" && os.Getenv("http_proxy") == "" {
403 _ = os.Setenv("HTTP_PROXY", proxy)
404 }
405 if os.Getenv("HTTPS_PROXY") == "" && os.Getenv("https_proxy") == "" {
406 _ = os.Setenv("HTTPS_PROXY", proxy)
407 }
408}
409
410// AuthStoreFor returns the auth.Store backed by AuthPath().
411func AuthStoreFor() *auth.Store { return auth.NewStore(AuthPath()) }
412
413// ResolveLlamaCPPConfig resolves the router URL and optional API key. The
414// environment overrides the credential stored through /login.
415func ResolveLlamaCPPConfig() (baseURL, apiKey string, err error) {
416 return resolveLlamaCPPConfig(context.Background(), apiKeyCommandExecute)
417}
418
419func resolveLlamaCPPConfig(ctx context.Context, commandMode apiKeyCommandMode) (baseURL, apiKey string, err error) {
420 baseURL = strings.TrimSpace(os.Getenv("LLAMA_BASE_URL"))
421 apiKey = strings.TrimSpace(os.Getenv("LLAMA_API_KEY"))
422 if baseURL == "" {
423 creds, loadErr := AuthStoreFor().Load()
424 if loadErr != nil {
425 return "", "", loadErr
426 }
427 if stored, ok := creds.AdditionalAPIKeyCreds[providerpkg.LlamaCPPProviderID]; ok {
428 baseURL = stored.BaseURL
429 if apiKey == "" {
430 if stored.APIKeyCommand != nil && commandMode == apiKeyCommandSkip {
431 return "", "", nil
432 }
433 if key, found, commandErr := resolveStoredAPIKey(ctx, providerpkg.LlamaCPPProviderID, stored, commandMode); found || commandErr != nil {
434 if commandErr != nil {
435 return "", "", commandErr
436 }
437 apiKey = key
438 }
439 }
440 }
441 }
442 if baseURL == "" {
443 return "", apiKey, nil
444 }
445 baseURL, err = providerpkg.NormalizeLlamaCPPURL(baseURL)
446 return baseURL, apiKey, err
447}
448
449// ResolveCredential returns the credential (api key or oauth access
450// token), the method ("apikey"/"oauth"), and an error when no
451// credential is available.
452//
453// Lookup order:
454// 1. explicit (e.g. --api-key): treated as API key
455// 2. provider-specific env var: treated as API key
456// 3. auth.json: api key OR oauth, whichever is present
457func ResolveCredential(provider, explicit string) (cred, method string, err error) {
458 cred, method, _, err = ResolveCredentialFull(provider, explicit)
459 return cred, method, err
460}
461
462// ResolveCredentialContext is ResolveCredential with caller cancellation.
463func ResolveCredentialContext(ctx context.Context, provider, explicit string) (cred, method string, err error) {
464 cred, method, _, err = ResolveCredentialFullContext(ctx, provider, explicit)
465 return cred, method, err
466}
467
468// ResolveCredentialFull is like ResolveCredential but also returns a
469// provider-specific accountID when the credential is an OpenAI OAuth
470// token (the ChatGPT account id extracted from the stored id_token).
471// accountID is "" for API-key auth and for anthropic.
472func ResolveCredentialFull(provider, explicit string) (cred, method, accountID string, err error) {
473 return ResolveCredentialFullContext(context.Background(), provider, explicit)
474}
475
476// ResolveCredentialFullContext is ResolveCredentialFull with caller cancellation.
477func ResolveCredentialFullContext(ctx context.Context, provider, explicit string) (cred, method, accountID string, err error) {
478 return resolveCredentialFull(ctx, provider, explicit, apiKeyCommandExecute)
479}
480
481type apiKeyCommandMode uint8
482
483const (
484 apiKeyCommandExecute apiKeyCommandMode = iota
485 apiKeyCommandAvailable
486 apiKeyCommandSkip
487)
488
489func resolveCredentialFull(ctx context.Context, provider, explicit string, commandMode apiKeyCommandMode) (cred, method, accountID string, err error) {
490 if explicit != "" {
491 return explicit, "apikey", "", nil
492 }
493 switch provider {
494 case "anthropic":
495 // ANTHROPIC_OAUTH_TOKEN takes precedence over ANTHROPIC_API_KEY.
496 // Useful when both are set and the user wants subscription auth
497 // without editing auth.json.
498 if v := os.Getenv("ANTHROPIC_OAUTH_TOKEN"); v != "" {
499 return v, "oauth", "", nil
500 }
501 if v := os.Getenv("ANTHROPIC_API_KEY"); v != "" {
502 return v, "apikey", "", nil
503 }
504 case "openai":
505 if v := os.Getenv("OPENAI_API_KEY"); v != "" {
506 return v, "apikey", "", nil
507 }
508 case "openai-codex":
509 // ChatGPT/Codex subscription route. It intentionally ignores
510 // OPENAI_API_KEY so users can keep both OpenAI API and Codex
511 // subscription credentials configured and choose by provider.
512 case "openai-responses":
513 // Public OpenAI Responses API. Same env var as the chat-completions
514 // `openai` provider; users pick the wire format by provider id.
515 if v := os.Getenv("OPENAI_API_KEY"); v != "" {
516 return v, "apikey", "", nil
517 }
518 case "kimi":
519 if v := os.Getenv("KIMI_API_KEY"); v != "" {
520 return v, "apikey", "", nil
521 }
522 if v := os.Getenv("MOONSHOT_API_KEY"); v != "" {
523 return v, "apikey", "", nil
524 }
525 case "google":
526 // Both env names are widely-used in the Google ecosystem;
527 // GEMINI_API_KEY is the AI Studio default, GOOGLE_API_KEY
528 // is the older / generic name. Either works.
529 if v := os.Getenv("GEMINI_API_KEY"); v != "" {
530 return v, "apikey", "", nil
531 }
532 if v := os.Getenv("GOOGLE_API_KEY"); v != "" {
533 return v, "apikey", "", nil
534 }
535 case "deepseek":
536 if v := os.Getenv("DEEPSEEK_API_KEY"); v != "" {
537 return v, "apikey", "", nil
538 }
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}