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