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