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 "mistral":
470 if v := os.Getenv("MISTRAL_API_KEY"); v != "" {
471 return v, "apikey", "", nil
472 }
473 case "zai":
474 if v := os.Getenv("ZAI_API_KEY"); v != "" {
475 return v, "apikey", "", nil
476 }
477 case "xiaomi", "xiaomi-token-plan-ams", "xiaomi-token-plan-cn", "xiaomi-token-plan-sgp":
478 envVar := "XIAOMI_API_KEY"
479 switch provider {
480 case "xiaomi-token-plan-ams":
481 envVar = "XIAOMI_TOKEN_PLAN_AMS_API_KEY"
482 case "xiaomi-token-plan-cn":
483 envVar = "XIAOMI_TOKEN_PLAN_CN_API_KEY"
484 case "xiaomi-token-plan-sgp":
485 envVar = "XIAOMI_TOKEN_PLAN_SGP_API_KEY"
486 }
487 if v := os.Getenv(envVar); v != "" {
488 return v, "apikey", "", nil
489 }
490 case "minimax":
491 if v := os.Getenv("MINIMAX_API_KEY"); v != "" {
492 return v, "apikey", "", nil
493 }
494 case "minimax-cn":
495 if v := os.Getenv("MINIMAX_CN_API_KEY"); v != "" {
496 return v, "apikey", "", nil
497 }
498 if v := os.Getenv("MINIMAX_API_KEY"); v != "" {
499 return v, "apikey", "", nil
500 }
501 case "fireworks":
502 if v := os.Getenv("FIREWORKS_API_KEY"); v != "" {
503 return v, "apikey", "", nil
504 }
505 case "vercel-ai-gateway":
506 if v := os.Getenv("AI_GATEWAY_API_KEY"); v != "" {
507 return v, "apikey", "", nil
508 }
509 case "opencode", "opencode-go":
510 if v := os.Getenv("OPENCODE_API_KEY"); v != "" {
511 return v, "apikey", "", nil
512 }
513 case "github-copilot":
514 if v := os.Getenv("COPILOT_GITHUB_TOKEN"); v != "" {
515 return v, "apikey", "", nil
516 }
517 if v := os.Getenv("GITHUB_COPILOT_TOKEN"); v != "" {
518 return v, "apikey", "", nil
519 }
520 case "cloudflare-workers-ai", "cloudflare-ai-gateway":
521 if v := os.Getenv("CLOUDFLARE_API_KEY"); v != "" {
522 return v, "apikey", "", nil
523 }
524 case "amazon-bedrock":
525 // Bedrock has many credential sources (AWS_PROFILE, IAM keys,
526 // container creds, IRSA, bearer token). We surface a sentinel so
527 // Resolve doesn't error on missing key; the real client (when
528 // implemented) will resolve credentials through aws-sdk-go-v2.
529 if os.Getenv("AWS_ACCESS_KEY_ID") != "" || os.Getenv("AWS_PROFILE") != "" ||
530 os.Getenv("AWS_BEARER_TOKEN_BEDROCK") != "" {
531 return "<aws>", "apikey", "", nil
532 }
533 case "google-vertex":
534 if v := os.Getenv("GOOGLE_CLOUD_API_KEY"); v != "" {
535 return v, "apikey", "", nil
536 }
537 // Check for Application Default Credentials (gcloud auth application-default login)
538 // or service account JSON, matching the actual NewVertex client behavior.
539 if os.Getenv("GOOGLE_APPLICATION_CREDENTIALS") != "" {
540 return "<adc>", "apikey", "", nil
541 }
542 // Check for the platform-specific default ADC path that gcloud writes to.
543 if adcPath, err := auth.GoogleApplicationDefaultCredentialsPath(); err == nil {
544 if _, err := os.Stat(adcPath); err == nil {
545 return "<adc>", "apikey", "", nil
546 }
547 }
548 case "azure-openai-responses":
549 if v := os.Getenv("AZURE_OPENAI_API_KEY"); v != "" {
550 return v, "apikey", "", nil
551 }
552 }
553 // Generic env var fallback for custom providers: normalize the
554 // provider id to a shell-friendly env var name (hyphens to
555 // underscores) and check {NAME}_API_KEY before auth.json.
556 if v := os.Getenv(normalizeCustomProviderEnvVar(provider) + "_API_KEY"); v != "" {
557 return v, "apikey", "", nil
558 }
559 c, err := AuthStoreFor().Load()
560 if err != nil {
561 return "", "", "", err
562 }
563 if pc, ok := storedProviderCreds(c, provider); ok {
564 if key, found, commandErr := resolveStoredAPIKey(ctx, provider, pc, commandMode); found || commandErr != nil {
565 if commandErr != nil {
566 return "", "", "", commandErr
567 }
568 return key, "apikey", "", nil
569 }
570 if provider == "xai" && pc.OAuth != nil && pc.OAuth.AccessToken != "" {
571 tok, _ := refreshIfExpired(provider, pc.OAuth)
572 return tok.AccessToken, "oauth", "", nil
573 }
574 }
575 switch provider {
576 case "anthropic":
577 if c.Anthropic.OAuth != nil && c.Anthropic.OAuth.AccessToken != "" {
578 tok, _ := refreshIfExpired("anthropic", c.Anthropic.OAuth)
579 return tok.AccessToken, "oauth", "", nil
580 }
581 case "openai-codex":
582 if c.OpenAI.OAuth != nil && c.OpenAI.OAuth.AccessToken != "" {
583 tok, _ := refreshIfExpired("openai", c.OpenAI.OAuth)
584 return tok.AccessToken, "oauth", tok.AccountID, nil
585 }
586 case "kimi":
587 if c.Kimi.OAuth != nil && c.Kimi.OAuth.AccessToken != "" {
588 tok, _ := refreshIfExpired("kimi", c.Kimi.OAuth)
589 return tok.AccessToken, "oauth", "", nil
590 }
591 if kimiCLIFallbackDisabled() {
592 break
593 }
594 if tok := loadKimiCodeCLIToken(); tok != nil && tok.AccessToken != "" {
595 tok, _ = refreshIfExpired("kimi", tok)
596 return tok.AccessToken, "oauth", "", nil
597 }
598 case "github-copilot":
599 if c.GithubCopilot.OAuth != nil && c.GithubCopilot.OAuth.AccessToken != "" {
600 return c.GithubCopilot.OAuth.AccessToken, "oauth", "", nil
601 }
602 }
603 return "", "", "", fmt.Errorf("no credential for %s", provider)
604}
605
606// CredentialAvailable reports whether a provider has a configured credential
607// without executing an api_key_command.
608func CredentialAvailable(provider string) bool {
609 _, _, _, err := resolveCredentialFull(context.Background(), provider, "", apiKeyCommandAvailable)
610 return err == nil
611}
612
613func resolveCredentialForBackground(ctx context.Context, provider string) (cred, method string, err error) {
614 cred, method, _, err = resolveCredentialFull(ctx, provider, "", apiKeyCommandSkip)
615 return cred, method, err
616}
617
618func storedProviderCreds(c auth.Credentials, provider string) (auth.ProviderCreds, bool) {
619 if pc, ok := c.AdditionalAPIKeyCreds[provider]; ok {
620 return pc, true
621 }
622 switch provider {
623 case "anthropic":
624 return c.Anthropic, true
625 case "openai":
626 return c.OpenAI, true
627 case "kimi":
628 return c.Kimi, true
629 case "google":
630 return c.Google, true
631 case "deepseek":
632 return c.DeepSeek, true
633 case "github-copilot":
634 return c.GithubCopilot, true
635 default:
636 return auth.ProviderCreds{}, false
637 }
638}
639
640func resolveStoredAPIKey(ctx context.Context, provider string, creds auth.ProviderCreds, mode apiKeyCommandMode) (key string, found bool, err error) {
641 if creds.APIKey != "" {
642 return creds.APIKey, true, nil
643 }
644 if creds.APIKeyCommand == nil {
645 return "", false, nil
646 }
647 switch mode {
648 case apiKeyCommandAvailable:
649 return "<api-key-command>", true, nil
650 case apiKeyCommandSkip:
651 return "", false, nil
652 default:
653 key, err := auth.ResolveAPIKeyCommand(ctx, *creds.APIKeyCommand)
654 if err != nil {
655 return "", true, fmt.Errorf("resolve api key for %s: %w", provider, err)
656 }
657 return key, true, nil
658 }
659}
660
661func kimiCLIFallbackDisabled() bool {
662 _, err := os.Stat(KimiCLIFallbackDisabledPath())
663 return err == nil
664}
665
666func SetKimiCLIFallbackDisabled(disabled bool) error {
667 path := KimiCLIFallbackDisabledPath()
668 if !disabled {
669 if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
670 return err
671 }
672 return nil
673 }
674 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
675 return err
676 }
677 return os.WriteFile(path, []byte("disabled\n"), 0o600)
678}
679
680// normalizeCustomProviderEnvVar converts a provider id such as
681// "my-company" to "MY_COMPANY", matching the common convention for
682// shell environment variables.
683func normalizeCustomProviderEnvVar(provider string) string {
684 provider = strings.ToUpper(provider)
685 provider = strings.ReplaceAll(provider, "-", "_")
686 return provider
687}
688
689func loadKimiCodeCLIToken() *auth.OAuthToken {
690 home, err := os.UserHomeDir()
691 if err != nil {
692 return nil
693 }
694 b, err := os.ReadFile(filepath.Join(home, ".kimi", "credentials", "kimi-code.json"))
695 if err != nil {
696 return nil
697 }
698 var raw struct {
699 AccessToken string `json:"access_token"`
700 RefreshToken string `json:"refresh_token"`
701 TokenType string `json:"token_type"`
702 ExpiresAt float64 `json:"expires_at"`
703 Scope string `json:"scope"`
704 ExpiresIn float64 `json:"expires_in"`
705 }
706 if err := json.Unmarshal(b, &raw); err != nil || raw.AccessToken == "" {
707 return nil
708 }
709 sec := int64(raw.ExpiresAt)
710 nsec := int64((raw.ExpiresAt - float64(sec)) * 1e9)
711 return &auth.OAuthToken{
712 AccessToken: raw.AccessToken,
713 RefreshToken: raw.RefreshToken,
714 TokenType: raw.TokenType,
715 Scope: raw.Scope,
716 ClientID: auth.KimiOAuth.ClientID,
717 Expiry: time.Unix(sec, nsec),
718 }
719}
720
721// loadOAuthToken reads the current OAuth token from auth.json for the
722// given provider. Returns nil if no token is stored.
723func loadOAuthToken(providerName string) *auth.OAuthToken {
724 c, err := AuthStoreFor().Load()
725 if err != nil {
726 return nil
727 }
728 switch providerName {
729 case "anthropic":
730 if c.Anthropic.OAuth != nil {
731 return c.Anthropic.OAuth
732 }
733 case "openai":
734 if c.OpenAI.OAuth != nil {
735 return c.OpenAI.OAuth
736 }
737 case "kimi":
738 if c.Kimi.OAuth != nil {
739 return c.Kimi.OAuth
740 }
741 if kimiCLIFallbackDisabled() {
742 return nil
743 }
744 return loadKimiCodeCLIToken()
745 case "github-copilot":
746 if c.GithubCopilot.OAuth != nil {
747 return c.GithubCopilot.OAuth
748 }
749 }
750 if pc, ok := c.AdditionalAPIKeyCreds[providerName]; ok {
751 return pc.OAuth
752 }
753 return nil
754}
755
756// refreshIfExpired returns a usable OAuth token for the given provider,
757// refreshing it synchronously when it's past (or near) expiry. The
758// refreshed token is persisted to auth.json.
759//
760// Failures return the original token unchanged — the caller then makes
761// a request with the stale access_token, which will 401. That's still
762// better than crashing at credential-resolution time.
763func refreshIfExpired(providerName string, tok *auth.OAuthToken) (*auth.OAuthToken, error) {
764 if tok == nil {
765 return &auth.OAuthToken{}, fmt.Errorf("nil token")
766 }
767 if !tok.Expired() {
768 return tok, nil
769 }
770 if tok.RefreshToken == "" {
771 return tok, fmt.Errorf("%s oauth token expired and no refresh_token available — run /login again", providerName)
772 }
773
774 if providerName == "xai" {
775 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
776 defer cancel()
777 next, err := auth.RefreshXAIToken(ctx, tok.RefreshToken)
778 if err != nil {
779 return tok, fmt.Errorf("refresh %s: %w", providerName, err)
780 }
781 if next.RefreshToken == "" {
782 next.RefreshToken = tok.RefreshToken
783 }
784 if err := AuthStoreFor().SetOAuth(providerName, *next); err != nil {
785 return next, fmt.Errorf("persist refreshed token: %w", err)
786 }
787 return next, nil
788 }
789
790 var op auth.OAuthProvider
791 switch providerName {
792 case "anthropic":
793 op = auth.AnthropicOAuth
794 case "openai":
795 op = auth.OpenAIOAuth
796 case "kimi":
797 op = auth.KimiOAuth
798 default:
799 return tok, fmt.Errorf("unknown provider %q", providerName)
800 }
801
802 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
803 defer cancel()
804 next, err := op.Refresh(ctx, tok.RefreshToken)
805 if err != nil {
806 return tok, fmt.Errorf("refresh %s: %w", providerName, err)
807 }
808 // Preserve the refresh token if the server omitted it (Anthropic often does).
809 if next.RefreshToken == "" {
810 next.RefreshToken = tok.RefreshToken
811 }
812 // Carry over account id (openai) / id_token across refreshes.
813 if next.AccountID == "" {
814 next.AccountID = tok.AccountID
815 }
816 if next.IDToken == "" {
817 next.IDToken = tok.IDToken
818 }
819 if err := AuthStoreFor().SetOAuth(providerName, *next); err != nil {
820 return next, fmt.Errorf("persist refreshed token: %w", err)
821 }
822 return next, nil
823}