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