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