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 }
162 c, err := AuthStoreFor().Load()
163 if err != nil {
164 return "", "", "", err
165 }
166 switch provider {
167 case "anthropic":
168 if c.Anthropic.APIKey != "" {
169 return c.Anthropic.APIKey, "apikey", "", nil
170 }
171 if c.Anthropic.OAuth != nil && c.Anthropic.OAuth.AccessToken != "" {
172 tok, _ := refreshIfExpired("anthropic", c.Anthropic.OAuth)
173 return tok.AccessToken, "oauth", "", nil
174 }
175 case "openai":
176 if c.OpenAI.APIKey != "" {
177 return c.OpenAI.APIKey, "apikey", "", nil
178 }
179 if c.OpenAI.OAuth != nil && c.OpenAI.OAuth.AccessToken != "" {
180 tok, _ := refreshIfExpired("openai", c.OpenAI.OAuth)
181 return tok.AccessToken, "oauth", tok.AccountID, nil
182 }
183 case "kimi":
184 if c.Kimi.APIKey != "" {
185 return c.Kimi.APIKey, "apikey", "", nil
186 }
187 if c.Kimi.OAuth != nil && c.Kimi.OAuth.AccessToken != "" {
188 tok, _ := refreshIfExpired("kimi", c.Kimi.OAuth)
189 return tok.AccessToken, "oauth", "", nil
190 }
191 if kimiCLIFallbackDisabled() {
192 break
193 }
194 if tok := loadKimiCodeCLIToken(); tok != nil && tok.AccessToken != "" {
195 tok, _ = refreshIfExpired("kimi", tok)
196 return tok.AccessToken, "oauth", "", nil
197 }
198 case "google":
199 // Google is API-key only — no OAuth path. We still load
200 // auth.json so /login api-key flows work without exporting
201 // an env var.
202 if c.Google.APIKey != "" {
203 return c.Google.APIKey, "apikey", "", nil
204 }
205 }
206 return "", "", "", fmt.Errorf("no credential for %s", provider)
207}
208
209func kimiCLIFallbackDisabled() bool {
210 _, err := os.Stat(KimiCLIFallbackDisabledPath())
211 return err == nil
212}
213
214func SetKimiCLIFallbackDisabled(disabled bool) error {
215 path := KimiCLIFallbackDisabledPath()
216 if !disabled {
217 if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
218 return err
219 }
220 return nil
221 }
222 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
223 return err
224 }
225 return os.WriteFile(path, []byte("disabled\n"), 0o600)
226}
227
228func loadKimiCodeCLIToken() *auth.OAuthToken {
229 home, err := os.UserHomeDir()
230 if err != nil {
231 return nil
232 }
233 b, err := os.ReadFile(filepath.Join(home, ".kimi", "credentials", "kimi-code.json"))
234 if err != nil {
235 return nil
236 }
237 var raw struct {
238 AccessToken string `json:"access_token"`
239 RefreshToken string `json:"refresh_token"`
240 TokenType string `json:"token_type"`
241 ExpiresAt float64 `json:"expires_at"`
242 Scope string `json:"scope"`
243 ExpiresIn float64 `json:"expires_in"`
244 }
245 if err := json.Unmarshal(b, &raw); err != nil || raw.AccessToken == "" {
246 return nil
247 }
248 sec := int64(raw.ExpiresAt)
249 nsec := int64((raw.ExpiresAt - float64(sec)) * 1e9)
250 return &auth.OAuthToken{
251 AccessToken: raw.AccessToken,
252 RefreshToken: raw.RefreshToken,
253 TokenType: raw.TokenType,
254 Scope: raw.Scope,
255 ClientID: auth.KimiOAuth.ClientID,
256 Expiry: time.Unix(sec, nsec),
257 }
258}
259
260// loadOAuthToken reads the current OAuth token from auth.json for the
261// given provider. Returns nil if no token is stored.
262func loadOAuthToken(providerName string) *auth.OAuthToken {
263 c, err := AuthStoreFor().Load()
264 if err != nil {
265 return nil
266 }
267 switch providerName {
268 case "anthropic":
269 if c.Anthropic.OAuth != nil {
270 return c.Anthropic.OAuth
271 }
272 case "openai":
273 if c.OpenAI.OAuth != nil {
274 return c.OpenAI.OAuth
275 }
276 case "kimi":
277 if c.Kimi.OAuth != nil {
278 return c.Kimi.OAuth
279 }
280 if kimiCLIFallbackDisabled() {
281 return nil
282 }
283 return loadKimiCodeCLIToken()
284 }
285 return nil
286}
287
288// refreshIfExpired returns a usable OAuth token for the given provider,
289// refreshing it synchronously when it's past (or near) expiry. The
290// refreshed token is persisted to auth.json.
291//
292// Failures return the original token unchanged — the caller then makes
293// a request with the stale access_token, which will 401. That's still
294// better than crashing at credential-resolution time.
295func refreshIfExpired(providerName string, tok *auth.OAuthToken) (*auth.OAuthToken, error) {
296 if tok == nil {
297 return &auth.OAuthToken{}, fmt.Errorf("nil token")
298 }
299 if !tok.Expired() {
300 return tok, nil
301 }
302 if tok.RefreshToken == "" {
303 return tok, fmt.Errorf("%s oauth token expired and no refresh_token available — run /login again", providerName)
304 }
305
306 var op auth.OAuthProvider
307 switch providerName {
308 case "anthropic":
309 op = auth.AnthropicOAuth
310 case "openai":
311 op = auth.OpenAIOAuth
312 case "kimi":
313 op = auth.KimiOAuth
314 default:
315 return tok, fmt.Errorf("unknown provider %q", providerName)
316 }
317
318 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
319 defer cancel()
320 next, err := op.Refresh(ctx, tok.RefreshToken)
321 if err != nil {
322 return tok, fmt.Errorf("refresh %s: %w", providerName, err)
323 }
324 // Preserve the refresh token if the server omitted it (Anthropic often does).
325 if next.RefreshToken == "" {
326 next.RefreshToken = tok.RefreshToken
327 }
328 // Carry over account id (openai) / id_token across refreshes.
329 if next.AccountID == "" {
330 next.AccountID = tok.AccountID
331 }
332 if next.IDToken == "" {
333 next.IDToken = tok.IDToken
334 }
335 if err := AuthStoreFor().SetOAuth(providerName, *next); err != nil {
336 return next, fmt.Errorf("persist refreshed token: %w", err)
337 }
338 return next, nil
339}