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