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