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