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