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