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 "github.com/patriceckhart/zot/packages/provider/auth"
16)
17
18// QuickModelShortcut is one configured keyboard shortcut slot.
19type QuickModelShortcut struct {
20 Provider string `json:"provider"`
21 Model string `json:"model"`
22}
23
24// Config is the persisted user configuration.
25type Config struct {
26 Provider string `json:"provider"`
27 Model string `json:"model"`
28 Reasoning string `json:"reasoning"`
29 Temperature *float32 `json:"temperature,omitempty"`
30 Theme string `json:"theme"`
31
32 // QuickModelShortcuts maps slots 1-9 to provider/model pairs used by
33 // Ctrl+1..9. Cmd+1..9 may also work on terminals that forward Super.
34 QuickModelShortcuts []QuickModelShortcut `json:"quick_model_shortcuts,omitempty"`
35
36 // InlineImagesEnabled controls whether zot draws screenshots inline
37 // when the terminal supports an image protocol. nil/missing means
38 // auto (enabled when supported); false disables; true forces the
39 // detected protocol when available.
40 InlineImagesEnabled *bool `json:"inline_images_enabled,omitempty"`
41
42 // AutoSwarmEnabled lets the main agent spawn background sub-agents
43 // for parallel sub-tasks via a built-in swarm_spawn tool. Off by
44 // default; nil/missing means disabled. Toggle from /settings.
45 AutoSwarmEnabled *bool `json:"auto_swarm_enabled,omitempty"`
46
47 // RecursiveFileSuggest controls the @-mention file picker. When true
48 // the picker fuzzy-searches the whole project tree below the working
49 // directory; nil/missing/false keeps the default directory-by-
50 // directory browse. Toggle from /settings.
51 RecursiveFileSuggest *bool `json:"recursive_file_suggest,omitempty"`
52
53 // RespectGitignore controls whether the @-mention file picker hides
54 // files and directories matched by the project's root .gitignore (in
55 // both flat and recursive modes). nil/missing means the default,
56 // which is on; false shows ignored entries. Toggle from /settings.
57 RespectGitignore *bool `json:"respect_gitignore,omitempty"`
58
59 // Insecure skips TLS verification for custom inference endpoints.
60 Insecure bool `json:"insecure,omitempty"`
61
62 // LastChangelogShown is the version whose release-notes
63 // dialog the user has already seen. When the running binary's
64 // version differs, the next interactive run shows the
65 // changelog (fetched from the GitHub release page) once and
66 // updates this field. Empty means "never shown".
67 LastChangelogShown string `json:"last_changelog_shown,omitempty"`
68}
69
70// ZotHome returns $ZOT_HOME or the OS-default data dir.
71//
72// All zot state (config.json, auth.json, sessions/, logs/) lives under
73// this directory.
74func ZotHome() string {
75 if v := os.Getenv("ZOT_HOME"); v != "" {
76 return v
77 }
78 switch runtime.GOOS {
79 case "darwin":
80 if home, err := os.UserHomeDir(); err == nil {
81 return filepath.Join(home, "Library", "Application Support", "zot")
82 }
83 case "windows":
84 if v := os.Getenv("LOCALAPPDATA"); v != "" {
85 return filepath.Join(v, "zot")
86 }
87 }
88 if v := os.Getenv("XDG_STATE_HOME"); v != "" {
89 return filepath.Join(v, "zot")
90 }
91 if home, err := os.UserHomeDir(); err == nil {
92 return filepath.Join(home, ".local", "state", "zot")
93 }
94 return ".zot"
95}
96
97// ConfigPath returns the path to config.json.
98func ConfigPath() string { return filepath.Join(ZotHome(), "config.json") }
99
100// AuthPath returns the path to auth.json.
101func AuthPath() string { return filepath.Join(ZotHome(), "auth.json") }
102
103// KimiCLIFallbackDisabledPath returns a sentinel that disables falling
104// back to the official Kimi Code CLI token after `zot /logout kimi`.
105func KimiCLIFallbackDisabledPath() string {
106 return filepath.Join(ZotHome(), "kimi-cli-fallback-disabled")
107}
108
109// SessionsPath returns the directory holding session files.
110func SessionsPath() string { return filepath.Join(ZotHome(), "sessions") }
111
112// LogsPath returns the directory holding log files.
113func LogsPath() string { return filepath.Join(ZotHome(), "logs") }
114
115// LoadConfig reads the config file, returning defaults if missing.
116func LoadConfig() (Config, error) {
117 var c Config
118 b, err := os.ReadFile(ConfigPath())
119 if errors.Is(err, os.ErrNotExist) {
120 return c, nil
121 }
122 if err != nil {
123 return c, err
124 }
125 if err := json.Unmarshal(b, &c); err != nil {
126 return c, fmt.Errorf("parse config: %w", err)
127 }
128 return c, nil
129}
130
131// SaveConfig writes the config file, creating parent dirs.
132func SaveConfig(c Config) error {
133 if err := os.MkdirAll(ZotHome(), 0o755); err != nil {
134 return err
135 }
136 b, err := json.MarshalIndent(c, "", " ")
137 if err != nil {
138 return err
139 }
140 return os.WriteFile(ConfigPath(), b, 0o644)
141}
142
143// AuthStoreFor returns the auth.Store backed by AuthPath().
144func AuthStoreFor() *auth.Store { return auth.NewStore(AuthPath()) }
145
146// ResolveCredential returns the credential (api key or oauth access
147// token), the method ("apikey"/"oauth"), and an error when no
148// credential is available.
149//
150// Lookup order:
151// 1. explicit (e.g. --api-key): treated as API key
152// 2. provider-specific env var: treated as API key
153// 3. auth.json: api key OR oauth, whichever is present
154func ResolveCredential(provider, explicit string) (cred, method string, err error) {
155 cred, method, _, err = ResolveCredentialFull(provider, explicit)
156 return cred, method, err
157}
158
159// ResolveCredentialFull is like ResolveCredential but also returns a
160// provider-specific accountID when the credential is an OpenAI OAuth
161// token (the ChatGPT account id extracted from the stored id_token).
162// accountID is "" for API-key auth and for anthropic.
163func ResolveCredentialFull(provider, explicit string) (cred, method, accountID string, err error) {
164 if explicit != "" {
165 return explicit, "apikey", "", nil
166 }
167 switch provider {
168 case "anthropic":
169 // ANTHROPIC_OAUTH_TOKEN takes precedence over ANTHROPIC_API_KEY.
170 // Useful when both are set and the user wants subscription auth
171 // without editing auth.json.
172 if v := os.Getenv("ANTHROPIC_OAUTH_TOKEN"); v != "" {
173 return v, "oauth", "", nil
174 }
175 if v := os.Getenv("ANTHROPIC_API_KEY"); v != "" {
176 return v, "apikey", "", nil
177 }
178 case "openai":
179 if v := os.Getenv("OPENAI_API_KEY"); v != "" {
180 return v, "apikey", "", nil
181 }
182 case "openai-codex":
183 // ChatGPT/Codex subscription route. It intentionally ignores
184 // OPENAI_API_KEY so users can keep both OpenAI API and Codex
185 // subscription credentials configured and choose by provider.
186 case "openai-responses":
187 // Public OpenAI Responses API. Same env var as the chat-completions
188 // `openai` provider; users pick the wire format by provider id.
189 if v := os.Getenv("OPENAI_API_KEY"); v != "" {
190 return v, "apikey", "", nil
191 }
192 case "kimi":
193 if v := os.Getenv("KIMI_API_KEY"); v != "" {
194 return v, "apikey", "", nil
195 }
196 if v := os.Getenv("MOONSHOT_API_KEY"); v != "" {
197 return v, "apikey", "", nil
198 }
199 case "google":
200 // Both env names are widely-used in the Google ecosystem;
201 // GEMINI_API_KEY is the AI Studio default, GOOGLE_API_KEY
202 // is the older / generic name. Either works.
203 if v := os.Getenv("GEMINI_API_KEY"); v != "" {
204 return v, "apikey", "", nil
205 }
206 if v := os.Getenv("GOOGLE_API_KEY"); v != "" {
207 return v, "apikey", "", nil
208 }
209 case "deepseek":
210 if v := os.Getenv("DEEPSEEK_API_KEY"); v != "" {
211 return v, "apikey", "", nil
212 }
213 case "moonshotai", "moonshotai-cn":
214 // Moonshot direct API (separate from kimi-coding, which is the
215 // Anthropic-Messages-fronted /coding endpoint with subscription OAuth).
216 if v := os.Getenv("MOONSHOT_API_KEY"); v != "" {
217 return v, "apikey", "", nil
218 }
219 case "groq":
220 if v := os.Getenv("GROQ_API_KEY"); v != "" {
221 return v, "apikey", "", nil
222 }
223 case "xai":
224 if v := os.Getenv("XAI_API_KEY"); v != "" {
225 return v, "apikey", "", nil
226 }
227 case "cerebras":
228 if v := os.Getenv("CEREBRAS_API_KEY"); v != "" {
229 return v, "apikey", "", nil
230 }
231 case "together":
232 if v := os.Getenv("TOGETHER_API_KEY"); v != "" {
233 return v, "apikey", "", nil
234 }
235 case "huggingface":
236 if v := os.Getenv("HF_TOKEN"); v != "" {
237 return v, "apikey", "", nil
238 }
239 case "openrouter":
240 if v := os.Getenv("OPENROUTER_API_KEY"); v != "" {
241 return v, "apikey", "", nil
242 }
243 case "mistral":
244 if v := os.Getenv("MISTRAL_API_KEY"); v != "" {
245 return v, "apikey", "", nil
246 }
247 case "zai":
248 if v := os.Getenv("ZAI_API_KEY"); v != "" {
249 return v, "apikey", "", nil
250 }
251 case "xiaomi", "xiaomi-token-plan-ams", "xiaomi-token-plan-cn", "xiaomi-token-plan-sgp":
252 envVar := "XIAOMI_API_KEY"
253 switch provider {
254 case "xiaomi-token-plan-ams":
255 envVar = "XIAOMI_TOKEN_PLAN_AMS_API_KEY"
256 case "xiaomi-token-plan-cn":
257 envVar = "XIAOMI_TOKEN_PLAN_CN_API_KEY"
258 case "xiaomi-token-plan-sgp":
259 envVar = "XIAOMI_TOKEN_PLAN_SGP_API_KEY"
260 }
261 if v := os.Getenv(envVar); v != "" {
262 return v, "apikey", "", nil
263 }
264 case "minimax":
265 if v := os.Getenv("MINIMAX_API_KEY"); v != "" {
266 return v, "apikey", "", nil
267 }
268 case "minimax-cn":
269 if v := os.Getenv("MINIMAX_CN_API_KEY"); v != "" {
270 return v, "apikey", "", nil
271 }
272 if v := os.Getenv("MINIMAX_API_KEY"); v != "" {
273 return v, "apikey", "", nil
274 }
275 case "fireworks":
276 if v := os.Getenv("FIREWORKS_API_KEY"); v != "" {
277 return v, "apikey", "", nil
278 }
279 case "vercel-ai-gateway":
280 if v := os.Getenv("AI_GATEWAY_API_KEY"); v != "" {
281 return v, "apikey", "", nil
282 }
283 case "opencode", "opencode-go":
284 if v := os.Getenv("OPENCODE_API_KEY"); v != "" {
285 return v, "apikey", "", nil
286 }
287 case "github-copilot":
288 if v := os.Getenv("COPILOT_GITHUB_TOKEN"); v != "" {
289 return v, "apikey", "", nil
290 }
291 if v := os.Getenv("GITHUB_COPILOT_TOKEN"); v != "" {
292 return v, "apikey", "", nil
293 }
294 case "cloudflare-workers-ai", "cloudflare-ai-gateway":
295 if v := os.Getenv("CLOUDFLARE_API_KEY"); v != "" {
296 return v, "apikey", "", nil
297 }
298 case "amazon-bedrock":
299 // Bedrock has many credential sources (AWS_PROFILE, IAM keys,
300 // container creds, IRSA, bearer token). We surface a sentinel so
301 // Resolve doesn't error on missing key; the real client (when
302 // implemented) will resolve credentials through aws-sdk-go-v2.
303 if os.Getenv("AWS_ACCESS_KEY_ID") != "" || os.Getenv("AWS_PROFILE") != "" ||
304 os.Getenv("AWS_BEARER_TOKEN_BEDROCK") != "" {
305 return "<aws>", "apikey", "", nil
306 }
307 case "google-vertex":
308 if v := os.Getenv("GOOGLE_CLOUD_API_KEY"); v != "" {
309 return v, "apikey", "", nil
310 }
311 case "azure-openai-responses":
312 if v := os.Getenv("AZURE_OPENAI_API_KEY"); v != "" {
313 return v, "apikey", "", nil
314 }
315 }
316 // Generic env var fallback for custom providers: normalize the
317 // provider id to a shell-friendly env var name (hyphens to
318 // underscores) and check {NAME}_API_KEY before auth.json.
319 if v := os.Getenv(normalizeCustomProviderEnvVar(provider) + "_API_KEY"); v != "" {
320 return v, "apikey", "", nil
321 }
322 c, err := AuthStoreFor().Load()
323 if err != nil {
324 return "", "", "", err
325 }
326 if pc, ok := c.AdditionalAPIKeyCreds[provider]; ok && pc.APIKey != "" {
327 return pc.APIKey, "apikey", "", nil
328 }
329 switch provider {
330 case "anthropic":
331 if c.Anthropic.APIKey != "" {
332 return c.Anthropic.APIKey, "apikey", "", nil
333 }
334 if c.Anthropic.OAuth != nil && c.Anthropic.OAuth.AccessToken != "" {
335 tok, _ := refreshIfExpired("anthropic", c.Anthropic.OAuth)
336 return tok.AccessToken, "oauth", "", nil
337 }
338 case "openai":
339 if c.OpenAI.APIKey != "" {
340 return c.OpenAI.APIKey, "apikey", "", nil
341 }
342 case "openai-codex":
343 if c.OpenAI.OAuth != nil && c.OpenAI.OAuth.AccessToken != "" {
344 tok, _ := refreshIfExpired("openai", c.OpenAI.OAuth)
345 return tok.AccessToken, "oauth", tok.AccountID, nil
346 }
347 case "kimi":
348 if c.Kimi.APIKey != "" {
349 return c.Kimi.APIKey, "apikey", "", nil
350 }
351 if c.Kimi.OAuth != nil && c.Kimi.OAuth.AccessToken != "" {
352 tok, _ := refreshIfExpired("kimi", c.Kimi.OAuth)
353 return tok.AccessToken, "oauth", "", nil
354 }
355 if kimiCLIFallbackDisabled() {
356 break
357 }
358 if tok := loadKimiCodeCLIToken(); tok != nil && tok.AccessToken != "" {
359 tok, _ = refreshIfExpired("kimi", tok)
360 return tok.AccessToken, "oauth", "", nil
361 }
362 case "deepseek":
363 if c.DeepSeek.APIKey != "" {
364 return c.DeepSeek.APIKey, "apikey", "", nil
365 }
366 case "google":
367 // Google is API-key only — no OAuth path. We still load
368 // auth.json so /login api-key flows work without exporting
369 // an env var.
370 if c.Google.APIKey != "" {
371 return c.Google.APIKey, "apikey", "", nil
372 }
373 case "github-copilot":
374 if c.GithubCopilot.APIKey != "" {
375 return c.GithubCopilot.APIKey, "apikey", "", nil
376 }
377 if c.GithubCopilot.OAuth != nil && c.GithubCopilot.OAuth.AccessToken != "" {
378 return c.GithubCopilot.OAuth.AccessToken, "oauth", "", nil
379 }
380 }
381 return "", "", "", fmt.Errorf("no credential for %s", provider)
382}
383
384func kimiCLIFallbackDisabled() bool {
385 _, err := os.Stat(KimiCLIFallbackDisabledPath())
386 return err == nil
387}
388
389func SetKimiCLIFallbackDisabled(disabled bool) error {
390 path := KimiCLIFallbackDisabledPath()
391 if !disabled {
392 if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
393 return err
394 }
395 return nil
396 }
397 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
398 return err
399 }
400 return os.WriteFile(path, []byte("disabled\n"), 0o600)
401}
402
403// normalizeCustomProviderEnvVar converts a provider id such as
404// "my-company" to "MY_COMPANY", matching the common convention for
405// shell environment variables.
406func normalizeCustomProviderEnvVar(provider string) string {
407 provider = strings.ToUpper(provider)
408 provider = strings.ReplaceAll(provider, "-", "_")
409 return provider
410}
411
412func loadKimiCodeCLIToken() *auth.OAuthToken {
413 home, err := os.UserHomeDir()
414 if err != nil {
415 return nil
416 }
417 b, err := os.ReadFile(filepath.Join(home, ".kimi", "credentials", "kimi-code.json"))
418 if err != nil {
419 return nil
420 }
421 var raw struct {
422 AccessToken string `json:"access_token"`
423 RefreshToken string `json:"refresh_token"`
424 TokenType string `json:"token_type"`
425 ExpiresAt float64 `json:"expires_at"`
426 Scope string `json:"scope"`
427 ExpiresIn float64 `json:"expires_in"`
428 }
429 if err := json.Unmarshal(b, &raw); err != nil || raw.AccessToken == "" {
430 return nil
431 }
432 sec := int64(raw.ExpiresAt)
433 nsec := int64((raw.ExpiresAt - float64(sec)) * 1e9)
434 return &auth.OAuthToken{
435 AccessToken: raw.AccessToken,
436 RefreshToken: raw.RefreshToken,
437 TokenType: raw.TokenType,
438 Scope: raw.Scope,
439 ClientID: auth.KimiOAuth.ClientID,
440 Expiry: time.Unix(sec, nsec),
441 }
442}
443
444// loadOAuthToken reads the current OAuth token from auth.json for the
445// given provider. Returns nil if no token is stored.
446func loadOAuthToken(providerName string) *auth.OAuthToken {
447 c, err := AuthStoreFor().Load()
448 if err != nil {
449 return nil
450 }
451 switch providerName {
452 case "anthropic":
453 if c.Anthropic.OAuth != nil {
454 return c.Anthropic.OAuth
455 }
456 case "openai":
457 if c.OpenAI.OAuth != nil {
458 return c.OpenAI.OAuth
459 }
460 case "kimi":
461 if c.Kimi.OAuth != nil {
462 return c.Kimi.OAuth
463 }
464 if kimiCLIFallbackDisabled() {
465 return nil
466 }
467 return loadKimiCodeCLIToken()
468 case "github-copilot":
469 if c.GithubCopilot.OAuth != nil {
470 return c.GithubCopilot.OAuth
471 }
472 }
473 return nil
474}
475
476// refreshIfExpired returns a usable OAuth token for the given provider,
477// refreshing it synchronously when it's past (or near) expiry. The
478// refreshed token is persisted to auth.json.
479//
480// Failures return the original token unchanged — the caller then makes
481// a request with the stale access_token, which will 401. That's still
482// better than crashing at credential-resolution time.
483func refreshIfExpired(providerName string, tok *auth.OAuthToken) (*auth.OAuthToken, error) {
484 if tok == nil {
485 return &auth.OAuthToken{}, fmt.Errorf("nil token")
486 }
487 if !tok.Expired() {
488 return tok, nil
489 }
490 if tok.RefreshToken == "" {
491 return tok, fmt.Errorf("%s oauth token expired and no refresh_token available — run /login again", providerName)
492 }
493
494 var op auth.OAuthProvider
495 switch providerName {
496 case "anthropic":
497 op = auth.AnthropicOAuth
498 case "openai":
499 op = auth.OpenAIOAuth
500 case "kimi":
501 op = auth.KimiOAuth
502 default:
503 return tok, fmt.Errorf("unknown provider %q", providerName)
504 }
505
506 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
507 defer cancel()
508 next, err := op.Refresh(ctx, tok.RefreshToken)
509 if err != nil {
510 return tok, fmt.Errorf("refresh %s: %w", providerName, err)
511 }
512 // Preserve the refresh token if the server omitted it (Anthropic often does).
513 if next.RefreshToken == "" {
514 next.RefreshToken = tok.RefreshToken
515 }
516 // Carry over account id (openai) / id_token across refreshes.
517 if next.AccountID == "" {
518 next.AccountID = tok.AccountID
519 }
520 if next.IDToken == "" {
521 next.IDToken = tok.IDToken
522 }
523 if err := AuthStoreFor().SetOAuth(providerName, *next); err != nil {
524 return next, fmt.Errorf("persist refreshed token: %w", err)
525 }
526 return next, nil
527}