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