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 // LastChangelogShown is the version whose release-notes
25 // dialog the user has already seen. When the running binary's
26 // version differs, the next interactive run shows the
27 // changelog (fetched from the GitHub release page) once and
28 // updates this field. Empty means "never shown".
29 LastChangelogShown string `json:"last_changelog_shown,omitempty"`
30}
31
32// ZotHome returns $ZOT_HOME or the OS-default data dir.
33//
34// All zot state (config.json, auth.json, sessions/, logs/) lives under
35// this directory.
36func ZotHome() string {
37 if v := os.Getenv("ZOT_HOME"); v != "" {
38 return v
39 }
40 switch runtime.GOOS {
41 case "darwin":
42 if home, err := os.UserHomeDir(); err == nil {
43 return filepath.Join(home, "Library", "Application Support", "zot")
44 }
45 case "windows":
46 if v := os.Getenv("LOCALAPPDATA"); v != "" {
47 return filepath.Join(v, "zot")
48 }
49 }
50 if v := os.Getenv("XDG_STATE_HOME"); v != "" {
51 return filepath.Join(v, "zot")
52 }
53 if home, err := os.UserHomeDir(); err == nil {
54 return filepath.Join(home, ".local", "state", "zot")
55 }
56 return ".zot"
57}
58
59// ConfigPath returns the path to config.json.
60func ConfigPath() string { return filepath.Join(ZotHome(), "config.json") }
61
62// AuthPath returns the path to auth.json.
63func AuthPath() string { return filepath.Join(ZotHome(), "auth.json") }
64
65// SessionsPath returns the directory holding session files.
66func SessionsPath() string { return filepath.Join(ZotHome(), "sessions") }
67
68// LogsPath returns the directory holding log files.
69func LogsPath() string { return filepath.Join(ZotHome(), "logs") }
70
71// LoadConfig reads the config file, returning defaults if missing.
72func LoadConfig() (Config, error) {
73 var c Config
74 b, err := os.ReadFile(ConfigPath())
75 if errors.Is(err, os.ErrNotExist) {
76 return c, nil
77 }
78 if err != nil {
79 return c, err
80 }
81 if err := json.Unmarshal(b, &c); err != nil {
82 return c, fmt.Errorf("parse config: %w", err)
83 }
84 return c, nil
85}
86
87// SaveConfig writes the config file, creating parent dirs.
88func SaveConfig(c Config) error {
89 if err := os.MkdirAll(ZotHome(), 0o755); err != nil {
90 return err
91 }
92 b, err := json.MarshalIndent(c, "", " ")
93 if err != nil {
94 return err
95 }
96 return os.WriteFile(ConfigPath(), b, 0o644)
97}
98
99// AuthStoreFor returns the auth.Store backed by AuthPath().
100func AuthStoreFor() *auth.Store { return auth.NewStore(AuthPath()) }
101
102// ResolveCredential returns the credential (api key or oauth access
103// token), the method ("apikey"/"oauth"), and an error when no
104// credential is available.
105//
106// Lookup order:
107// 1. explicit (e.g. --api-key): treated as API key
108// 2. provider-specific env var: treated as API key
109// 3. auth.json: api key OR oauth, whichever is present
110func ResolveCredential(provider, explicit string) (cred, method string, err error) {
111 cred, method, _, err = ResolveCredentialFull(provider, explicit)
112 return cred, method, err
113}
114
115// ResolveCredentialFull is like ResolveCredential but also returns a
116// provider-specific accountID when the credential is an OpenAI OAuth
117// token (the ChatGPT account id extracted from the stored id_token).
118// accountID is "" for API-key auth and for anthropic.
119func ResolveCredentialFull(provider, explicit string) (cred, method, accountID string, err error) {
120 if explicit != "" {
121 return explicit, "apikey", "", nil
122 }
123 switch provider {
124 case "anthropic":
125 if v := os.Getenv("ANTHROPIC_API_KEY"); v != "" {
126 return v, "apikey", "", nil
127 }
128 case "openai":
129 if v := os.Getenv("OPENAI_API_KEY"); v != "" {
130 return v, "apikey", "", nil
131 }
132 }
133 c, err := AuthStoreFor().Load()
134 if err != nil {
135 return "", "", "", err
136 }
137 switch provider {
138 case "anthropic":
139 if c.Anthropic.APIKey != "" {
140 return c.Anthropic.APIKey, "apikey", "", nil
141 }
142 if c.Anthropic.OAuth != nil && c.Anthropic.OAuth.AccessToken != "" {
143 tok, _ := refreshIfExpired("anthropic", c.Anthropic.OAuth)
144 return tok.AccessToken, "oauth", "", nil
145 }
146 case "openai":
147 if c.OpenAI.APIKey != "" {
148 return c.OpenAI.APIKey, "apikey", "", nil
149 }
150 if c.OpenAI.OAuth != nil && c.OpenAI.OAuth.AccessToken != "" {
151 tok, _ := refreshIfExpired("openai", c.OpenAI.OAuth)
152 return tok.AccessToken, "oauth", tok.AccountID, nil
153 }
154 }
155 return "", "", "", fmt.Errorf("no credential for %s", provider)
156}
157
158// loadOAuthToken reads the current OAuth token from auth.json for the
159// given provider. Returns nil if no token is stored.
160func loadOAuthToken(providerName string) *auth.OAuthToken {
161 c, err := AuthStoreFor().Load()
162 if err != nil {
163 return nil
164 }
165 switch providerName {
166 case "anthropic":
167 if c.Anthropic.OAuth != nil {
168 return c.Anthropic.OAuth
169 }
170 case "openai":
171 if c.OpenAI.OAuth != nil {
172 return c.OpenAI.OAuth
173 }
174 }
175 return nil
176}
177
178// refreshIfExpired returns a usable OAuth token for the given provider,
179// refreshing it synchronously when it's past (or near) expiry. The
180// refreshed token is persisted to auth.json.
181//
182// Failures return the original token unchanged — the caller then makes
183// a request with the stale access_token, which will 401. That's still
184// better than crashing at credential-resolution time.
185func refreshIfExpired(providerName string, tok *auth.OAuthToken) (*auth.OAuthToken, error) {
186 if tok == nil {
187 return &auth.OAuthToken{}, fmt.Errorf("nil token")
188 }
189 if !tok.Expired() {
190 return tok, nil
191 }
192 if tok.RefreshToken == "" {
193 return tok, fmt.Errorf("%s oauth token expired and no refresh_token available — run /login again", providerName)
194 }
195
196 var op auth.OAuthProvider
197 switch providerName {
198 case "anthropic":
199 op = auth.AnthropicOAuth
200 case "openai":
201 op = auth.OpenAIOAuth
202 default:
203 return tok, fmt.Errorf("unknown provider %q", providerName)
204 }
205
206 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
207 defer cancel()
208 next, err := op.Refresh(ctx, tok.RefreshToken)
209 if err != nil {
210 return tok, fmt.Errorf("refresh %s: %w", providerName, err)
211 }
212 // Preserve the refresh token if the server omitted it (Anthropic often does).
213 if next.RefreshToken == "" {
214 next.RefreshToken = tok.RefreshToken
215 }
216 // Carry over account id (openai) / id_token across refreshes.
217 if next.AccountID == "" {
218 next.AccountID = tok.AccountID
219 }
220 if next.IDToken == "" {
221 next.IDToken = tok.IDToken
222 }
223 if err := AuthStoreFor().SetOAuth(providerName, *next); err != nil {
224 return next, fmt.Errorf("persist refreshed token: %w", err)
225 }
226 return next, nil
227}