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/internal/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 // LastChangelogShown is the version whose release-notes
31 // dialog the user has already seen. When the running binary's
32 // version differs, the next interactive run shows the
33 // changelog (fetched from the GitHub release page) once and
34 // updates this field. Empty means "never shown".
35 LastChangelogShown string `json:"last_changelog_shown,omitempty"`
36}
37
38// ZotHome returns $ZOT_HOME or the OS-default data dir.
39//
40// All zot state (config.json, auth.json, sessions/, logs/) lives under
41// this directory.
42func ZotHome() string {
43 if v := os.Getenv("ZOT_HOME"); v != "" {
44 return v
45 }
46 switch runtime.GOOS {
47 case "darwin":
48 if home, err := os.UserHomeDir(); err == nil {
49 return filepath.Join(home, "Library", "Application Support", "zot")
50 }
51 case "windows":
52 if v := os.Getenv("LOCALAPPDATA"); v != "" {
53 return filepath.Join(v, "zot")
54 }
55 }
56 if v := os.Getenv("XDG_STATE_HOME"); v != "" {
57 return filepath.Join(v, "zot")
58 }
59 if home, err := os.UserHomeDir(); err == nil {
60 return filepath.Join(home, ".local", "state", "zot")
61 }
62 return ".zot"
63}
64
65// ConfigPath returns the path to config.json.
66func ConfigPath() string { return filepath.Join(ZotHome(), "config.json") }
67
68// AuthPath returns the path to auth.json.
69func AuthPath() string { return filepath.Join(ZotHome(), "auth.json") }
70
71// KimiCLIFallbackDisabledPath returns a sentinel that disables falling
72// back to the official Kimi Code CLI token after `zot /logout kimi`.
73func KimiCLIFallbackDisabledPath() string {
74 return filepath.Join(ZotHome(), "kimi-cli-fallback-disabled")
75}
76
77// SessionsPath returns the directory holding session files.
78func SessionsPath() string { return filepath.Join(ZotHome(), "sessions") }
79
80// LogsPath returns the directory holding log files.
81func LogsPath() string { return filepath.Join(ZotHome(), "logs") }
82
83// LoadConfig reads the config file, returning defaults if missing.
84func LoadConfig() (Config, error) {
85 var c Config
86 b, err := os.ReadFile(ConfigPath())
87 if errors.Is(err, os.ErrNotExist) {
88 return c, nil
89 }
90 if err != nil {
91 return c, err
92 }
93 if err := json.Unmarshal(b, &c); err != nil {
94 return c, fmt.Errorf("parse config: %w", err)
95 }
96 return c, nil
97}
98
99// SaveConfig writes the config file, creating parent dirs.
100func SaveConfig(c Config) error {
101 if err := os.MkdirAll(ZotHome(), 0o755); err != nil {
102 return err
103 }
104 b, err := json.MarshalIndent(c, "", " ")
105 if err != nil {
106 return err
107 }
108 return os.WriteFile(ConfigPath(), b, 0o644)
109}
110
111// AuthStoreFor returns the auth.Store backed by AuthPath().
112func AuthStoreFor() *auth.Store { return auth.NewStore(AuthPath()) }
113
114// ResolveCredential returns the credential (api key or oauth access
115// token), the method ("apikey"/"oauth"), and an error when no
116// credential is available.
117//
118// Lookup order:
119// 1. explicit (e.g. --api-key): treated as API key
120// 2. provider-specific env var: treated as API key
121// 3. auth.json: api key OR oauth, whichever is present
122func ResolveCredential(provider, explicit string) (cred, method string, err error) {
123 cred, method, _, err = ResolveCredentialFull(provider, explicit)
124 return cred, method, err
125}
126
127// ResolveCredentialFull is like ResolveCredential but also returns a
128// provider-specific accountID when the credential is an OpenAI OAuth
129// token (the ChatGPT account id extracted from the stored id_token).
130// accountID is "" for API-key auth and for anthropic.
131func ResolveCredentialFull(provider, explicit string) (cred, method, accountID string, err error) {
132 if explicit != "" {
133 return explicit, "apikey", "", nil
134 }
135 switch provider {
136 case "anthropic":
137 if v := os.Getenv("ANTHROPIC_API_KEY"); v != "" {
138 return v, "apikey", "", nil
139 }
140 case "openai":
141 if v := os.Getenv("OPENAI_API_KEY"); v != "" {
142 return v, "apikey", "", nil
143 }
144 case "kimi":
145 if v := os.Getenv("KIMI_API_KEY"); v != "" {
146 return v, "apikey", "", nil
147 }
148 if v := os.Getenv("MOONSHOT_API_KEY"); v != "" {
149 return v, "apikey", "", nil
150 }
151 case "google":
152 // Both env names are widely-used in the Google ecosystem;
153 // GEMINI_API_KEY is the AI Studio default, GOOGLE_API_KEY
154 // is the older / generic name. Either works.
155 if v := os.Getenv("GEMINI_API_KEY"); v != "" {
156 return v, "apikey", "", nil
157 }
158 if v := os.Getenv("GOOGLE_API_KEY"); v != "" {
159 return v, "apikey", "", nil
160 }
161 case "deepseek":
162 if v := os.Getenv("DEEPSEEK_API_KEY"); v != "" {
163 return v, "apikey", "", nil
164 }
165 }
166 c, err := AuthStoreFor().Load()
167 if err != nil {
168 return "", "", "", err
169 }
170 switch provider {
171 case "anthropic":
172 if c.Anthropic.APIKey != "" {
173 return c.Anthropic.APIKey, "apikey", "", nil
174 }
175 if c.Anthropic.OAuth != nil && c.Anthropic.OAuth.AccessToken != "" {
176 tok, _ := refreshIfExpired("anthropic", c.Anthropic.OAuth)
177 return tok.AccessToken, "oauth", "", nil
178 }
179 case "openai":
180 if c.OpenAI.APIKey != "" {
181 return c.OpenAI.APIKey, "apikey", "", nil
182 }
183 if c.OpenAI.OAuth != nil && c.OpenAI.OAuth.AccessToken != "" {
184 tok, _ := refreshIfExpired("openai", c.OpenAI.OAuth)
185 return tok.AccessToken, "oauth", tok.AccountID, nil
186 }
187 case "kimi":
188 if c.Kimi.APIKey != "" {
189 return c.Kimi.APIKey, "apikey", "", nil
190 }
191 if c.Kimi.OAuth != nil && c.Kimi.OAuth.AccessToken != "" {
192 tok, _ := refreshIfExpired("kimi", c.Kimi.OAuth)
193 return tok.AccessToken, "oauth", "", nil
194 }
195 if kimiCLIFallbackDisabled() {
196 break
197 }
198 if tok := loadKimiCodeCLIToken(); tok != nil && tok.AccessToken != "" {
199 tok, _ = refreshIfExpired("kimi", tok)
200 return tok.AccessToken, "oauth", "", nil
201 }
202 case "deepseek":
203 if c.DeepSeek.APIKey != "" {
204 return c.DeepSeek.APIKey, "apikey", "", nil
205 }
206 case "google":
207 // Google is API-key only — no OAuth path. We still load
208 // auth.json so /login api-key flows work without exporting
209 // an env var.
210 if c.Google.APIKey != "" {
211 return c.Google.APIKey, "apikey", "", nil
212 }
213 }
214 return "", "", "", fmt.Errorf("no credential for %s", provider)
215}
216
217func kimiCLIFallbackDisabled() bool {
218 _, err := os.Stat(KimiCLIFallbackDisabledPath())
219 return err == nil
220}
221
222func SetKimiCLIFallbackDisabled(disabled bool) error {
223 path := KimiCLIFallbackDisabledPath()
224 if !disabled {
225 if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
226 return err
227 }
228 return nil
229 }
230 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
231 return err
232 }
233 return os.WriteFile(path, []byte("disabled\n"), 0o600)
234}
235
236func loadKimiCodeCLIToken() *auth.OAuthToken {
237 home, err := os.UserHomeDir()
238 if err != nil {
239 return nil
240 }
241 b, err := os.ReadFile(filepath.Join(home, ".kimi", "credentials", "kimi-code.json"))
242 if err != nil {
243 return nil
244 }
245 var raw struct {
246 AccessToken string `json:"access_token"`
247 RefreshToken string `json:"refresh_token"`
248 TokenType string `json:"token_type"`
249 ExpiresAt float64 `json:"expires_at"`
250 Scope string `json:"scope"`
251 ExpiresIn float64 `json:"expires_in"`
252 }
253 if err := json.Unmarshal(b, &raw); err != nil || raw.AccessToken == "" {
254 return nil
255 }
256 sec := int64(raw.ExpiresAt)
257 nsec := int64((raw.ExpiresAt - float64(sec)) * 1e9)
258 return &auth.OAuthToken{
259 AccessToken: raw.AccessToken,
260 RefreshToken: raw.RefreshToken,
261 TokenType: raw.TokenType,
262 Scope: raw.Scope,
263 ClientID: auth.KimiOAuth.ClientID,
264 Expiry: time.Unix(sec, nsec),
265 }
266}
267
268// loadOAuthToken reads the current OAuth token from auth.json for the
269// given provider. Returns nil if no token is stored.
270func loadOAuthToken(providerName string) *auth.OAuthToken {
271 c, err := AuthStoreFor().Load()
272 if err != nil {
273 return nil
274 }
275 switch providerName {
276 case "anthropic":
277 if c.Anthropic.OAuth != nil {
278 return c.Anthropic.OAuth
279 }
280 case "openai":
281 if c.OpenAI.OAuth != nil {
282 return c.OpenAI.OAuth
283 }
284 case "kimi":
285 if c.Kimi.OAuth != nil {
286 return c.Kimi.OAuth
287 }
288 if kimiCLIFallbackDisabled() {
289 return nil
290 }
291 return loadKimiCodeCLIToken()
292 }
293 return nil
294}
295
296// refreshIfExpired returns a usable OAuth token for the given provider,
297// refreshing it synchronously when it's past (or near) expiry. The
298// refreshed token is persisted to auth.json.
299//
300// Failures return the original token unchanged — the caller then makes
301// a request with the stale access_token, which will 401. That's still
302// better than crashing at credential-resolution time.
303func refreshIfExpired(providerName string, tok *auth.OAuthToken) (*auth.OAuthToken, error) {
304 if tok == nil {
305 return &auth.OAuthToken{}, fmt.Errorf("nil token")
306 }
307 if !tok.Expired() {
308 return tok, nil
309 }
310 if tok.RefreshToken == "" {
311 return tok, fmt.Errorf("%s oauth token expired and no refresh_token available — run /login again", providerName)
312 }
313
314 var op auth.OAuthProvider
315 switch providerName {
316 case "anthropic":
317 op = auth.AnthropicOAuth
318 case "openai":
319 op = auth.OpenAIOAuth
320 case "kimi":
321 op = auth.KimiOAuth
322 default:
323 return tok, fmt.Errorf("unknown provider %q", providerName)
324 }
325
326 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
327 defer cancel()
328 next, err := op.Refresh(ctx, tok.RefreshToken)
329 if err != nil {
330 return tok, fmt.Errorf("refresh %s: %w", providerName, err)
331 }
332 // Preserve the refresh token if the server omitted it (Anthropic often does).
333 if next.RefreshToken == "" {
334 next.RefreshToken = tok.RefreshToken
335 }
336 // Carry over account id (openai) / id_token across refreshes.
337 if next.AccountID == "" {
338 next.AccountID = tok.AccountID
339 }
340 if next.IDToken == "" {
341 next.IDToken = tok.IDToken
342 }
343 if err := AuthStoreFor().SetOAuth(providerName, *next); err != nil {
344 return next, fmt.Errorf("persist refreshed token: %w", err)
345 }
346 return next, nil
347}