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