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// refreshIfExpired returns a usable OAuth token for the given provider,
159// refreshing it synchronously when it's past (or near) expiry. The
160// refreshed token is persisted to auth.json.
161//
162// Failures return the original token unchanged — the caller then makes
163// a request with the stale access_token, which will 401. That's still
164// better than crashing at credential-resolution time.
165func refreshIfExpired(providerName string, tok *auth.OAuthToken) (*auth.OAuthToken, error) {
166 if tok == nil {
167 return &auth.OAuthToken{}, fmt.Errorf("nil token")
168 }
169 if !tok.Expired() {
170 return tok, nil
171 }
172 if tok.RefreshToken == "" {
173 return tok, fmt.Errorf("%s oauth token expired and no refresh_token available — run /login again", providerName)
174 }
175
176 var op auth.OAuthProvider
177 switch providerName {
178 case "anthropic":
179 op = auth.AnthropicOAuth
180 case "openai":
181 op = auth.OpenAIOAuth
182 default:
183 return tok, fmt.Errorf("unknown provider %q", providerName)
184 }
185
186 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
187 defer cancel()
188 next, err := op.Refresh(ctx, tok.RefreshToken)
189 if err != nil {
190 return tok, fmt.Errorf("refresh %s: %w", providerName, err)
191 }
192 // Preserve the refresh token if the server omitted it (Anthropic often does).
193 if next.RefreshToken == "" {
194 next.RefreshToken = tok.RefreshToken
195 }
196 // Carry over account id (openai) / id_token across refreshes.
197 if next.AccountID == "" {
198 next.AccountID = tok.AccountID
199 }
200 if next.IDToken == "" {
201 next.IDToken = tok.IDToken
202 }
203 if err := AuthStoreFor().SetOAuth(providerName, *next); err != nil {
204 return next, fmt.Errorf("persist refreshed token: %w", err)
205 }
206 return next, nil
207}