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