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