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