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 case "llama.cpp":
547 baseURL, apiKey, resolveErr := resolveLlamaCPPConfig(ctx, commandMode)
548 if resolveErr != nil {
549 return "", "", "", resolveErr
550 }
551 if baseURL != "" {
552 return firstNonEmpty(apiKey, "local"), "apikey", "", nil
553 }
554 case "moonshotai", "moonshotai-cn":
555 // Moonshot direct API (separate from kimi-coding, which is the
556 // Anthropic-Messages-fronted /coding endpoint with subscription OAuth).
557 if v := os.Getenv("MOONSHOT_API_KEY"); v != "" {
558 return v, "apikey", "", nil
559 }
560 case "groq":
561 if v := os.Getenv("GROQ_API_KEY"); v != "" {
562 return v, "apikey", "", nil
563 }
564 case "xai":
565 if v := os.Getenv("XAI_API_KEY"); v != "" {
566 return v, "apikey", "", nil
567 }
568 case "cerebras":
569 if v := os.Getenv("CEREBRAS_API_KEY"); v != "" {
570 return v, "apikey", "", nil
571 }
572 case "together":
573 if v := os.Getenv("TOGETHER_API_KEY"); v != "" {
574 return v, "apikey", "", nil
575 }
576 case "huggingface":
577 if v := os.Getenv("HF_TOKEN"); v != "" {
578 return v, "apikey", "", nil
579 }
580 case "openrouter":
581 if v := os.Getenv("OPENROUTER_API_KEY"); v != "" {
582 return v, "apikey", "", nil
583 }
584 case "mistral":
585 if v := os.Getenv("MISTRAL_API_KEY"); v != "" {
586 return v, "apikey", "", nil
587 }
588 case "zai":
589 if v := os.Getenv("ZAI_API_KEY"); v != "" {
590 return v, "apikey", "", nil
591 }
592 case "xiaomi", "xiaomi-token-plan-ams", "xiaomi-token-plan-cn", "xiaomi-token-plan-sgp":
593 envVar := "XIAOMI_API_KEY"
594 switch provider {
595 case "xiaomi-token-plan-ams":
596 envVar = "XIAOMI_TOKEN_PLAN_AMS_API_KEY"
597 case "xiaomi-token-plan-cn":
598 envVar = "XIAOMI_TOKEN_PLAN_CN_API_KEY"
599 case "xiaomi-token-plan-sgp":
600 envVar = "XIAOMI_TOKEN_PLAN_SGP_API_KEY"
601 }
602 if v := os.Getenv(envVar); v != "" {
603 return v, "apikey", "", nil
604 }
605 case "minimax":
606 if v := os.Getenv("MINIMAX_API_KEY"); v != "" {
607 return v, "apikey", "", nil
608 }
609 case "minimax-cn":
610 if v := os.Getenv("MINIMAX_CN_API_KEY"); v != "" {
611 return v, "apikey", "", nil
612 }
613 if v := os.Getenv("MINIMAX_API_KEY"); v != "" {
614 return v, "apikey", "", nil
615 }
616 case "fireworks":
617 if v := os.Getenv("FIREWORKS_API_KEY"); v != "" {
618 return v, "apikey", "", nil
619 }
620 case "vercel-ai-gateway":
621 if v := os.Getenv("AI_GATEWAY_API_KEY"); v != "" {
622 return v, "apikey", "", nil
623 }
624 case "opencode", "opencode-go":
625 if v := os.Getenv("OPENCODE_API_KEY"); v != "" {
626 return v, "apikey", "", nil
627 }
628 case "github-copilot":
629 if v := os.Getenv("COPILOT_GITHUB_TOKEN"); v != "" {
630 return v, "apikey", "", nil
631 }
632 if v := os.Getenv("GITHUB_COPILOT_TOKEN"); v != "" {
633 return v, "apikey", "", nil
634 }
635 case "cloudflare-workers-ai", "cloudflare-ai-gateway":
636 if v := os.Getenv("CLOUDFLARE_API_KEY"); v != "" {
637 return v, "apikey", "", nil
638 }
639 case "amazon-bedrock":
640 // Bedrock has many credential sources (AWS_PROFILE, IAM keys,
641 // container creds, IRSA, bearer token). We surface a sentinel so
642 // Resolve doesn't error on missing key; the real client (when
643 // implemented) will resolve credentials through aws-sdk-go-v2.
644 if os.Getenv("AWS_ACCESS_KEY_ID") != "" || os.Getenv("AWS_PROFILE") != "" ||
645 os.Getenv("AWS_BEARER_TOKEN_BEDROCK") != "" {
646 return "<aws>", "apikey", "", nil
647 }
648 case "google-vertex":
649 if v := os.Getenv("GOOGLE_CLOUD_API_KEY"); v != "" {
650 return v, "apikey", "", nil
651 }
652 // Check for Application Default Credentials (gcloud auth application-default login)
653 // or service account JSON, matching the actual NewVertex client behavior.
654 if os.Getenv("GOOGLE_APPLICATION_CREDENTIALS") != "" {
655 return "<adc>", "apikey", "", nil
656 }
657 // Check for the platform-specific default ADC path that gcloud writes to.
658 if adcPath, err := auth.GoogleApplicationDefaultCredentialsPath(); err == nil {
659 if _, err := os.Stat(adcPath); err == nil {
660 return "<adc>", "apikey", "", nil
661 }
662 }
663 case "azure-openai-responses":
664 if v := os.Getenv("AZURE_OPENAI_API_KEY"); v != "" {
665 return v, "apikey", "", nil
666 }
667 }
668 // Generic env var fallback for custom providers: normalize the
669 // provider id to a shell-friendly env var name (hyphens to
670 // underscores) and check {NAME}_API_KEY before auth.json.
671 if v := os.Getenv(normalizeCustomProviderEnvVar(provider) + "_API_KEY"); v != "" {
672 return v, "apikey", "", nil
673 }
674 c, err := AuthStoreFor().Load()
675 if err != nil {
676 return "", "", "", err
677 }
678 if pc, ok := storedProviderCreds(c, provider); ok {
679 if key, found, commandErr := resolveStoredAPIKey(ctx, provider, pc, commandMode); found || commandErr != nil {
680 if commandErr != nil {
681 return "", "", "", commandErr
682 }
683 return key, "apikey", "", nil
684 }
685 if provider == "xai" && pc.OAuth != nil && pc.OAuth.AccessToken != "" {
686 tok, _ := refreshIfExpiredContext(ctx, provider, pc.OAuth)
687 return tok.AccessToken, "oauth", "", nil
688 }
689 }
690 switch provider {
691 case "anthropic":
692 if c.Anthropic.OAuth != nil && c.Anthropic.OAuth.AccessToken != "" {
693 tok, _ := refreshIfExpiredContext(ctx, "anthropic", c.Anthropic.OAuth)
694 return tok.AccessToken, "oauth", "", nil
695 }
696 case "openai-codex":
697 if c.OpenAI.OAuth != nil && c.OpenAI.OAuth.AccessToken != "" {
698 tok, _ := refreshIfExpiredContext(ctx, "openai", c.OpenAI.OAuth)
699 return tok.AccessToken, "oauth", tok.AccountID, nil
700 }
701 case "kimi":
702 if c.Kimi.OAuth != nil && c.Kimi.OAuth.AccessToken != "" {
703 tok, _ := refreshIfExpiredContext(ctx, "kimi", c.Kimi.OAuth)
704 return tok.AccessToken, "oauth", "", nil
705 }
706 if kimiCLIFallbackDisabled() {
707 break
708 }
709 if tok := loadKimiCodeCLIToken(); tok != nil && tok.AccessToken != "" {
710 tok, _ = refreshIfExpiredContext(ctx, "kimi", tok)
711 return tok.AccessToken, "oauth", "", nil
712 }
713 case "github-copilot":
714 if c.GithubCopilot.OAuth != nil && c.GithubCopilot.OAuth.AccessToken != "" {
715 return c.GithubCopilot.OAuth.AccessToken, "oauth", "", nil
716 }
717 }
718 return "", "", "", fmt.Errorf("no credential for %s", provider)
719}
720
721// CredentialAvailable reports whether a provider has a configured credential
722// without executing an api_key_command.
723func CredentialAvailable(provider string) bool {
724 _, _, _, err := resolveCredentialFull(context.Background(), provider, "", apiKeyCommandAvailable)
725 return err == nil
726}
727
728func resolveCredentialForBackground(ctx context.Context, provider string) (cred, method string, err error) {
729 cred, method, _, err = resolveCredentialFull(ctx, provider, "", apiKeyCommandSkip)
730 return cred, method, err
731}
732
733func storedProviderCreds(c auth.Credentials, provider string) (auth.ProviderCreds, bool) {
734 if pc, ok := c.AdditionalAPIKeyCreds[provider]; ok {
735 return pc, true
736 }
737 switch provider {
738 case "anthropic":
739 return c.Anthropic, true
740 case "openai":
741 return c.OpenAI, true
742 case "kimi":
743 return c.Kimi, true
744 case "google":
745 return c.Google, true
746 case "deepseek":
747 return c.DeepSeek, true
748 case "github-copilot":
749 return c.GithubCopilot, true
750 default:
751 return auth.ProviderCreds{}, false
752 }
753}
754
755func resolveStoredAPIKey(ctx context.Context, provider string, creds auth.ProviderCreds, mode apiKeyCommandMode) (key string, found bool, err error) {
756 if creds.APIKey != "" {
757 return creds.APIKey, true, nil
758 }
759 if creds.APIKeyCommand == nil {
760 return "", false, nil
761 }
762 switch mode {
763 case apiKeyCommandAvailable:
764 return "<api-key-command>", true, nil
765 case apiKeyCommandSkip:
766 return "", false, nil
767 default:
768 key, err := auth.ResolveAPIKeyCommand(ctx, *creds.APIKeyCommand)
769 if err != nil {
770 return "", true, fmt.Errorf("resolve api key for %s: %w", provider, err)
771 }
772 return key, true, nil
773 }
774}
775
776func kimiCLIFallbackDisabled() bool {
777 _, err := os.Stat(KimiCLIFallbackDisabledPath())
778 return err == nil
779}
780
781func SetKimiCLIFallbackDisabled(disabled bool) error {
782 path := KimiCLIFallbackDisabledPath()
783 if !disabled {
784 if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
785 return err
786 }
787 return nil
788 }
789 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
790 return err
791 }
792 return os.WriteFile(path, []byte("disabled\n"), 0o600)
793}
794
795// normalizeCustomProviderEnvVar converts a provider id such as
796// "my-company" to "MY_COMPANY", matching the common convention for
797// shell environment variables.
798func normalizeCustomProviderEnvVar(provider string) string {
799 provider = strings.ToUpper(provider)
800 provider = strings.ReplaceAll(provider, "-", "_")
801 return provider
802}
803
804func loadKimiCodeCLIToken() *auth.OAuthToken {
805 home, err := os.UserHomeDir()
806 if err != nil {
807 return nil
808 }
809 b, err := os.ReadFile(filepath.Join(home, ".kimi", "credentials", "kimi-code.json"))
810 if err != nil {
811 return nil
812 }
813 var raw struct {
814 AccessToken string `json:"access_token"`
815 RefreshToken string `json:"refresh_token"`
816 TokenType string `json:"token_type"`
817 ExpiresAt float64 `json:"expires_at"`
818 Scope string `json:"scope"`
819 ExpiresIn float64 `json:"expires_in"`
820 }
821 if err := json.Unmarshal(b, &raw); err != nil || raw.AccessToken == "" {
822 return nil
823 }
824 sec := int64(raw.ExpiresAt)
825 nsec := int64((raw.ExpiresAt - float64(sec)) * 1e9)
826 return &auth.OAuthToken{
827 AccessToken: raw.AccessToken,
828 RefreshToken: raw.RefreshToken,
829 TokenType: raw.TokenType,
830 Scope: raw.Scope,
831 ClientID: auth.KimiOAuth.ClientID,
832 Expiry: time.Unix(sec, nsec),
833 }
834}
835
836// loadOAuthToken reads the current OAuth token from auth.json for the
837// given provider. Returns nil if no token is stored.
838func loadOAuthToken(providerName string) *auth.OAuthToken {
839 c, err := AuthStoreFor().Load()
840 if err != nil {
841 return nil
842 }
843 switch providerName {
844 case "anthropic":
845 if c.Anthropic.OAuth != nil {
846 return c.Anthropic.OAuth
847 }
848 case "openai":
849 if c.OpenAI.OAuth != nil {
850 return c.OpenAI.OAuth
851 }
852 case "kimi":
853 if c.Kimi.OAuth != nil {
854 return c.Kimi.OAuth
855 }
856 if kimiCLIFallbackDisabled() {
857 return nil
858 }
859 return loadKimiCodeCLIToken()
860 case "github-copilot":
861 if c.GithubCopilot.OAuth != nil {
862 return c.GithubCopilot.OAuth
863 }
864 }
865 if pc, ok := c.AdditionalAPIKeyCreds[providerName]; ok {
866 return pc.OAuth
867 }
868 return nil
869}
870
871// refreshIfExpired returns a usable OAuth token for the given provider,
872// refreshing it synchronously when it's past (or near) expiry. The
873// refreshed token is persisted to auth.json.
874//
875// Failures return the original token unchanged — the caller then makes
876// a request with the stale access_token, which will 401. That's still
877// better than crashing at credential-resolution time.
878func refreshIfExpired(providerName string, tok *auth.OAuthToken) (*auth.OAuthToken, error) {
879 return refreshIfExpiredContext(context.Background(), providerName, tok)
880}
881
882// refreshIfExpiredContext uses the caller's cancellation deadline while
883// refreshing an expired OAuth token.
884func refreshIfExpiredContext(parent context.Context, providerName string, tok *auth.OAuthToken) (*auth.OAuthToken, error) {
885 if tok == nil {
886 return &auth.OAuthToken{}, fmt.Errorf("nil token")
887 }
888 if !tok.Expired() {
889 return tok, nil
890 }
891 if tok.RefreshToken == "" {
892 return tok, fmt.Errorf("%s oauth token expired and no refresh_token available — run /login again", providerName)
893 }
894
895 if providerName == "xai" {
896 ctx, cancel := context.WithTimeout(parent, 30*time.Second)
897 defer cancel()
898 next, err := auth.RefreshXAIToken(ctx, tok.RefreshToken)
899 if err != nil {
900 return tok, fmt.Errorf("refresh %s: %w", providerName, err)
901 }
902 if next.RefreshToken == "" {
903 next.RefreshToken = tok.RefreshToken
904 }
905 if err := AuthStoreFor().SetOAuth(providerName, *next); err != nil {
906 return next, fmt.Errorf("persist refreshed token: %w", err)
907 }
908 return next, nil
909 }
910
911 var op auth.OAuthProvider
912 switch providerName {
913 case "anthropic":
914 op = auth.AnthropicOAuth
915 case "openai":
916 op = auth.OpenAIOAuth
917 case "kimi":
918 op = auth.KimiOAuth
919 default:
920 return tok, fmt.Errorf("unknown provider %q", providerName)
921 }
922
923 ctx, cancel := context.WithTimeout(parent, 30*time.Second)
924 defer cancel()
925 next, err := op.Refresh(ctx, tok.RefreshToken)
926 if err != nil {
927 return tok, fmt.Errorf("refresh %s: %w", providerName, err)
928 }
929 // Preserve the refresh token if the server omitted it (Anthropic often does).
930 if next.RefreshToken == "" {
931 next.RefreshToken = tok.RefreshToken
932 }
933 // Carry over account id (openai) / id_token across refreshes.
934 if next.AccountID == "" {
935 next.AccountID = tok.AccountID
936 }
937 if next.IDToken == "" {
938 next.IDToken = tok.IDToken
939 }
940 if err := AuthStoreFor().SetOAuth(providerName, *next); err != nil {
941 return next, fmt.Errorf("persist refreshed token: %w", err)
942 }
943 return next, nil
944}