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