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