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 keyboard shortcut slot.
20type QuickModelShortcut struct {
21 Provider string `json:"provider"`
22 Model string `json:"model"`
23}
24
25// SubagentsConfig contains the persisted supervisor policy. Duration values
26// use Go strings such as "20m" so config files remain readable.
27type SubagentsConfig struct {
28 MaxConcurrent int `json:"max_concurrent,omitempty"`
29 MaxConcurrentPerParent int `json:"max_concurrent_per_parent,omitempty"`
30 QueueTimeout string `json:"queue_timeout,omitempty"`
31 StartupTimeout string `json:"startup_timeout,omitempty"`
32 DefaultTimeout string `json:"default_timeout,omitempty"`
33 MaxOutputBytes int `json:"max_output_bytes,omitempty"`
34 MaxOutputLines int `json:"max_output_lines,omitempty"`
35 AllowedTools []string `json:"allowed_tools,omitempty"`
36 AllowedRoots []string `json:"allowed_roots,omitempty"`
37 HeartbeatInterval string `json:"heartbeat_interval,omitempty"`
38 IdleTimeout string `json:"idle_timeout,omitempty"`
39 ReconnectTimeout string `json:"reconnect_timeout,omitempty"`
40 CancelGracePeriod string `json:"cancel_grace_period,omitempty"`
41
42 // MaxTotalSpawned is retained only to accept existing configuration.
43 // Lifetime total-spawn budgets are no longer enforced.
44 MaxTotalSpawned int `json:"max_total_spawned,omitempty"`
45}
46
47// Config is the persisted user configuration.
48type Config struct {
49 Provider string `json:"provider"`
50 Model string `json:"model"`
51 Reasoning string `json:"reasoning"`
52 Temperature *float32 `json:"temperature,omitempty"`
53 Theme string `json:"theme"`
54
55 // FastMode requests OpenAI's fast service tier. Off by default;
56 // nil/missing means disabled. Other providers reject fast-mode
57 // requests at the provider boundary.
58 FastMode *bool `json:"fast_mode,omitempty"`
59
60 // ToolRender selects how tool calls are drawn in interactive mode.
61 // "box" (default, or empty) wraps each call in a bordered panel;
62 // "flat" drops the frame for a quiet header line plus indented,
63 // frameless output. The ZUT_FLAT_TOOLS env var overrides this when
64 // set ("1"/"true" forces flat, "0"/"false" forces box).
65 ToolRender string `json:"tool_render,omitempty"`
66
67 // CompactInput renders sent user messages as a single quiet gutter
68 // line instead of a padded, background-tinted bubble. nil/false
69 // (the default) keeps the bubble. The ZUT_COMPACT_INPUT env var
70 // overrides this when set.
71 CompactInput *bool `json:"compact_input,omitempty"`
72
73 // QuickModelShortcuts maps slots 1-9 to provider/model pairs used by
74 // Ctrl+1..9. Cmd+1..9 may also work on terminals that forward Super.
75 QuickModelShortcuts []QuickModelShortcut `json:"quick_model_shortcuts,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 // AutoSubagentsEnabled lets the main agent spawn background sub-agents
97 // and query their live state via built-in auto-subagent tools. Off by
98 // default; nil/missing means disabled. Toggle from /settings.
99 AutoSubagentsEnabled *bool `json:"auto_subagents_enabled,omitempty"`
100
101 // PonytailEnabled controls the compact coding-guidance addendum. On by
102 // default; nil/missing means enabled. Toggle from /settings.
103 PonytailEnabled *bool `json:"ponytail_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 subagent worker
116 // processes. 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 disabled to keep multi-edit sequences quiet.
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 // TUISubagentPosition controls whether live subagent activity renders
176 // above or below the main input. Supported values: "above_input" and
177 // "below_input" (default).
178 TUISubagentPosition string `json:"tui_subagent_position,omitempty"`
179
180 // Insecure skips TLS verification for custom inference endpoints.
181 Insecure bool `json:"insecure,omitempty"`
182
183 // HTTPProxy is a global proxy URL used for HTTP and HTTPS requests when
184 // the corresponding standard proxy environment variable is not already set.
185 HTTPProxy string `json:"http_proxy,omitempty"`
186
187 // LastChangelogShown is the version whose release-notes
188 // dialog the user has already seen. When the running binary's
189 // version differs, the next interactive run shows the
190 // changelog (fetched from the GitHub release page) once and
191 // updates this field. Empty means "never shown".
192 LastChangelogShown string `json:"last_changelog_shown,omitempty"`
193}
194
195// ZutHome returns $ZUT_HOME or the OS-default data dir.
196//
197// All zut state (config.json, auth.json, sessions/, logs/) lives under
198// this directory.
199func ZutHome() string {
200 if v := os.Getenv("ZUT_HOME"); v != "" {
201 return v
202 }
203 if v := os.Getenv("XDG_STATE_HOME"); v != "" {
204 return filepath.Join(v, "zut")
205 }
206 switch runtime.GOOS {
207 case "darwin":
208 if home, err := os.UserHomeDir(); err == nil {
209 return filepath.Join(home, "Library", "Application Support", "zut")
210 }
211 case "windows":
212 if v := os.Getenv("LOCALAPPDATA"); v != "" {
213 return filepath.Join(v, "zut")
214 }
215 }
216 if home, err := os.UserHomeDir(); err == nil {
217 return filepath.Join(home, ".local", "state", "zut")
218 }
219 return ".zut"
220}
221
222// ConfigPath returns the path to config.json.
223func ConfigPath() string { return filepath.Join(ZutHome(), "config.json") }
224
225// FlatToolRender reports whether tool calls should render flat (no
226// bordered panel). The ZUT_FLAT_TOOLS env var takes precedence over
227// the config when set: "1"/"true"/"yes"/"on" force flat, "0"/"false"/
228// "no"/"off" force box. Otherwise the config's tool_render is
229// consulted; "flat" is flat, anything else (including empty) is box.
230func (c Config) FlatToolRender() bool {
231 if v := strings.TrimSpace(strings.ToLower(os.Getenv("ZUT_FLAT_TOOLS"))); v != "" {
232 switch v {
233 case "1", "true", "yes", "on", "flat":
234 return true
235 case "0", "false", "no", "off", "box":
236 return false
237 }
238 }
239 return strings.EqualFold(strings.TrimSpace(c.ToolRender), "flat")
240}
241
242// CompactUserInput reports whether sent user messages should render as
243// a single quiet gutter line instead of a padded, background-tinted
244// bubble. The ZUT_COMPACT_INPUT env var takes precedence over the
245// config when set: "1"/"true"/"yes"/"on" force compact, "0"/"false"/
246// "no"/"off" force the bubble. Otherwise the config's compact_input
247// is consulted (nil/false means the bubble).
248func (c Config) CompactUserInput() bool {
249 if v := strings.TrimSpace(strings.ToLower(os.Getenv("ZUT_COMPACT_INPUT"))); v != "" {
250 switch v {
251 case "1", "true", "yes", "on", "compact":
252 return true
253 case "0", "false", "no", "off", "bubble":
254 return false
255 }
256 }
257 return c.CompactInput != nil && *c.CompactInput
258}
259
260// LSPEnabledFor reports whether LSP is enabled for a main or subagent
261// sub-agent session. Both settings default to true so new installations
262// get code intelligence without a migration or generated config file.
263func (c Config) LSPEnabledFor(subagent bool) bool {
264 value := c.LSPEnabled
265 if subagent {
266 value = c.SubagentLSPEnabled
267 }
268 return value == nil || *value
269}
270
271// PonytailModeEnabled reports the default-on coding-guidance preference
272// without requiring a generated config entry.
273func (c Config) PonytailModeEnabled() bool {
274 return c.PonytailEnabled == nil || *c.PonytailEnabled
275}
276
277// WebSearchEnabledForCLI reports the default-on web-search preference
278// without requiring a generated config entry.
279func (c Config) WebSearchEnabledForCLI() bool {
280 return c.WebSearchEnabled == nil || *c.WebSearchEnabled
281}
282
283// LSPDiagnosticsOnWriteEnabled reports the default-on write diagnostics
284// preference without requiring a generated config entry.
285func (c Config) LSPDiagnosticsOnWriteEnabled(subagent bool) bool {
286 return c.LSPEnabledFor(subagent) && (c.LSPDiagnosticsOnWrite == nil || *c.LSPDiagnosticsOnWrite)
287}
288
289// LSPDiagnosticsOnEditEnabled reports the default-off edit diagnostics
290// preference without requiring a generated config entry.
291func (c Config) LSPDiagnosticsOnEditEnabled(subagent bool) bool {
292 return c.LSPEnabledFor(subagent) && c.LSPDiagnosticsOnEdit != nil && *c.LSPDiagnosticsOnEdit
293}
294
295// AuthPath returns the path to auth.json.
296func AuthPath() string { return filepath.Join(ZutHome(), "auth.json") }
297
298// KimiCLIFallbackDisabledPath returns a sentinel that disables falling
299// back to the official Kimi Code CLI token after `zut /logout kimi`.
300func KimiCLIFallbackDisabledPath() string {
301 return filepath.Join(ZutHome(), "kimi-cli-fallback-disabled")
302}
303
304// SessionsPath returns the directory holding session files.
305func SessionsPath() string { return filepath.Join(ZutHome(), "sessions") }
306
307// LogsPath returns the directory holding log files.
308func LogsPath() string { return filepath.Join(ZutHome(), "logs") }
309
310// LoadConfig reads the config file, returning defaults if missing.
311func LoadConfig() (Config, error) {
312 var c Config
313 b, err := os.ReadFile(ConfigPath())
314 if errors.Is(err, os.ErrNotExist) {
315 return c, nil
316 }
317 if err != nil {
318 return c, err
319 }
320 if err := json.Unmarshal(b, &c); err != nil {
321 return c, fmt.Errorf("parse config: %w", err)
322 }
323 if err := validateSubagentDurations(c.Subagents); err != nil {
324 return c, err
325 }
326 return c, nil
327}
328
329func validateSubagentDurations(cfg SubagentsConfig) error {
330 values := []struct {
331 name string
332 value string
333 }{
334 {"queue_timeout", cfg.QueueTimeout},
335 {"startup_timeout", cfg.StartupTimeout},
336 {"default_timeout", cfg.DefaultTimeout},
337 {"heartbeat_interval", cfg.HeartbeatInterval},
338 {"idle_timeout", cfg.IdleTimeout},
339 {"reconnect_timeout", cfg.ReconnectTimeout},
340 {"cancel_grace_period", cfg.CancelGracePeriod},
341 }
342 for _, item := range values {
343 value := strings.TrimSpace(item.value)
344 if value == "" {
345 continue
346 }
347 if _, err := time.ParseDuration(value); err != nil {
348 return fmt.Errorf("parse config: subagents.%s: %w", item.name, err)
349 }
350 }
351 return nil
352}
353
354// SaveConfig writes the config file, creating parent dirs.
355func SaveConfig(c Config) error {
356 if err := os.MkdirAll(ZutHome(), 0o755); err != nil {
357 return err
358 }
359 b, err := json.MarshalIndent(c, "", " ")
360 if err != nil {
361 return err
362 }
363 return os.WriteFile(ConfigPath(), b, 0o644)
364}
365
366// applyConfiguredHTTPProxy makes the persisted proxy available to Go's
367// standard HTTP transport and to child processes. Explicit environment
368// variables take precedence over config.json.
369func applyConfiguredHTTPProxy() {
370 cfg, err := LoadConfig()
371 if err != nil {
372 return
373 }
374 proxy := strings.TrimSpace(cfg.HTTPProxy)
375 if proxy == "" {
376 return
377 }
378 if os.Getenv("HTTP_PROXY") == "" && os.Getenv("http_proxy") == "" {
379 _ = os.Setenv("HTTP_PROXY", proxy)
380 }
381 if os.Getenv("HTTPS_PROXY") == "" && os.Getenv("https_proxy") == "" {
382 _ = os.Setenv("HTTPS_PROXY", proxy)
383 }
384}
385
386// AuthStoreFor returns the auth.Store backed by AuthPath().
387func AuthStoreFor() *auth.Store { return auth.NewStore(AuthPath()) }
388
389// ResolveLlamaCPPConfig resolves the router URL and optional API key. The
390// environment overrides the credential stored through /login.
391func ResolveLlamaCPPConfig() (baseURL, apiKey string, err error) {
392 return resolveLlamaCPPConfig(context.Background(), apiKeyCommandExecute)
393}
394
395func resolveLlamaCPPConfig(ctx context.Context, commandMode apiKeyCommandMode) (baseURL, apiKey string, err error) {
396 baseURL = strings.TrimSpace(os.Getenv("LLAMA_BASE_URL"))
397 apiKey = strings.TrimSpace(os.Getenv("LLAMA_API_KEY"))
398 if baseURL == "" {
399 creds, loadErr := AuthStoreFor().Load()
400 if loadErr != nil {
401 return "", "", loadErr
402 }
403 if stored, ok := creds.AdditionalAPIKeyCreds[providerpkg.LlamaCPPProviderID]; ok {
404 baseURL = stored.BaseURL
405 if apiKey == "" {
406 if stored.APIKeyCommand != nil && commandMode == apiKeyCommandSkip {
407 return "", "", nil
408 }
409 if key, found, commandErr := resolveStoredAPIKey(ctx, providerpkg.LlamaCPPProviderID, stored, commandMode); found || commandErr != nil {
410 if commandErr != nil {
411 return "", "", commandErr
412 }
413 apiKey = key
414 }
415 }
416 }
417 }
418 if baseURL == "" {
419 return "", apiKey, nil
420 }
421 baseURL, err = providerpkg.NormalizeLlamaCPPURL(baseURL)
422 return baseURL, apiKey, err
423}
424
425// ResolveCredential returns the credential (api key or oauth access
426// token), the method ("apikey"/"oauth"), and an error when no
427// credential is available.
428//
429// Lookup order:
430// 1. explicit (e.g. --api-key): treated as API key
431// 2. provider-specific env var: treated as API key
432// 3. auth.json: api key OR oauth, whichever is present
433func ResolveCredential(provider, explicit string) (cred, method string, err error) {
434 cred, method, _, err = ResolveCredentialFull(provider, explicit)
435 return cred, method, err
436}
437
438// ResolveCredentialContext is ResolveCredential with caller cancellation.
439func ResolveCredentialContext(ctx context.Context, provider, explicit string) (cred, method string, err error) {
440 cred, method, _, err = ResolveCredentialFullContext(ctx, provider, explicit)
441 return cred, method, err
442}
443
444// ResolveCredentialFull is like ResolveCredential but also returns a
445// provider-specific accountID when the credential is an OpenAI OAuth
446// token (the ChatGPT account id extracted from the stored id_token).
447// accountID is "" for API-key auth and for anthropic.
448func ResolveCredentialFull(provider, explicit string) (cred, method, accountID string, err error) {
449 return ResolveCredentialFullContext(context.Background(), provider, explicit)
450}
451
452// ResolveCredentialFullContext is ResolveCredentialFull with caller cancellation.
453func ResolveCredentialFullContext(ctx context.Context, provider, explicit string) (cred, method, accountID string, err error) {
454 return resolveCredentialFull(ctx, provider, explicit, apiKeyCommandExecute)
455}
456
457type apiKeyCommandMode uint8
458
459const (
460 apiKeyCommandExecute apiKeyCommandMode = iota
461 apiKeyCommandAvailable
462 apiKeyCommandSkip
463)
464
465func resolveCredentialFull(ctx context.Context, provider, explicit string, commandMode apiKeyCommandMode) (cred, method, accountID string, err error) {
466 if explicit != "" {
467 return explicit, "apikey", "", nil
468 }
469 switch provider {
470 case "anthropic":
471 // ANTHROPIC_OAUTH_TOKEN takes precedence over ANTHROPIC_API_KEY.
472 // Useful when both are set and the user wants subscription auth
473 // without editing auth.json.
474 if v := os.Getenv("ANTHROPIC_OAUTH_TOKEN"); v != "" {
475 return v, "oauth", "", nil
476 }
477 if v := os.Getenv("ANTHROPIC_API_KEY"); v != "" {
478 return v, "apikey", "", nil
479 }
480 case "openai":
481 if v := os.Getenv("OPENAI_API_KEY"); v != "" {
482 return v, "apikey", "", nil
483 }
484 case "openai-codex":
485 // ChatGPT/Codex subscription route. It intentionally ignores
486 // OPENAI_API_KEY so users can keep both OpenAI API and Codex
487 // subscription credentials configured and choose by provider.
488 case "openai-responses":
489 // Public OpenAI Responses API. Same env var as the chat-completions
490 // `openai` provider; users pick the wire format by provider id.
491 if v := os.Getenv("OPENAI_API_KEY"); v != "" {
492 return v, "apikey", "", nil
493 }
494 case "kimi":
495 if v := os.Getenv("KIMI_API_KEY"); v != "" {
496 return v, "apikey", "", nil
497 }
498 if v := os.Getenv("MOONSHOT_API_KEY"); v != "" {
499 return v, "apikey", "", nil
500 }
501 case "google":
502 // Both env names are widely-used in the Google ecosystem;
503 // GEMINI_API_KEY is the AI Studio default, GOOGLE_API_KEY
504 // is the older / generic name. Either works.
505 if v := os.Getenv("GEMINI_API_KEY"); v != "" {
506 return v, "apikey", "", nil
507 }
508 if v := os.Getenv("GOOGLE_API_KEY"); v != "" {
509 return v, "apikey", "", nil
510 }
511 case "deepseek":
512 if v := os.Getenv("DEEPSEEK_API_KEY"); v != "" {
513 return v, "apikey", "", nil
514 }
515 case "llama.cpp":
516 baseURL, apiKey, resolveErr := resolveLlamaCPPConfig(ctx, commandMode)
517 if resolveErr != nil {
518 return "", "", "", resolveErr
519 }
520 if baseURL != "" {
521 return firstNonEmpty(apiKey, "local"), "apikey", "", nil
522 }
523 case "moonshotai", "moonshotai-cn":
524 // Moonshot direct API (separate from kimi-coding, which is the
525 // Anthropic-Messages-fronted /coding endpoint with subscription OAuth).
526 if v := os.Getenv("MOONSHOT_API_KEY"); v != "" {
527 return v, "apikey", "", nil
528 }
529 case "groq":
530 if v := os.Getenv("GROQ_API_KEY"); v != "" {
531 return v, "apikey", "", nil
532 }
533 case "xai":
534 if v := os.Getenv("XAI_API_KEY"); v != "" {
535 return v, "apikey", "", nil
536 }
537 case "cerebras":
538 if v := os.Getenv("CEREBRAS_API_KEY"); v != "" {
539 return v, "apikey", "", nil
540 }
541 case "together":
542 if v := os.Getenv("TOGETHER_API_KEY"); v != "" {
543 return v, "apikey", "", nil
544 }
545 case "huggingface":
546 if v := os.Getenv("HF_TOKEN"); v != "" {
547 return v, "apikey", "", nil
548 }
549 case "openrouter":
550 if v := os.Getenv("OPENROUTER_API_KEY"); v != "" {
551 return v, "apikey", "", nil
552 }
553 case "mistral":
554 if v := os.Getenv("MISTRAL_API_KEY"); v != "" {
555 return v, "apikey", "", nil
556 }
557 case "zai":
558 if v := os.Getenv("ZAI_API_KEY"); v != "" {
559 return v, "apikey", "", nil
560 }
561 case "xiaomi", "xiaomi-token-plan-ams", "xiaomi-token-plan-cn", "xiaomi-token-plan-sgp":
562 envVar := "XIAOMI_API_KEY"
563 switch provider {
564 case "xiaomi-token-plan-ams":
565 envVar = "XIAOMI_TOKEN_PLAN_AMS_API_KEY"
566 case "xiaomi-token-plan-cn":
567 envVar = "XIAOMI_TOKEN_PLAN_CN_API_KEY"
568 case "xiaomi-token-plan-sgp":
569 envVar = "XIAOMI_TOKEN_PLAN_SGP_API_KEY"
570 }
571 if v := os.Getenv(envVar); v != "" {
572 return v, "apikey", "", nil
573 }
574 case "minimax":
575 if v := os.Getenv("MINIMAX_API_KEY"); v != "" {
576 return v, "apikey", "", nil
577 }
578 case "minimax-cn":
579 if v := os.Getenv("MINIMAX_CN_API_KEY"); v != "" {
580 return v, "apikey", "", nil
581 }
582 if v := os.Getenv("MINIMAX_API_KEY"); v != "" {
583 return v, "apikey", "", nil
584 }
585 case "fireworks":
586 if v := os.Getenv("FIREWORKS_API_KEY"); v != "" {
587 return v, "apikey", "", nil
588 }
589 case "vercel-ai-gateway":
590 if v := os.Getenv("AI_GATEWAY_API_KEY"); v != "" {
591 return v, "apikey", "", nil
592 }
593 case "opencode", "opencode-go":
594 if v := os.Getenv("OPENCODE_API_KEY"); v != "" {
595 return v, "apikey", "", nil
596 }
597 case "github-copilot":
598 if v := os.Getenv("COPILOT_GITHUB_TOKEN"); v != "" {
599 return v, "apikey", "", nil
600 }
601 if v := os.Getenv("GITHUB_COPILOT_TOKEN"); v != "" {
602 return v, "apikey", "", nil
603 }
604 case "cloudflare-workers-ai", "cloudflare-ai-gateway":
605 if v := os.Getenv("CLOUDFLARE_API_KEY"); v != "" {
606 return v, "apikey", "", nil
607 }
608 case "amazon-bedrock":
609 // Bedrock has many credential sources (AWS_PROFILE, IAM keys,
610 // container creds, IRSA, bearer token). We surface a sentinel so
611 // Resolve doesn't error on missing key; the real client (when
612 // implemented) will resolve credentials through aws-sdk-go-v2.
613 if os.Getenv("AWS_ACCESS_KEY_ID") != "" || os.Getenv("AWS_PROFILE") != "" ||
614 os.Getenv("AWS_BEARER_TOKEN_BEDROCK") != "" {
615 return "<aws>", "apikey", "", nil
616 }
617 case "google-vertex":
618 if v := os.Getenv("GOOGLE_CLOUD_API_KEY"); v != "" {
619 return v, "apikey", "", nil
620 }
621 // Check for Application Default Credentials (gcloud auth application-default login)
622 // or service account JSON, matching the actual NewVertex client behavior.
623 if os.Getenv("GOOGLE_APPLICATION_CREDENTIALS") != "" {
624 return "<adc>", "apikey", "", nil
625 }
626 // Check for the platform-specific default ADC path that gcloud writes to.
627 if adcPath, err := auth.GoogleApplicationDefaultCredentialsPath(); err == nil {
628 if _, err := os.Stat(adcPath); err == nil {
629 return "<adc>", "apikey", "", nil
630 }
631 }
632 case "azure-openai-responses":
633 if v := os.Getenv("AZURE_OPENAI_API_KEY"); v != "" {
634 return v, "apikey", "", nil
635 }
636 }
637 // Generic env var fallback for custom providers: normalize the
638 // provider id to a shell-friendly env var name (hyphens to
639 // underscores) and check {NAME}_API_KEY before auth.json.
640 if v := os.Getenv(normalizeCustomProviderEnvVar(provider) + "_API_KEY"); v != "" {
641 return v, "apikey", "", nil
642 }
643 c, err := AuthStoreFor().Load()
644 if err != nil {
645 return "", "", "", err
646 }
647 if pc, ok := storedProviderCreds(c, provider); ok {
648 if key, found, commandErr := resolveStoredAPIKey(ctx, provider, pc, commandMode); found || commandErr != nil {
649 if commandErr != nil {
650 return "", "", "", commandErr
651 }
652 return key, "apikey", "", nil
653 }
654 if provider == "xai" && pc.OAuth != nil && pc.OAuth.AccessToken != "" {
655 tok, _ := refreshIfExpiredContext(ctx, provider, pc.OAuth)
656 return tok.AccessToken, "oauth", "", nil
657 }
658 }
659 switch provider {
660 case "anthropic":
661 if c.Anthropic.OAuth != nil && c.Anthropic.OAuth.AccessToken != "" {
662 tok, _ := refreshIfExpiredContext(ctx, "anthropic", c.Anthropic.OAuth)
663 return tok.AccessToken, "oauth", "", nil
664 }
665 case "openai-codex":
666 if c.OpenAI.OAuth != nil && c.OpenAI.OAuth.AccessToken != "" {
667 tok, _ := refreshIfExpiredContext(ctx, "openai", c.OpenAI.OAuth)
668 return tok.AccessToken, "oauth", tok.AccountID, nil
669 }
670 case "kimi":
671 if c.Kimi.OAuth != nil && c.Kimi.OAuth.AccessToken != "" {
672 tok, _ := refreshIfExpiredContext(ctx, "kimi", c.Kimi.OAuth)
673 return tok.AccessToken, "oauth", "", nil
674 }
675 if kimiCLIFallbackDisabled() {
676 break
677 }
678 if tok := loadKimiCodeCLIToken(); tok != nil && tok.AccessToken != "" {
679 tok, _ = refreshIfExpiredContext(ctx, "kimi", tok)
680 return tok.AccessToken, "oauth", "", nil
681 }
682 case "github-copilot":
683 if c.GithubCopilot.OAuth != nil && c.GithubCopilot.OAuth.AccessToken != "" {
684 return c.GithubCopilot.OAuth.AccessToken, "oauth", "", nil
685 }
686 }
687 return "", "", "", fmt.Errorf("no credential for %s", provider)
688}
689
690// CredentialAvailable reports whether a provider has a configured credential
691// without executing an api_key_command.
692func CredentialAvailable(provider string) bool {
693 _, _, _, err := resolveCredentialFull(context.Background(), provider, "", apiKeyCommandAvailable)
694 return err == nil
695}
696
697func resolveCredentialForBackground(ctx context.Context, provider string) (cred, method string, err error) {
698 cred, method, _, err = resolveCredentialFull(ctx, provider, "", apiKeyCommandSkip)
699 return cred, method, err
700}
701
702func storedProviderCreds(c auth.Credentials, provider string) (auth.ProviderCreds, bool) {
703 if pc, ok := c.AdditionalAPIKeyCreds[provider]; ok {
704 return pc, true
705 }
706 switch provider {
707 case "anthropic":
708 return c.Anthropic, true
709 case "openai":
710 return c.OpenAI, true
711 case "kimi":
712 return c.Kimi, true
713 case "google":
714 return c.Google, true
715 case "deepseek":
716 return c.DeepSeek, true
717 case "github-copilot":
718 return c.GithubCopilot, true
719 default:
720 return auth.ProviderCreds{}, false
721 }
722}
723
724func resolveStoredAPIKey(ctx context.Context, provider string, creds auth.ProviderCreds, mode apiKeyCommandMode) (key string, found bool, err error) {
725 if creds.APIKey != "" {
726 return creds.APIKey, true, nil
727 }
728 if creds.APIKeyCommand == nil {
729 return "", false, nil
730 }
731 switch mode {
732 case apiKeyCommandAvailable:
733 return "<api-key-command>", true, nil
734 case apiKeyCommandSkip:
735 return "", false, nil
736 default:
737 key, err := auth.ResolveAPIKeyCommand(ctx, *creds.APIKeyCommand)
738 if err != nil {
739 return "", true, fmt.Errorf("resolve api key for %s: %w", provider, err)
740 }
741 return key, true, nil
742 }
743}
744
745func kimiCLIFallbackDisabled() bool {
746 _, err := os.Stat(KimiCLIFallbackDisabledPath())
747 return err == nil
748}
749
750func SetKimiCLIFallbackDisabled(disabled bool) error {
751 path := KimiCLIFallbackDisabledPath()
752 if !disabled {
753 if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
754 return err
755 }
756 return nil
757 }
758 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
759 return err
760 }
761 return os.WriteFile(path, []byte("disabled\n"), 0o600)
762}
763
764// normalizeCustomProviderEnvVar converts a provider id such as
765// "my-company" to "MY_COMPANY", matching the common convention for
766// shell environment variables.
767func normalizeCustomProviderEnvVar(provider string) string {
768 provider = strings.ToUpper(provider)
769 provider = strings.ReplaceAll(provider, "-", "_")
770 return provider
771}
772
773func loadKimiCodeCLIToken() *auth.OAuthToken {
774 home, err := os.UserHomeDir()
775 if err != nil {
776 return nil
777 }
778 b, err := os.ReadFile(filepath.Join(home, ".kimi", "credentials", "kimi-code.json"))
779 if err != nil {
780 return nil
781 }
782 var raw struct {
783 AccessToken string `json:"access_token"`
784 RefreshToken string `json:"refresh_token"`
785 TokenType string `json:"token_type"`
786 ExpiresAt float64 `json:"expires_at"`
787 Scope string `json:"scope"`
788 ExpiresIn float64 `json:"expires_in"`
789 }
790 if err := json.Unmarshal(b, &raw); err != nil || raw.AccessToken == "" {
791 return nil
792 }
793 sec := int64(raw.ExpiresAt)
794 nsec := int64((raw.ExpiresAt - float64(sec)) * 1e9)
795 return &auth.OAuthToken{
796 AccessToken: raw.AccessToken,
797 RefreshToken: raw.RefreshToken,
798 TokenType: raw.TokenType,
799 Scope: raw.Scope,
800 ClientID: auth.KimiOAuth.ClientID,
801 Expiry: time.Unix(sec, nsec),
802 }
803}
804
805// loadOAuthToken reads the current OAuth token from auth.json for the
806// given provider. Returns nil if no token is stored.
807func loadOAuthToken(providerName string) *auth.OAuthToken {
808 c, err := AuthStoreFor().Load()
809 if err != nil {
810 return nil
811 }
812 switch providerName {
813 case "anthropic":
814 if c.Anthropic.OAuth != nil {
815 return c.Anthropic.OAuth
816 }
817 case "openai":
818 if c.OpenAI.OAuth != nil {
819 return c.OpenAI.OAuth
820 }
821 case "kimi":
822 if c.Kimi.OAuth != nil {
823 return c.Kimi.OAuth
824 }
825 if kimiCLIFallbackDisabled() {
826 return nil
827 }
828 return loadKimiCodeCLIToken()
829 case "github-copilot":
830 if c.GithubCopilot.OAuth != nil {
831 return c.GithubCopilot.OAuth
832 }
833 }
834 if pc, ok := c.AdditionalAPIKeyCreds[providerName]; ok {
835 return pc.OAuth
836 }
837 return nil
838}
839
840// refreshIfExpired returns a usable OAuth token for the given provider,
841// refreshing it synchronously when it's past (or near) expiry. The
842// refreshed token is persisted to auth.json.
843//
844// Failures return the original token unchanged — the caller then makes
845// a request with the stale access_token, which will 401. That's still
846// better than crashing at credential-resolution time.
847func refreshIfExpired(providerName string, tok *auth.OAuthToken) (*auth.OAuthToken, error) {
848 return refreshIfExpiredContext(context.Background(), providerName, tok)
849}
850
851// refreshIfExpiredContext uses the caller's cancellation deadline while
852// refreshing an expired OAuth token.
853func refreshIfExpiredContext(parent context.Context, providerName string, tok *auth.OAuthToken) (*auth.OAuthToken, error) {
854 if tok == nil {
855 return &auth.OAuthToken{}, fmt.Errorf("nil token")
856 }
857 if !tok.Expired() {
858 return tok, nil
859 }
860 if tok.RefreshToken == "" {
861 return tok, fmt.Errorf("%s oauth token expired and no refresh_token available — run /login again", providerName)
862 }
863
864 if providerName == "xai" {
865 ctx, cancel := context.WithTimeout(parent, 30*time.Second)
866 defer cancel()
867 next, err := auth.RefreshXAIToken(ctx, tok.RefreshToken)
868 if err != nil {
869 return tok, fmt.Errorf("refresh %s: %w", providerName, err)
870 }
871 if next.RefreshToken == "" {
872 next.RefreshToken = tok.RefreshToken
873 }
874 if err := AuthStoreFor().SetOAuth(providerName, *next); err != nil {
875 return next, fmt.Errorf("persist refreshed token: %w", err)
876 }
877 return next, nil
878 }
879
880 var op auth.OAuthProvider
881 switch providerName {
882 case "anthropic":
883 op = auth.AnthropicOAuth
884 case "openai":
885 op = auth.OpenAIOAuth
886 case "kimi":
887 op = auth.KimiOAuth
888 default:
889 return tok, fmt.Errorf("unknown provider %q", providerName)
890 }
891
892 ctx, cancel := context.WithTimeout(parent, 30*time.Second)
893 defer cancel()
894 next, err := op.Refresh(ctx, tok.RefreshToken)
895 if err != nil {
896 return tok, fmt.Errorf("refresh %s: %w", providerName, err)
897 }
898 // Preserve the refresh token if the server omitted it (Anthropic often does).
899 if next.RefreshToken == "" {
900 next.RefreshToken = tok.RefreshToken
901 }
902 // Carry over account id (openai) / id_token across refreshes.
903 if next.AccountID == "" {
904 next.AccountID = tok.AccountID
905 }
906 if next.IDToken == "" {
907 next.IDToken = tok.IDToken
908 }
909 if err := AuthStoreFor().SetOAuth(providerName, *next); err != nil {
910 return next, fmt.Errorf("persist refreshed token: %w", err)
911 }
912 return next, nil
913}