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