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