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