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