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