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