hkfires commited on
Commit
d466f9f
·
1 Parent(s): a7b7b9c

feat(gemini-web): squash all features and fixes for gemini-web

Browse files
.dockerignore CHANGED
@@ -27,5 +27,6 @@ conv/*
27
  config.yaml
28
 
29
  # Development/editor
 
30
  .claude/*
31
  .vscode/*
 
27
  config.yaml
28
 
29
  # Development/editor
30
+ bin/*
31
  .claude/*
32
  .vscode/*
.gitignore CHANGED
@@ -1,5 +1,4 @@
1
  config.yaml
2
- *.exe
3
  bin/*
4
  docs/*
5
  logs/*
@@ -9,4 +8,5 @@ auths/*
9
  .vscode/*
10
  .claude/*
11
  AGENTS.md
12
- CLAUDE.md
 
 
1
  config.yaml
 
2
  bin/*
3
  docs/*
4
  logs/*
 
8
  .vscode/*
9
  .claude/*
10
  AGENTS.md
11
+ CLAUDE.md
12
+ *.exe
cmd/server/main.go CHANGED
@@ -72,6 +72,7 @@ func main() {
72
  var codexLogin bool
73
  var claudeLogin bool
74
  var qwenLogin bool
 
75
  var noBrowser bool
76
  var projectID string
77
  var configPath string
@@ -81,6 +82,7 @@ func main() {
81
  flag.BoolVar(&codexLogin, "codex-login", false, "Login to Codex using OAuth")
82
  flag.BoolVar(&claudeLogin, "claude-login", false, "Login to Claude using OAuth")
83
  flag.BoolVar(&qwenLogin, "qwen-login", false, "Login to Qwen using OAuth")
 
84
  flag.BoolVar(&noBrowser, "no-browser", false, "Don't open browser automatically for OAuth")
85
  flag.StringVar(&projectID, "project_id", "", "Project ID (Gemini only, not required)")
86
  flag.StringVar(&configPath, "config", "", "Configure File Path")
@@ -151,6 +153,8 @@ func main() {
151
  cmd.DoClaudeLogin(cfg, options)
152
  } else if qwenLogin {
153
  cmd.DoQwenLogin(cfg, options)
 
 
154
  } else {
155
  // Start the main proxy service
156
  cmd.StartService(cfg, configFilePath)
 
72
  var codexLogin bool
73
  var claudeLogin bool
74
  var qwenLogin bool
75
+ var geminiWebAuth bool
76
  var noBrowser bool
77
  var projectID string
78
  var configPath string
 
82
  flag.BoolVar(&codexLogin, "codex-login", false, "Login to Codex using OAuth")
83
  flag.BoolVar(&claudeLogin, "claude-login", false, "Login to Claude using OAuth")
84
  flag.BoolVar(&qwenLogin, "qwen-login", false, "Login to Qwen using OAuth")
85
+ flag.BoolVar(&geminiWebAuth, "gemini-web-auth", false, "Auth Gemini Web using cookies")
86
  flag.BoolVar(&noBrowser, "no-browser", false, "Don't open browser automatically for OAuth")
87
  flag.StringVar(&projectID, "project_id", "", "Project ID (Gemini only, not required)")
88
  flag.StringVar(&configPath, "config", "", "Configure File Path")
 
153
  cmd.DoClaudeLogin(cfg, options)
154
  } else if qwenLogin {
155
  cmd.DoQwenLogin(cfg, options)
156
+ } else if geminiWebAuth {
157
+ cmd.DoGeminiWebAuth(cfg)
158
  } else {
159
  // Start the main proxy service
160
  cmd.StartService(cfg, configFilePath)
config.example.yaml CHANGED
@@ -65,3 +65,23 @@ openai-compatibility:
65
  models: # The models supported by the provider.
66
  - name: "moonshotai/kimi-k2:free" # The actual model name.
67
  alias: "kimi-k2" # The alias used in the API.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  models: # The models supported by the provider.
66
  - name: "moonshotai/kimi-k2:free" # The actual model name.
67
  alias: "kimi-k2" # The alias used in the API.
68
+
69
+ # Gemini Web settings
70
+ # gemini-web:
71
+ # # Conversation reuse: set to true to enable (default), false to disable.
72
+ # context: true
73
+ # # Maximum characters per single request to Gemini Web. Requests exceeding this
74
+ # # size split into chunks. Only the last chunk carries files and yields the final answer.
75
+ # max-chars-per-request: 1000000
76
+ # # Disable the short continuation hint appended to intermediate chunks
77
+ # # when splitting long prompts. Default is false (hint enabled by default).
78
+ # disable-continuation-hint: false
79
+ # # Background token auto-refresh interval seconds (defaults to 540 if unset or <= 0)
80
+ # token-refresh-seconds: 540
81
+ # # Code mode:
82
+ # # - true: enable XML wrapping hint and attach the coding-partner Gem.
83
+ # # Thought merging (<think> into visible content) applies to STREAMING only;
84
+ # # non-stream responses keep reasoning/thought parts separate for clients
85
+ # # that expect explicit reasoning fields.
86
+ # # - false: disable XML hint and keep <think> separate
87
+ # code-mode: false
docker-compose.yml CHANGED
@@ -19,4 +19,5 @@ services:
19
  - ./config.yaml:/CLIProxyAPI/config.yaml
20
  - ./auths:/root/.cli-proxy-api
21
  - ./logs:/CLIProxyAPI/logs
 
22
  restart: unless-stopped
 
19
  - ./config.yaml:/CLIProxyAPI/config.yaml
20
  - ./auths:/root/.cli-proxy-api
21
  - ./logs:/CLIProxyAPI/logs
22
+ - ./conv:/CLIProxyAPI/conv
23
  restart: unless-stopped
internal/api/server.go CHANGED
@@ -380,6 +380,8 @@ func (s *Server) UpdateClients(clients map[string]interfaces.Client, cfg *config
380
  switch cl := c.(type) {
381
  case *client.GeminiCLIClient:
382
  authFiles++
 
 
383
  case *client.CodexClient:
384
  if cl.GetAPIKey() == "" {
385
  authFiles++
 
380
  switch cl := c.(type) {
381
  case *client.GeminiCLIClient:
382
  authFiles++
383
+ case *client.GeminiWebClient:
384
+ authFiles++
385
  case *client.CodexClient:
386
  if cl.GetAPIKey() == "" {
387
  authFiles++
internal/auth/gemini/gemini-web_token.go ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Package gemini provides authentication and token management functionality
2
+ // for Google's Gemini AI services. It handles OAuth2 token storage, serialization,
3
+ // and retrieval for maintaining authenticated sessions with the Gemini API.
4
+ package gemini
5
+
6
+ import (
7
+ "encoding/json"
8
+ "fmt"
9
+ "os"
10
+ "path/filepath"
11
+
12
+ log "github.com/sirupsen/logrus"
13
+ )
14
+
15
+ // GeminiWebTokenStorage stores cookie information for Google Gemini Web authentication.
16
+ type GeminiWebTokenStorage struct {
17
+ Secure1PSID string `json:"secure_1psid"`
18
+ Secure1PSIDTS string `json:"secure_1psidts"`
19
+ Type string `json:"type"`
20
+ }
21
+
22
+ // SaveTokenToFile serializes the Gemini Web token storage to a JSON file.
23
+ func (ts *GeminiWebTokenStorage) SaveTokenToFile(authFilePath string) error {
24
+ ts.Type = "gemini-web"
25
+ if err := os.MkdirAll(filepath.Dir(authFilePath), 0700); err != nil {
26
+ return fmt.Errorf("failed to create directory: %v", err)
27
+ }
28
+
29
+ f, err := os.Create(authFilePath)
30
+ if err != nil {
31
+ return fmt.Errorf("failed to create token file: %w", err)
32
+ }
33
+ defer func() {
34
+ if errClose := f.Close(); errClose != nil {
35
+ log.Errorf("failed to close file: %v", errClose)
36
+ }
37
+ }()
38
+
39
+ if err = json.NewEncoder(f).Encode(ts); err != nil {
40
+ return fmt.Errorf("failed to write token to file: %w", err)
41
+ }
42
+ return nil
43
+ }
internal/client/claude_client.go CHANGED
@@ -331,8 +331,16 @@ func (c *ClaudeClient) SendRawTokenCount(_ context.Context, _ string, _ []byte,
331
  // Returns:
332
  // - error: An error if the save operation fails, nil otherwise.
333
  func (c *ClaudeClient) SaveTokenToFile() error {
334
- fileName := filepath.Join(c.cfg.AuthDir, fmt.Sprintf("claude-%s.json", c.tokenStorage.(*claude.ClaudeTokenStorage).Email))
335
- return c.tokenStorage.SaveTokenToFile(fileName)
 
 
 
 
 
 
 
 
336
  }
337
 
338
  // RefreshTokens refreshes the access tokens if they have expired.
 
331
  // Returns:
332
  // - error: An error if the save operation fails, nil otherwise.
333
  func (c *ClaudeClient) SaveTokenToFile() error {
334
+ // API-key based clients don't have a file-backed token to persist.
335
+ if c.apiKeyIndex != -1 {
336
+ return nil
337
+ }
338
+ ts, ok := c.tokenStorage.(*claude.ClaudeTokenStorage)
339
+ if !ok || ts == nil || ts.Email == "" {
340
+ return nil
341
+ }
342
+ fileName := filepath.Join(c.cfg.AuthDir, fmt.Sprintf("claude-%s.json", ts.Email))
343
+ return ts.SaveTokenToFile(fileName)
344
  }
345
 
346
  // RefreshTokens refreshes the access tokens if they have expired.
internal/client/codex_client.go CHANGED
@@ -324,8 +324,16 @@ func (c *CodexClient) SendRawTokenCount(_ context.Context, _ string, _ []byte, _
324
  // Returns:
325
  // - error: An error if the save operation fails, nil otherwise.
326
  func (c *CodexClient) SaveTokenToFile() error {
327
- fileName := filepath.Join(c.cfg.AuthDir, fmt.Sprintf("codex-%s.json", c.tokenStorage.(*codex.CodexTokenStorage).Email))
328
- return c.tokenStorage.SaveTokenToFile(fileName)
 
 
 
 
 
 
 
 
329
  }
330
 
331
  // RefreshTokens refreshes the access tokens if needed
 
324
  // Returns:
325
  // - error: An error if the save operation fails, nil otherwise.
326
  func (c *CodexClient) SaveTokenToFile() error {
327
+ // API-key based clients don't have a file-backed token to persist.
328
+ if c.apiKeyIndex != -1 {
329
+ return nil
330
+ }
331
+ ts, ok := c.tokenStorage.(*codex.CodexTokenStorage)
332
+ if !ok || ts == nil || ts.Email == "" {
333
+ return nil
334
+ }
335
+ fileName := filepath.Join(c.cfg.AuthDir, fmt.Sprintf("codex-%s.json", ts.Email))
336
+ return ts.SaveTokenToFile(fileName)
337
  }
338
 
339
  // RefreshTokens refreshes the access tokens if needed
internal/client/gemini-web/auth.go ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package geminiwebapi
2
+
3
+ import (
4
+ "crypto/tls"
5
+ "errors"
6
+ "io"
7
+ "net/http"
8
+ "net/http/cookiejar"
9
+ "net/url"
10
+ "os"
11
+ "path/filepath"
12
+ "regexp"
13
+ "strings"
14
+ "time"
15
+ )
16
+
17
+ type httpOptions struct {
18
+ ProxyURL string
19
+ Insecure bool
20
+ FollowRedirects bool
21
+ }
22
+
23
+ func newHTTPClient(opts httpOptions) *http.Client {
24
+ transport := &http.Transport{}
25
+ if opts.ProxyURL != "" {
26
+ if pu, err := url.Parse(opts.ProxyURL); err == nil {
27
+ transport.Proxy = http.ProxyURL(pu)
28
+ }
29
+ }
30
+ if opts.Insecure {
31
+ transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
32
+ }
33
+ jar, _ := cookiejar.New(nil)
34
+ client := &http.Client{Transport: transport, Timeout: 60 * time.Second, Jar: jar}
35
+ if !opts.FollowRedirects {
36
+ client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
37
+ return http.ErrUseLastResponse
38
+ }
39
+ }
40
+ return client
41
+ }
42
+
43
+ func applyHeaders(req *http.Request, headers http.Header) {
44
+ for k, v := range headers {
45
+ for _, vv := range v {
46
+ req.Header.Add(k, vv)
47
+ }
48
+ }
49
+ }
50
+
51
+ func applyCookies(req *http.Request, cookies map[string]string) {
52
+ for k, v := range cookies {
53
+ req.AddCookie(&http.Cookie{Name: k, Value: v})
54
+ }
55
+ }
56
+
57
+ func sendInitRequest(cookies map[string]string, proxy string, insecure bool) (*http.Response, map[string]string, error) {
58
+ client := newHTTPClient(httpOptions{ProxyURL: proxy, Insecure: insecure, FollowRedirects: true})
59
+ req, _ := http.NewRequest(http.MethodGet, EndpointInit, nil)
60
+ applyHeaders(req, HeadersGemini)
61
+ applyCookies(req, cookies)
62
+ resp, err := client.Do(req)
63
+ if err != nil {
64
+ return nil, nil, err
65
+ }
66
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
67
+ return resp, nil, &AuthError{Msg: resp.Status}
68
+ }
69
+ outCookies := map[string]string{}
70
+ for _, c := range resp.Cookies() {
71
+ outCookies[c.Name] = c.Value
72
+ }
73
+ for k, v := range cookies {
74
+ outCookies[k] = v
75
+ }
76
+ return resp, outCookies, nil
77
+ }
78
+
79
+ func getAccessToken(baseCookies map[string]string, proxy string, verbose bool, insecure bool) (string, map[string]string, error) {
80
+ // Warm-up google.com to gain extra cookies (NID, etc.) and capture them.
81
+ extraCookies := map[string]string{}
82
+ {
83
+ client := newHTTPClient(httpOptions{ProxyURL: proxy, Insecure: insecure, FollowRedirects: true})
84
+ req, _ := http.NewRequest(http.MethodGet, EndpointGoogle, nil)
85
+ resp, _ := client.Do(req)
86
+ if resp != nil {
87
+ if u, err := url.Parse(EndpointGoogle); err == nil {
88
+ for _, c := range client.Jar.Cookies(u) {
89
+ extraCookies[c.Name] = c.Value
90
+ }
91
+ }
92
+ _ = resp.Body.Close()
93
+ }
94
+ }
95
+
96
+ trySets := make([]map[string]string, 0, 8)
97
+
98
+ if v1, ok1 := baseCookies["__Secure-1PSID"]; ok1 {
99
+ if v2, ok2 := baseCookies["__Secure-1PSIDTS"]; ok2 {
100
+ merged := map[string]string{"__Secure-1PSID": v1, "__Secure-1PSIDTS": v2}
101
+ if nid, ok := baseCookies["NID"]; ok {
102
+ merged["NID"] = nid
103
+ }
104
+ trySets = append(trySets, merged)
105
+ } else if verbose {
106
+ Debug("Skipping base cookies: __Secure-1PSIDTS missing")
107
+ }
108
+ }
109
+
110
+ cacheDir := "temp"
111
+ _ = os.MkdirAll(cacheDir, 0o755)
112
+ if v1, ok1 := baseCookies["__Secure-1PSID"]; ok1 {
113
+ cacheFile := filepath.Join(cacheDir, ".cached_1psidts_"+v1+".txt")
114
+ if b, err := os.ReadFile(cacheFile); err == nil {
115
+ cv := strings.TrimSpace(string(b))
116
+ if cv != "" {
117
+ merged := map[string]string{"__Secure-1PSID": v1, "__Secure-1PSIDTS": cv}
118
+ trySets = append(trySets, merged)
119
+ }
120
+ }
121
+ }
122
+
123
+ if len(extraCookies) > 0 {
124
+ trySets = append(trySets, extraCookies)
125
+ }
126
+
127
+ reToken := regexp.MustCompile(`"SNlM0e":"([^"]+)"`)
128
+
129
+ for _, cookies := range trySets {
130
+ resp, mergedCookies, err := sendInitRequest(cookies, proxy, insecure)
131
+ if err != nil {
132
+ if verbose {
133
+ Warning("Failed init request: %v", err)
134
+ }
135
+ continue
136
+ }
137
+ body, err := io.ReadAll(resp.Body)
138
+ _ = resp.Body.Close()
139
+ if err != nil {
140
+ return "", nil, err
141
+ }
142
+ matches := reToken.FindStringSubmatch(string(body))
143
+ if len(matches) >= 2 {
144
+ token := matches[1]
145
+ if verbose {
146
+ Success("Gemini access token acquired.")
147
+ }
148
+ return token, mergedCookies, nil
149
+ }
150
+ }
151
+ return "", nil, &AuthError{Msg: "Failed to retrieve token."}
152
+ }
153
+
154
+ // rotate1psidts refreshes __Secure-1PSIDTS and caches it locally.
155
+ func rotate1psidts(cookies map[string]string, proxy string, insecure bool) (string, error) {
156
+ psid, ok := cookies["__Secure-1PSID"]
157
+ if !ok {
158
+ return "", &AuthError{Msg: "__Secure-1PSID missing"}
159
+ }
160
+
161
+ cacheDir := "temp"
162
+ _ = os.MkdirAll(cacheDir, 0o755)
163
+ cacheFile := filepath.Join(cacheDir, ".cached_1psidts_"+psid+".txt")
164
+
165
+ if st, err := os.Stat(cacheFile); err == nil {
166
+ if time.Since(st.ModTime()) <= time.Minute {
167
+ if b, err := os.ReadFile(cacheFile); err == nil {
168
+ v := strings.TrimSpace(string(b))
169
+ if v != "" {
170
+ return v, nil
171
+ }
172
+ }
173
+ }
174
+ }
175
+
176
+ tr := &http.Transport{}
177
+ if proxy != "" {
178
+ if pu, err := url.Parse(proxy); err == nil {
179
+ tr.Proxy = http.ProxyURL(pu)
180
+ }
181
+ }
182
+ if insecure {
183
+ tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
184
+ }
185
+ client := &http.Client{Transport: tr, Timeout: 60 * time.Second}
186
+
187
+ req, _ := http.NewRequest(http.MethodPost, EndpointRotateCookies, io.NopCloser(stringsReader("[000,\"-0000000000000000000\"]")))
188
+ applyHeaders(req, HeadersRotateCookies)
189
+ applyCookies(req, cookies)
190
+
191
+ resp, err := client.Do(req)
192
+ if err != nil {
193
+ return "", err
194
+ }
195
+ defer resp.Body.Close()
196
+
197
+ if resp.StatusCode == http.StatusUnauthorized {
198
+ return "", &AuthError{Msg: "unauthorized"}
199
+ }
200
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
201
+ return "", errors.New(resp.Status)
202
+ }
203
+
204
+ for _, c := range resp.Cookies() {
205
+ if c.Name == "__Secure-1PSIDTS" {
206
+ _ = os.WriteFile(cacheFile, []byte(c.Value), 0o644)
207
+ return c.Value, nil
208
+ }
209
+ }
210
+ return "", nil
211
+ }
212
+
213
+ // Minimal reader helpers to avoid importing strings everywhere.
214
+ type constReader struct {
215
+ s string
216
+ i int
217
+ }
218
+
219
+ func (r *constReader) Read(p []byte) (int, error) {
220
+ if r.i >= len(r.s) {
221
+ return 0, io.EOF
222
+ }
223
+ n := copy(p, r.s[r.i:])
224
+ r.i += n
225
+ return n, nil
226
+ }
227
+
228
+ func stringsReader(s string) io.Reader { return &constReader{s: s} }
internal/client/gemini-web/client.go ADDED
@@ -0,0 +1,772 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package geminiwebapi
2
+
3
+ import (
4
+ "context"
5
+ "encoding/json"
6
+ "errors"
7
+ "fmt"
8
+ "io"
9
+ "net/http"
10
+ "net/url"
11
+ "regexp"
12
+ "strings"
13
+ "sync"
14
+ "time"
15
+ )
16
+
17
+ // GeminiClient is the async http client interface (Go port)
18
+ type GeminiClient struct {
19
+ Cookies map[string]string
20
+ Proxy string
21
+ Running bool
22
+ httpClient *http.Client
23
+ AccessToken string
24
+ Timeout time.Duration
25
+ AutoClose bool
26
+ CloseDelay time.Duration
27
+ closeMu sync.Mutex
28
+ closeTimer *time.Timer
29
+ AutoRefresh bool
30
+ RefreshInterval time.Duration
31
+ rotateCancel context.CancelFunc
32
+ insecure bool
33
+ accountLabel string
34
+ }
35
+
36
+ // NewGeminiClient creates a client. Pass empty strings to auto-detect via browser cookies (not implemented in Go port).
37
+ func NewGeminiClient(secure1psid string, secure1psidts string, proxy string, opts ...func(*GeminiClient)) *GeminiClient {
38
+ c := &GeminiClient{
39
+ Cookies: map[string]string{},
40
+ Proxy: proxy,
41
+ Running: false,
42
+ Timeout: 300 * time.Second,
43
+ AutoClose: false,
44
+ CloseDelay: 300 * time.Second,
45
+ AutoRefresh: true,
46
+ RefreshInterval: 540 * time.Second,
47
+ insecure: false,
48
+ }
49
+ if secure1psid != "" {
50
+ c.Cookies["__Secure-1PSID"] = secure1psid
51
+ if secure1psidts != "" {
52
+ c.Cookies["__Secure-1PSIDTS"] = secure1psidts
53
+ }
54
+ }
55
+ for _, f := range opts {
56
+ f(c)
57
+ }
58
+ return c
59
+ }
60
+
61
+ // WithInsecureTLS sets skipping TLS verification (to mirror httpx verify=False)
62
+ func WithInsecureTLS(insecure bool) func(*GeminiClient) {
63
+ return func(c *GeminiClient) { c.insecure = insecure }
64
+ }
65
+
66
+ // WithAccountLabel sets an identifying label (e.g., token filename sans .json)
67
+ // for logging purposes.
68
+ func WithAccountLabel(label string) func(*GeminiClient) {
69
+ return func(c *GeminiClient) { c.accountLabel = label }
70
+ }
71
+
72
+ // Init initializes the access token and http client.
73
+ func (c *GeminiClient) Init(timeoutSec float64, autoClose bool, closeDelaySec float64, autoRefresh bool, refreshIntervalSec float64, verbose bool) error {
74
+ // get access token
75
+ token, validCookies, err := getAccessToken(c.Cookies, c.Proxy, verbose, c.insecure)
76
+ if err != nil {
77
+ c.Close(0)
78
+ return err
79
+ }
80
+ c.AccessToken = token
81
+ c.Cookies = validCookies
82
+
83
+ tr := &http.Transport{}
84
+ if c.Proxy != "" {
85
+ if pu, err := url.Parse(c.Proxy); err == nil {
86
+ tr.Proxy = http.ProxyURL(pu)
87
+ }
88
+ }
89
+ if c.insecure {
90
+ // set via roundtripper in utils_get_access_token for token; here we reuse via default Transport
91
+ // intentionally not adding here, as requests rely on endpoints with normal TLS
92
+ }
93
+ c.httpClient = &http.Client{Transport: tr, Timeout: time.Duration(timeoutSec * float64(time.Second))}
94
+ c.Running = true
95
+
96
+ c.Timeout = time.Duration(timeoutSec * float64(time.Second))
97
+ c.AutoClose = autoClose
98
+ c.CloseDelay = time.Duration(closeDelaySec * float64(time.Second))
99
+ if c.AutoClose {
100
+ c.resetCloseTimer()
101
+ }
102
+
103
+ c.AutoRefresh = autoRefresh
104
+ c.RefreshInterval = time.Duration(refreshIntervalSec * float64(time.Second))
105
+ if c.AutoRefresh {
106
+ c.startAutoRefresh()
107
+ }
108
+ if verbose {
109
+ Success("Gemini client initialized successfully.")
110
+ }
111
+ return nil
112
+ }
113
+
114
+ func (c *GeminiClient) Close(delaySec float64) {
115
+ if delaySec > 0 {
116
+ time.Sleep(time.Duration(delaySec * float64(time.Second)))
117
+ }
118
+ c.Running = false
119
+ c.closeMu.Lock()
120
+ if c.closeTimer != nil {
121
+ c.closeTimer.Stop()
122
+ c.closeTimer = nil
123
+ }
124
+ c.closeMu.Unlock()
125
+ // Transport/client closed by GC; nothing explicit
126
+ if c.rotateCancel != nil {
127
+ c.rotateCancel()
128
+ c.rotateCancel = nil
129
+ }
130
+ }
131
+
132
+ func (c *GeminiClient) resetCloseTimer() {
133
+ c.closeMu.Lock()
134
+ defer c.closeMu.Unlock()
135
+ if c.closeTimer != nil {
136
+ c.closeTimer.Stop()
137
+ c.closeTimer = nil
138
+ }
139
+ c.closeTimer = time.AfterFunc(c.CloseDelay, func() { c.Close(0) })
140
+ }
141
+
142
+ func (c *GeminiClient) startAutoRefresh() {
143
+ if c.rotateCancel != nil {
144
+ c.rotateCancel()
145
+ }
146
+ ctx, cancel := context.WithCancel(context.Background())
147
+ c.rotateCancel = cancel
148
+ go func() {
149
+ ticker := time.NewTicker(c.RefreshInterval)
150
+ defer ticker.Stop()
151
+ for {
152
+ select {
153
+ case <-ctx.Done():
154
+ return
155
+ case <-ticker.C:
156
+ // Step 1: rotate __Secure-1PSIDTS
157
+ newTS, err := rotate1psidts(c.Cookies, c.Proxy, c.insecure)
158
+ if err != nil {
159
+ Warning("Failed to refresh cookies. Background auto refresh canceled: %v", err)
160
+ cancel()
161
+ return
162
+ }
163
+
164
+ // Prepare a snapshot of cookies for access token refresh
165
+ nextCookies := map[string]string{}
166
+ for k, v := range c.Cookies {
167
+ nextCookies[k] = v
168
+ }
169
+ if newTS != "" {
170
+ nextCookies["__Secure-1PSIDTS"] = newTS
171
+ }
172
+
173
+ // Step 2: refresh access token using updated cookies
174
+ token, validCookies, err := getAccessToken(nextCookies, c.Proxy, false, c.insecure)
175
+ if err != nil {
176
+ // Apply rotated cookies even if token refresh fails, then retry on next tick
177
+ c.Cookies = nextCookies
178
+ Warning("Failed to refresh access token after cookie rotation: %v", err)
179
+ } else {
180
+ c.AccessToken = token
181
+ c.Cookies = validCookies
182
+ }
183
+
184
+ if c.accountLabel != "" {
185
+ DebugRaw("Cookies and token refreshed [%s]. New __Secure-1PSIDTS: %s", c.accountLabel, MaskToken28(nextCookies["__Secure-1PSIDTS"]))
186
+ } else {
187
+ DebugRaw("Cookies and token refreshed. New __Secure-1PSIDTS: %s", MaskToken28(nextCookies["__Secure-1PSIDTS"]))
188
+ }
189
+ }
190
+ }
191
+ }()
192
+ }
193
+
194
+ // ensureRunning mirrors the Python decorator behavior and retries on APIError.
195
+ func (c *GeminiClient) ensureRunning() error {
196
+ if c.Running {
197
+ return nil
198
+ }
199
+ return c.Init(float64(c.Timeout/time.Second), c.AutoClose, float64(c.CloseDelay/time.Second), c.AutoRefresh, float64(c.RefreshInterval/time.Second), false)
200
+ }
201
+
202
+ // GenerateContent sends a prompt (with optional files) and parses the response into ModelOutput.
203
+ func (c *GeminiClient) GenerateContent(prompt string, files []string, model Model, gem *Gem, chat *ChatSession) (ModelOutput, error) {
204
+ var empty ModelOutput
205
+ if prompt == "" {
206
+ return empty, &ValueError{Msg: "Prompt cannot be empty."}
207
+ }
208
+ if err := c.ensureRunning(); err != nil {
209
+ return empty, err
210
+ }
211
+ if c.AutoClose {
212
+ c.resetCloseTimer()
213
+ }
214
+
215
+ // Retry wrapper similar to decorator (retry=2)
216
+ retries := 2
217
+ for {
218
+ out, err := c.generateOnce(prompt, files, model, gem, chat)
219
+ if err == nil {
220
+ return out, nil
221
+ }
222
+ var apiErr *APIError
223
+ var imgErr *ImageGenerationError
224
+ shouldRetry := false
225
+ if errors.As(err, &imgErr) {
226
+ if retries > 1 {
227
+ retries = 1
228
+ } // only once for image generation
229
+ shouldRetry = true
230
+ } else if errors.As(err, &apiErr) {
231
+ shouldRetry = true
232
+ }
233
+ if shouldRetry && retries > 0 {
234
+ time.Sleep(time.Second)
235
+ retries--
236
+ continue
237
+ }
238
+ return empty, err
239
+ }
240
+ }
241
+
242
+ func (c *GeminiClient) generateOnce(prompt string, files []string, model Model, gem *Gem, chat *ChatSession) (ModelOutput, error) {
243
+ var empty ModelOutput
244
+ // Build f.req
245
+ var uploaded [][]any
246
+ for _, fp := range files {
247
+ id, err := uploadFile(fp, c.Proxy, c.insecure)
248
+ if err != nil {
249
+ return empty, err
250
+ }
251
+ name, err := parseFileName(fp)
252
+ if err != nil {
253
+ return empty, err
254
+ }
255
+ uploaded = append(uploaded, []any{[]any{id}, name})
256
+ }
257
+ var item0 any
258
+ if len(uploaded) > 0 {
259
+ item0 = []any{prompt, 0, nil, uploaded}
260
+ } else {
261
+ item0 = []any{prompt}
262
+ }
263
+ var item2 any = nil
264
+ if chat != nil {
265
+ item2 = chat.Metadata()
266
+ }
267
+
268
+ inner := []any{item0, nil, item2}
269
+ if gem != nil {
270
+ // pad with 16 nils then gem ID
271
+ for i := 0; i < 16; i++ {
272
+ inner = append(inner, nil)
273
+ }
274
+ inner = append(inner, gem.ID)
275
+ }
276
+ innerJSON, _ := json.Marshal(inner)
277
+ outer := []any{nil, string(innerJSON)}
278
+ outerJSON, _ := json.Marshal(outer)
279
+
280
+ // form
281
+ form := url.Values{}
282
+ form.Set("at", c.AccessToken)
283
+ form.Set("f.req", string(outerJSON))
284
+
285
+ req, _ := http.NewRequest(http.MethodPost, EndpointGenerate, strings.NewReader(form.Encode()))
286
+ // headers
287
+ for k, v := range HeadersGemini {
288
+ for _, vv := range v {
289
+ req.Header.Add(k, vv)
290
+ }
291
+ }
292
+ for k, v := range model.ModelHeader {
293
+ for _, vv := range v {
294
+ req.Header.Add(k, vv)
295
+ }
296
+ }
297
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
298
+ for k, v := range c.Cookies {
299
+ req.AddCookie(&http.Cookie{Name: k, Value: v})
300
+ }
301
+
302
+ resp, err := c.httpClient.Do(req)
303
+ if err != nil {
304
+ return empty, &TimeoutError{GeminiError{Msg: "Generate content request timed out."}}
305
+ }
306
+ defer resp.Body.Close()
307
+
308
+ if resp.StatusCode == 429 {
309
+ // Surface 429 as TemporarilyBlocked to match Python behavior
310
+ c.Close(0)
311
+ return empty, &TemporarilyBlocked{GeminiError{Msg: "Too many requests. IP temporarily blocked."}}
312
+ }
313
+ if resp.StatusCode != 200 {
314
+ c.Close(0)
315
+ return empty, &APIError{Msg: fmt.Sprintf("Failed to generate contents. Status %d", resp.StatusCode)}
316
+ }
317
+
318
+ // Read body and split lines; take the 3rd line (index 2)
319
+ b, _ := io.ReadAll(resp.Body)
320
+ parts := strings.Split(string(b), "\n")
321
+ if len(parts) < 3 {
322
+ c.Close(0)
323
+ return empty, &APIError{Msg: "Invalid response data received."}
324
+ }
325
+ var responseJSON []any
326
+ if err := json.Unmarshal([]byte(parts[2]), &responseJSON); err != nil {
327
+ c.Close(0)
328
+ return empty, &APIError{Msg: "Invalid response data received."}
329
+ }
330
+
331
+ // find body where main_part[4] exists
332
+ var (
333
+ body any
334
+ bodyIndex int
335
+ )
336
+ for i, p := range responseJSON {
337
+ arr, ok := p.([]any)
338
+ if !ok || len(arr) < 3 {
339
+ continue
340
+ }
341
+ s, ok := arr[2].(string)
342
+ if !ok {
343
+ continue
344
+ }
345
+ var mainPart []any
346
+ if err := json.Unmarshal([]byte(s), &mainPart); err != nil {
347
+ continue
348
+ }
349
+ if len(mainPart) > 4 && mainPart[4] != nil {
350
+ body = mainPart
351
+ bodyIndex = i
352
+ break
353
+ }
354
+ }
355
+ if body == nil {
356
+ // Fallback: scan subsequent lines to locate a data frame with a non-empty body (mainPart[4]).
357
+ var lastTop []any
358
+ for li := 3; li < len(parts) && body == nil; li++ {
359
+ line := strings.TrimSpace(parts[li])
360
+ if line == "" {
361
+ continue
362
+ }
363
+ var top []any
364
+ if err := json.Unmarshal([]byte(line), &top); err != nil {
365
+ continue
366
+ }
367
+ lastTop = top
368
+ for i, p := range top {
369
+ arr, ok := p.([]any)
370
+ if !ok || len(arr) < 3 {
371
+ continue
372
+ }
373
+ s, ok := arr[2].(string)
374
+ if !ok {
375
+ continue
376
+ }
377
+ var mainPart []any
378
+ if err := json.Unmarshal([]byte(s), &mainPart); err != nil {
379
+ continue
380
+ }
381
+ if len(mainPart) > 4 && mainPart[4] != nil {
382
+ body = mainPart
383
+ bodyIndex = i
384
+ responseJSON = top
385
+ break
386
+ }
387
+ }
388
+ }
389
+ // Parse nested error code to align with Python mapping
390
+ var top []any
391
+ // Prefer lastTop from fallback scan; otherwise try parts[2]
392
+ if len(lastTop) > 0 {
393
+ top = lastTop
394
+ } else {
395
+ _ = json.Unmarshal([]byte(parts[2]), &top)
396
+ }
397
+ if len(top) > 0 {
398
+ if code, ok := extractErrorCode(top); ok {
399
+ switch code {
400
+ case ErrorUsageLimitExceeded:
401
+ return empty, &UsageLimitExceeded{GeminiError{Msg: fmt.Sprintf("Failed to generate contents. Usage limit of %s has exceeded. Please try switching to another model.", model.Name)}}
402
+ case ErrorModelInconsistent:
403
+ return empty, &ModelInvalid{GeminiError{Msg: "Selected model is inconsistent or unavailable."}}
404
+ case ErrorModelHeaderInvalid:
405
+ return empty, &APIError{Msg: "Invalid model header string. Please update the selected model header."}
406
+ case ErrorIPTemporarilyBlocked:
407
+ return empty, &TemporarilyBlocked{GeminiError{Msg: "Too many requests. IP temporarily blocked."}}
408
+ }
409
+ }
410
+ }
411
+ // Debug("Invalid response: control frames only; no body found")
412
+ // Close the client to force re-initialization on next request (parity with Python client behavior)
413
+ c.Close(0)
414
+ return empty, &APIError{Msg: "Failed to generate contents. Invalid response data received."}
415
+ }
416
+
417
+ bodyArr := body.([]any)
418
+ // metadata
419
+ var metadata []string
420
+ if len(bodyArr) > 1 {
421
+ if metaArr, ok := bodyArr[1].([]any); ok {
422
+ for _, v := range metaArr {
423
+ if s, ok := v.(string); ok {
424
+ metadata = append(metadata, s)
425
+ }
426
+ }
427
+ }
428
+ }
429
+
430
+ // candidates parsing
431
+ candContainer, ok := bodyArr[4].([]any)
432
+ if !ok {
433
+ return empty, &APIError{Msg: "Failed to parse response body."}
434
+ }
435
+ candidates := make([]Candidate, 0, len(candContainer))
436
+ reCard := regexp.MustCompile(`^http://googleusercontent\.com/card_content/\d+`)
437
+ reGen := regexp.MustCompile(`http://googleusercontent\.com/image_generation_content/\d+`)
438
+
439
+ for ci, candAny := range candContainer {
440
+ cArr, ok := candAny.([]any)
441
+ if !ok {
442
+ continue
443
+ }
444
+ // text: cArr[1][0]
445
+ var text string
446
+ if len(cArr) > 1 {
447
+ if sArr, ok := cArr[1].([]any); ok && len(sArr) > 0 {
448
+ text, _ = sArr[0].(string)
449
+ }
450
+ }
451
+ if reCard.MatchString(text) {
452
+ // candidate[22] and candidate[22][0] or text
453
+ if len(cArr) > 22 {
454
+ if arr, ok := cArr[22].([]any); ok && len(arr) > 0 {
455
+ if s, ok := arr[0].(string); ok {
456
+ text = s
457
+ }
458
+ }
459
+ }
460
+ }
461
+
462
+ // thoughts: candidate[37][0][0]
463
+ var thoughts *string
464
+ if len(cArr) > 37 {
465
+ if a, ok := cArr[37].([]any); ok && len(a) > 0 {
466
+ if b, ok := a[0].([]any); ok && len(b) > 0 {
467
+ if s, ok := b[0].(string); ok {
468
+ ss := decodeHTML(s)
469
+ thoughts = &ss
470
+ }
471
+ }
472
+ }
473
+ }
474
+
475
+ // web images: candidate[12][1]
476
+ webImages := []WebImage{}
477
+ var imgSection any
478
+ if len(cArr) > 12 {
479
+ imgSection = cArr[12]
480
+ }
481
+ if arr, ok := imgSection.([]any); ok && len(arr) > 1 {
482
+ if imagesArr, ok := arr[1].([]any); ok {
483
+ for _, wiAny := range imagesArr {
484
+ wiArr, ok := wiAny.([]any)
485
+ if !ok {
486
+ continue
487
+ }
488
+ // url: wiArr[0][0][0], title: wiArr[7][0], alt: wiArr[0][4]
489
+ var urlStr, title, alt string
490
+ if len(wiArr) > 0 {
491
+ if a, ok := wiArr[0].([]any); ok && len(a) > 0 {
492
+ if b, ok := a[0].([]any); ok && len(b) > 0 {
493
+ urlStr, _ = b[0].(string)
494
+ }
495
+ if len(a) > 4 {
496
+ if s, ok := a[4].(string); ok {
497
+ alt = s
498
+ }
499
+ }
500
+ }
501
+ }
502
+ if len(wiArr) > 7 {
503
+ if a, ok := wiArr[7].([]any); ok && len(a) > 0 {
504
+ title, _ = a[0].(string)
505
+ }
506
+ }
507
+ webImages = append(webImages, WebImage{Image: Image{URL: urlStr, Title: title, Alt: alt, Proxy: c.Proxy}})
508
+ }
509
+ }
510
+ }
511
+
512
+ // generated images
513
+ genImages := []GeneratedImage{}
514
+ hasGen := false
515
+ if arr, ok := imgSection.([]any); ok && len(arr) > 7 {
516
+ if a, ok := arr[7].([]any); ok && len(a) > 0 && a[0] != nil {
517
+ hasGen = true
518
+ }
519
+ }
520
+ if hasGen {
521
+ // find img part
522
+ var imgBody []any
523
+ for pi := bodyIndex; pi < len(responseJSON); pi++ {
524
+ part := responseJSON[pi]
525
+ arr, ok := part.([]any)
526
+ if !ok || len(arr) < 3 {
527
+ continue
528
+ }
529
+ s, ok := arr[2].(string)
530
+ if !ok {
531
+ continue
532
+ }
533
+ var mp []any
534
+ if err := json.Unmarshal([]byte(s), &mp); err != nil {
535
+ continue
536
+ }
537
+ if len(mp) > 4 {
538
+ if tt, ok := mp[4].([]any); ok && len(tt) > ci {
539
+ if sec, ok := tt[ci].([]any); ok && len(sec) > 12 {
540
+ if ss, ok := sec[12].([]any); ok && len(ss) > 7 {
541
+ if first, ok := ss[7].([]any); ok && len(first) > 0 && first[0] != nil {
542
+ imgBody = mp
543
+ break
544
+ }
545
+ }
546
+ }
547
+ }
548
+ }
549
+ }
550
+ if imgBody == nil {
551
+ return empty, &ImageGenerationError{APIError{Msg: "Failed to parse generated images."}}
552
+ }
553
+ imgCand := imgBody[4].([]any)[ci].([]any)
554
+ if len(imgCand) > 1 {
555
+ if a, ok := imgCand[1].([]any); ok && len(a) > 0 {
556
+ if s, ok := a[0].(string); ok {
557
+ text = strings.TrimSpace(reGen.ReplaceAllString(s, ""))
558
+ }
559
+ }
560
+ }
561
+ // images list at imgCand[12][7][0]
562
+ if len(imgCand) > 12 {
563
+ if s1, ok := imgCand[12].([]any); ok && len(s1) > 7 {
564
+ if s2, ok := s1[7].([]any); ok && len(s2) > 0 {
565
+ if s3, ok := s2[0].([]any); ok {
566
+ for ii, giAny := range s3 {
567
+ ga, ok := giAny.([]any)
568
+ if !ok || len(ga) < 4 {
569
+ continue
570
+ }
571
+ // url: ga[0][3][3]
572
+ var urlStr, title, alt string
573
+ if a, ok := ga[0].([]any); ok && len(a) > 3 {
574
+ if b, ok := a[3].([]any); ok && len(b) > 3 {
575
+ urlStr, _ = b[3].(string)
576
+ }
577
+ }
578
+ // title from ga[3][6]
579
+ if len(ga) > 3 {
580
+ if a, ok := ga[3].([]any); ok {
581
+ if len(a) > 6 {
582
+ if v, ok := a[6].(float64); ok && v != 0 {
583
+ title = fmt.Sprintf("[Generated Image %.0f]", v)
584
+ } else {
585
+ title = "[Generated Image]"
586
+ }
587
+ } else {
588
+ title = "[Generated Image]"
589
+ }
590
+ // alt from ga[3][5][ii] fallback
591
+ if len(a) > 5 {
592
+ if tt, ok := a[5].([]any); ok {
593
+ if ii < len(tt) {
594
+ if s, ok := tt[ii].(string); ok {
595
+ alt = s
596
+ }
597
+ } else if len(tt) > 0 {
598
+ if s, ok := tt[0].(string); ok {
599
+ alt = s
600
+ }
601
+ }
602
+ }
603
+ }
604
+ }
605
+ }
606
+ genImages = append(genImages, GeneratedImage{Image: Image{URL: urlStr, Title: title, Alt: alt, Proxy: c.Proxy}, Cookies: c.Cookies})
607
+ }
608
+ }
609
+ }
610
+ }
611
+ }
612
+ }
613
+
614
+ cand := Candidate{
615
+ RCID: fmt.Sprintf("%v", cArr[0]),
616
+ Text: decodeHTML(text),
617
+ Thoughts: thoughts,
618
+ WebImages: webImages,
619
+ GeneratedImages: genImages,
620
+ }
621
+ candidates = append(candidates, cand)
622
+ }
623
+
624
+ if len(candidates) == 0 {
625
+ return empty, &GeminiError{Msg: "Failed to generate contents. No output data found in response."}
626
+ }
627
+ output := ModelOutput{Metadata: metadata, Candidates: candidates, Chosen: 0}
628
+ if chat != nil {
629
+ chat.lastOutput = &output
630
+ }
631
+ return output, nil
632
+ }
633
+
634
+ // extractErrorCode attempts to navigate the known nested error structure and fetch the integer code.
635
+ // Mirrors Python path: response_json[0][5][2][0][1][0]
636
+ func extractErrorCode(top []any) (int, bool) {
637
+ if len(top) == 0 {
638
+ return 0, false
639
+ }
640
+ a, ok := top[0].([]any)
641
+ if !ok || len(a) <= 5 {
642
+ return 0, false
643
+ }
644
+ b, ok := a[5].([]any)
645
+ if !ok || len(b) <= 2 {
646
+ return 0, false
647
+ }
648
+ c, ok := b[2].([]any)
649
+ if !ok || len(c) == 0 {
650
+ return 0, false
651
+ }
652
+ d, ok := c[0].([]any)
653
+ if !ok || len(d) <= 1 {
654
+ return 0, false
655
+ }
656
+ e, ok := d[1].([]any)
657
+ if !ok || len(e) == 0 {
658
+ return 0, false
659
+ }
660
+ f, ok := e[0].(float64)
661
+ if !ok {
662
+ return 0, false
663
+ }
664
+ return int(f), true
665
+ }
666
+
667
+ // truncateForLog returns a shortened string for logging
668
+ func truncateForLog(s string, n int) string {
669
+ if n <= 0 || len(s) <= n {
670
+ return s
671
+ }
672
+ return s[:n]
673
+ }
674
+
675
+ // StartChat returns a ChatSession attached to the client
676
+ func (c *GeminiClient) StartChat(model Model, gem *Gem, metadata []string) *ChatSession {
677
+ return &ChatSession{client: c, metadata: normalizeMeta(metadata), model: model, gem: gem}
678
+ }
679
+
680
+ // ChatSession holds conversation metadata
681
+ type ChatSession struct {
682
+ client *GeminiClient
683
+ metadata []string // cid, rid, rcid
684
+ lastOutput *ModelOutput
685
+ model Model
686
+ gem *Gem
687
+ }
688
+
689
+ func (cs *ChatSession) String() string {
690
+ var cid, rid, rcid string
691
+ if len(cs.metadata) > 0 {
692
+ cid = cs.metadata[0]
693
+ }
694
+ if len(cs.metadata) > 1 {
695
+ rid = cs.metadata[1]
696
+ }
697
+ if len(cs.metadata) > 2 {
698
+ rcid = cs.metadata[2]
699
+ }
700
+ return fmt.Sprintf("ChatSession(cid='%s', rid='%s', rcid='%s')", cid, rid, rcid)
701
+ }
702
+
703
+ func normalizeMeta(v []string) []string {
704
+ out := []string{"", "", ""}
705
+ for i := 0; i < len(v) && i < 3; i++ {
706
+ out[i] = v[i]
707
+ }
708
+ return out
709
+ }
710
+
711
+ func (cs *ChatSession) Metadata() []string { return cs.metadata }
712
+ func (cs *ChatSession) SetMetadata(v []string) { cs.metadata = normalizeMeta(v) }
713
+ func (cs *ChatSession) CID() string {
714
+ if len(cs.metadata) > 0 {
715
+ return cs.metadata[0]
716
+ }
717
+ return ""
718
+ }
719
+ func (cs *ChatSession) RID() string {
720
+ if len(cs.metadata) > 1 {
721
+ return cs.metadata[1]
722
+ }
723
+ return ""
724
+ }
725
+ func (cs *ChatSession) RCID() string {
726
+ if len(cs.metadata) > 2 {
727
+ return cs.metadata[2]
728
+ }
729
+ return ""
730
+ }
731
+ func (cs *ChatSession) setCID(v string) {
732
+ if len(cs.metadata) < 1 {
733
+ cs.metadata = normalizeMeta(cs.metadata)
734
+ }
735
+ cs.metadata[0] = v
736
+ }
737
+ func (cs *ChatSession) setRID(v string) {
738
+ if len(cs.metadata) < 2 {
739
+ cs.metadata = normalizeMeta(cs.metadata)
740
+ }
741
+ cs.metadata[1] = v
742
+ }
743
+ func (cs *ChatSession) setRCID(v string) {
744
+ if len(cs.metadata) < 3 {
745
+ cs.metadata = normalizeMeta(cs.metadata)
746
+ }
747
+ cs.metadata[2] = v
748
+ }
749
+
750
+ // SendMessage shortcut to client's GenerateContent
751
+ func (cs *ChatSession) SendMessage(prompt string, files []string) (ModelOutput, error) {
752
+ out, err := cs.client.GenerateContent(prompt, files, cs.model, cs.gem, cs)
753
+ if err == nil {
754
+ cs.lastOutput = &out
755
+ cs.SetMetadata(out.Metadata)
756
+ cs.setRCID(out.RCID())
757
+ }
758
+ return out, err
759
+ }
760
+
761
+ // ChooseCandidate selects a candidate from last output and updates rcid
762
+ func (cs *ChatSession) ChooseCandidate(index int) (ModelOutput, error) {
763
+ if cs.lastOutput == nil {
764
+ return ModelOutput{}, &ValueError{Msg: "No previous output data found in this chat session."}
765
+ }
766
+ if index >= len(cs.lastOutput.Candidates) {
767
+ return ModelOutput{}, &ValueError{Msg: fmt.Sprintf("Index %d exceeds candidates", index)}
768
+ }
769
+ cs.lastOutput.Chosen = index
770
+ cs.setRCID(cs.lastOutput.RCID())
771
+ return *cs.lastOutput, nil
772
+ }
internal/client/gemini-web/convert_ext.go ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package geminiwebapi
2
+
3
+ import (
4
+ "encoding/json"
5
+ "fmt"
6
+ "math"
7
+ "regexp"
8
+ "strings"
9
+ "time"
10
+ "unicode/utf8"
11
+ )
12
+
13
+ var (
14
+ reGoogle = regexp.MustCompile("(\\()?\\[`([^`]+?)`\\]\\(https://www\\.google\\.com/search\\?q=[^)]*\\)(\\))?")
15
+ reColonNum = regexp.MustCompile(`([^:]+:\d+)`)
16
+ reInline = regexp.MustCompile("`(\\[[^\\]]+\\]\\([^\\)]+\\))`")
17
+ )
18
+
19
+ func unescapeGeminiText(s string) string {
20
+ if s == "" {
21
+ return s
22
+ }
23
+ s = strings.ReplaceAll(s, "&lt;", "<")
24
+ s = strings.ReplaceAll(s, "\\<", "<")
25
+ s = strings.ReplaceAll(s, "\\_", "_")
26
+ s = strings.ReplaceAll(s, "\\>", ">")
27
+ return s
28
+ }
29
+
30
+ func postProcessModelText(text string) string {
31
+ text = reGoogle.ReplaceAllStringFunc(text, func(m string) string {
32
+ subs := reGoogle.FindStringSubmatch(m)
33
+ if len(subs) < 4 {
34
+ return m
35
+ }
36
+ outerOpen := subs[1]
37
+ display := subs[2]
38
+ target := display
39
+ if loc := reColonNum.FindString(display); loc != "" {
40
+ target = loc
41
+ }
42
+ newSeg := "[`" + display + "`](" + target + ")"
43
+ if outerOpen != "" {
44
+ return "(" + newSeg + ")"
45
+ }
46
+ return newSeg
47
+ })
48
+ text = reInline.ReplaceAllString(text, "$1")
49
+ return text
50
+ }
51
+
52
+ func estimateTokens(s string) int {
53
+ if s == "" {
54
+ return 0
55
+ }
56
+ rc := float64(utf8.RuneCountInString(s))
57
+ if rc <= 0 {
58
+ return 0
59
+ }
60
+ est := int(math.Ceil(rc / 4.0))
61
+ if est < 0 {
62
+ return 0
63
+ }
64
+ return est
65
+ }
66
+
67
+ // ConvertOutputToGemini converts simplified ModelOutput to Gemini API-like JSON.
68
+ // promptText is used only to estimate usage tokens to populate usage fields.
69
+ func ConvertOutputToGemini(output *ModelOutput, modelName string, promptText string) ([]byte, error) {
70
+ if output == nil || len(output.Candidates) == 0 {
71
+ return nil, fmt.Errorf("empty output")
72
+ }
73
+
74
+ parts := make([]map[string]any, 0, 2)
75
+
76
+ var thoughtsText string
77
+ if output.Candidates[0].Thoughts != nil {
78
+ if t := strings.TrimSpace(*output.Candidates[0].Thoughts); t != "" {
79
+ thoughtsText = unescapeGeminiText(t)
80
+ parts = append(parts, map[string]any{
81
+ "text": thoughtsText,
82
+ "thought": true,
83
+ })
84
+ }
85
+ }
86
+
87
+ visible := unescapeGeminiText(output.Candidates[0].Text)
88
+ finalText := postProcessModelText(visible)
89
+ if finalText != "" {
90
+ parts = append(parts, map[string]any{"text": finalText})
91
+ }
92
+
93
+ if imgs := output.Candidates[0].GeneratedImages; len(imgs) > 0 {
94
+ for _, gi := range imgs {
95
+ if mime, data, err := FetchGeneratedImageData(gi); err == nil && data != "" {
96
+ parts = append(parts, map[string]any{
97
+ "inlineData": map[string]any{
98
+ "mimeType": mime,
99
+ "data": data,
100
+ },
101
+ })
102
+ }
103
+ }
104
+ }
105
+
106
+ promptTokens := estimateTokens(promptText)
107
+ completionTokens := estimateTokens(finalText)
108
+ thoughtsTokens := 0
109
+ if thoughtsText != "" {
110
+ thoughtsTokens = estimateTokens(thoughtsText)
111
+ }
112
+ totalTokens := promptTokens + completionTokens
113
+
114
+ now := time.Now()
115
+ resp := map[string]any{
116
+ "candidates": []any{
117
+ map[string]any{
118
+ "content": map[string]any{
119
+ "parts": parts,
120
+ "role": "model",
121
+ },
122
+ "finishReason": "stop",
123
+ "index": 0,
124
+ },
125
+ },
126
+ "createTime": now.Format(time.RFC3339Nano),
127
+ "responseId": fmt.Sprintf("gemini-web-%d", now.UnixNano()),
128
+ "modelVersion": modelName,
129
+ "usageMetadata": map[string]any{
130
+ "promptTokenCount": promptTokens,
131
+ "candidatesTokenCount": completionTokens,
132
+ "thoughtsTokenCount": thoughtsTokens,
133
+ "totalTokenCount": totalTokens,
134
+ },
135
+ }
136
+ b, err := json.Marshal(resp)
137
+ if err != nil {
138
+ return nil, fmt.Errorf("failed to marshal gemini response: %w", err)
139
+ }
140
+ return b, nil
141
+ }
internal/client/gemini-web/errors.go ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package geminiwebapi
2
+
3
+ type AuthError struct{ Msg string }
4
+
5
+ func (e *AuthError) Error() string {
6
+ if e.Msg == "" {
7
+ return "authentication error"
8
+ }
9
+ return e.Msg
10
+ }
11
+
12
+ type APIError struct{ Msg string }
13
+
14
+ func (e *APIError) Error() string {
15
+ if e.Msg == "" {
16
+ return "api error"
17
+ }
18
+ return e.Msg
19
+ }
20
+
21
+ type ImageGenerationError struct{ APIError }
22
+
23
+ type GeminiError struct{ Msg string }
24
+
25
+ func (e *GeminiError) Error() string {
26
+ if e.Msg == "" {
27
+ return "gemini error"
28
+ }
29
+ return e.Msg
30
+ }
31
+
32
+ type TimeoutError struct{ GeminiError }
33
+
34
+ type UsageLimitExceeded struct{ GeminiError }
35
+
36
+ type ModelInvalid struct{ GeminiError }
37
+
38
+ type TemporarilyBlocked struct{ GeminiError }
39
+
40
+ type ValueError struct{ Msg string }
41
+
42
+ func (e *ValueError) Error() string {
43
+ if e.Msg == "" {
44
+ return "value error"
45
+ }
46
+ return e.Msg
47
+ }
internal/client/gemini-web/logging.go ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package geminiwebapi
2
+
3
+ import (
4
+ "fmt"
5
+ "os"
6
+ "strings"
7
+
8
+ log "github.com/sirupsen/logrus"
9
+ )
10
+
11
+ // init honors GEMINI_WEBAPI_LOG to keep parity with the Python client.
12
+ func init() {
13
+ if lvl := os.Getenv("GEMINI_WEBAPI_LOG"); lvl != "" {
14
+ SetLogLevel(lvl)
15
+ }
16
+ }
17
+
18
+ // SetLogLevel adjusts logging verbosity using CLI-style strings.
19
+ func SetLogLevel(level string) {
20
+ switch strings.ToUpper(level) {
21
+ case "TRACE":
22
+ log.SetLevel(log.TraceLevel)
23
+ case "DEBUG":
24
+ log.SetLevel(log.DebugLevel)
25
+ case "INFO":
26
+ log.SetLevel(log.InfoLevel)
27
+ case "WARNING", "WARN":
28
+ log.SetLevel(log.WarnLevel)
29
+ case "ERROR":
30
+ log.SetLevel(log.ErrorLevel)
31
+ case "CRITICAL", "FATAL":
32
+ log.SetLevel(log.FatalLevel)
33
+ default:
34
+ log.SetLevel(log.InfoLevel)
35
+ }
36
+ }
37
+
38
+ func prefix(format string) string { return "[gemini_webapi] " + format }
39
+
40
+ func Debug(format string, v ...any) { log.Debugf(prefix(format), v...) }
41
+
42
+ // DebugRaw logs without the module prefix; use sparingly for messages
43
+ // that should integrate with global formatting without extra tags.
44
+ func DebugRaw(format string, v ...any) { log.Debugf(format, v...) }
45
+ func Info(format string, v ...any) { log.Infof(prefix(format), v...) }
46
+ func Warning(format string, v ...any) { log.Warnf(prefix(format), v...) }
47
+ func Error(format string, v ...any) { log.Errorf(prefix(format), v...) }
48
+ func Success(format string, v ...any) { log.Infof(prefix("SUCCESS "+format), v...) }
49
+
50
+ // MaskToken hides the middle part of a sensitive value with '*'.
51
+ // It keeps up to left and right edge characters for readability.
52
+ // If input is very short, it returns a fully masked string of the same length.
53
+ func MaskToken(s string) string {
54
+ n := len(s)
55
+ if n == 0 {
56
+ return ""
57
+ }
58
+ if n <= 6 {
59
+ return strings.Repeat("*", n)
60
+ }
61
+ // Keep up to 6 chars on the left and 4 on the right, but never exceed available length
62
+ left := 6
63
+ if left > n-4 {
64
+ left = n - 4
65
+ }
66
+ right := 4
67
+ if right > n-left {
68
+ right = n - left
69
+ }
70
+ if left < 0 {
71
+ left = 0
72
+ }
73
+ if right < 0 {
74
+ right = 0
75
+ }
76
+ middle := n - left - right
77
+ if middle < 0 {
78
+ middle = 0
79
+ }
80
+ return s[:left] + strings.Repeat("*", middle) + s[n-right:]
81
+ }
82
+
83
+ // MaskToken28 returns a fixed-length (28) masked representation showing:
84
+ // first 8 chars + 8 asterisks + 4 middle chars + last 8 chars.
85
+ // If the input is shorter than 20 characters, it returns a fully masked string
86
+ // of length min(len(s), 28).
87
+ func MaskToken28(s string) string {
88
+ n := len(s)
89
+ if n == 0 {
90
+ return ""
91
+ }
92
+ if n < 20 {
93
+ // Too short to safely reveal; mask entirely but cap to 28
94
+ if n > 28 {
95
+ n = 28
96
+ }
97
+ return strings.Repeat("*", n)
98
+ }
99
+ // Pick 4 middle characters around the center
100
+ midStart := n/2 - 2
101
+ if midStart < 8 {
102
+ midStart = 8
103
+ }
104
+ if midStart+4 > n-8 {
105
+ midStart = n - 8 - 4
106
+ if midStart < 8 {
107
+ midStart = 8
108
+ }
109
+ }
110
+ prefix := s[:8]
111
+ middle := s[midStart : midStart+4]
112
+ suffix := s[n-8:]
113
+ return prefix + strings.Repeat("*", 4) + middle + strings.Repeat("*", 4) + suffix
114
+ }
115
+
116
+ // BuildUpstreamRequestLog builds a compact preview string for upstream request logging.
117
+ func BuildUpstreamRequestLog(account string, contextOn bool, useTags, explicitContext bool, prompt string, filesCount int, reuse bool, metaLen int, gem *Gem) string {
118
+ var sb strings.Builder
119
+ sb.WriteString("\n\n=== GEMINI WEB UPSTREAM ===\n")
120
+ sb.WriteString(fmt.Sprintf("account: %s\n", account))
121
+ if contextOn {
122
+ sb.WriteString("context_mode: on\n")
123
+ } else {
124
+ sb.WriteString("context_mode: off\n")
125
+ }
126
+ if reuse {
127
+ sb.WriteString("reuseIdx: 1\n")
128
+ } else {
129
+ sb.WriteString("reuseIdx: 0\n")
130
+ }
131
+ sb.WriteString(fmt.Sprintf("useTags: %t\n", useTags))
132
+ sb.WriteString(fmt.Sprintf("metadata_len: %d\n", metaLen))
133
+ if explicitContext {
134
+ sb.WriteString("explicit_context: true\n")
135
+ } else {
136
+ sb.WriteString("explicit_context: false\n")
137
+ }
138
+ if filesCount > 0 {
139
+ sb.WriteString(fmt.Sprintf("files: %d\n", filesCount))
140
+ }
141
+
142
+ if gem != nil {
143
+ sb.WriteString("gem:\n")
144
+ if gem.ID != "" {
145
+ sb.WriteString(fmt.Sprintf(" id: %s\n", gem.ID))
146
+ }
147
+ if gem.Name != "" {
148
+ sb.WriteString(fmt.Sprintf(" name: %s\n", gem.Name))
149
+ }
150
+ sb.WriteString(fmt.Sprintf(" predefined: %t\n", gem.Predefined))
151
+ } else {
152
+ sb.WriteString("gem: none\n")
153
+ }
154
+
155
+ chunks := ChunkByRunes(prompt, 4096)
156
+ preview := prompt
157
+ truncated := false
158
+ if len(chunks) > 1 {
159
+ preview = chunks[0]
160
+ truncated = true
161
+ }
162
+ sb.WriteString("prompt_preview:\n")
163
+ sb.WriteString(preview)
164
+ if truncated {
165
+ sb.WriteString("\n... [truncated]\n")
166
+ }
167
+ return sb.String()
168
+ }
internal/client/gemini-web/media.go ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package geminiwebapi
2
+
3
+ import (
4
+ "bytes"
5
+ "crypto/tls"
6
+ "encoding/base64"
7
+ "errors"
8
+ "fmt"
9
+ "io"
10
+ "mime/multipart"
11
+ "net/http"
12
+ "net/http/cookiejar"
13
+ "net/url"
14
+ "os"
15
+ "path/filepath"
16
+ "regexp"
17
+ "sort"
18
+ "strings"
19
+ "time"
20
+
21
+ "github.com/luispater/CLIProxyAPI/v5/internal/interfaces"
22
+ misc "github.com/luispater/CLIProxyAPI/v5/internal/misc"
23
+ "github.com/tidwall/gjson"
24
+ )
25
+
26
+ // Image helpers ------------------------------------------------------------
27
+
28
+ type Image struct {
29
+ URL string
30
+ Title string
31
+ Alt string
32
+ Proxy string
33
+ }
34
+
35
+ func (i Image) String() string {
36
+ short := i.URL
37
+ if len(short) > 20 {
38
+ short = short[:8] + "..." + short[len(short)-12:]
39
+ }
40
+ return fmt.Sprintf("Image(title='%s', alt='%s', url='%s')", i.Title, i.Alt, short)
41
+ }
42
+
43
+ func (i Image) Save(path string, filename string, cookies map[string]string, verbose bool, skipInvalidFilename bool, insecure bool) (string, error) {
44
+ if filename == "" {
45
+ // Try to parse filename from URL.
46
+ u := i.URL
47
+ if p := strings.Split(u, "/"); len(p) > 0 {
48
+ filename = p[len(p)-1]
49
+ }
50
+ if q := strings.Split(filename, "?"); len(q) > 0 {
51
+ filename = q[0]
52
+ }
53
+ }
54
+ // Regex validation (align with Python: ^(.*\.\w+)) to extract name with extension.
55
+ if filename != "" {
56
+ re := regexp.MustCompile(`^(.*\.\w+)`)
57
+ if m := re.FindStringSubmatch(filename); len(m) >= 2 {
58
+ filename = m[1]
59
+ } else {
60
+ if verbose {
61
+ Warning("Invalid filename: %s", filename)
62
+ }
63
+ if skipInvalidFilename {
64
+ return "", nil
65
+ }
66
+ }
67
+ }
68
+ // Build client with cookie jar so cookies persist across redirects.
69
+ tr := &http.Transport{}
70
+ if i.Proxy != "" {
71
+ if pu, err := url.Parse(i.Proxy); err == nil {
72
+ tr.Proxy = http.ProxyURL(pu)
73
+ }
74
+ }
75
+ if insecure {
76
+ tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
77
+ }
78
+ jar, _ := cookiejar.New(nil)
79
+ client := &http.Client{Transport: tr, Timeout: 120 * time.Second, Jar: jar}
80
+
81
+ // Helper to set raw Cookie header using provided cookies (to mirror Python client behavior).
82
+ buildCookieHeader := func(m map[string]string) string {
83
+ if len(m) == 0 {
84
+ return ""
85
+ }
86
+ keys := make([]string, 0, len(m))
87
+ for k := range m {
88
+ keys = append(keys, k)
89
+ }
90
+ sort.Strings(keys)
91
+ parts := make([]string, 0, len(keys))
92
+ for _, k := range keys {
93
+ parts = append(parts, fmt.Sprintf("%s=%s", k, m[k]))
94
+ }
95
+ return strings.Join(parts, "; ")
96
+ }
97
+ rawCookie := buildCookieHeader(cookies)
98
+
99
+ client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
100
+ // Ensure provided cookies are always sent across redirects (domain-agnostic).
101
+ if rawCookie != "" {
102
+ req.Header.Set("Cookie", rawCookie)
103
+ }
104
+ if len(via) >= 10 {
105
+ return errors.New("stopped after 10 redirects")
106
+ }
107
+ return nil
108
+ }
109
+
110
+ req, _ := http.NewRequest(http.MethodGet, i.URL, nil)
111
+ if rawCookie != "" {
112
+ req.Header.Set("Cookie", rawCookie)
113
+ }
114
+ // Add browser-like headers to improve compatibility.
115
+ req.Header.Set("Accept", "image/avif,image/webp,image/apng,image/*,*/*;q=0.8")
116
+ req.Header.Set("Connection", "keep-alive")
117
+ resp, err := client.Do(req)
118
+ if err != nil {
119
+ return "", err
120
+ }
121
+ defer resp.Body.Close()
122
+ if resp.StatusCode != http.StatusOK {
123
+ return "", fmt.Errorf("Error downloading image: %d %s", resp.StatusCode, resp.Status)
124
+ }
125
+ if ct := resp.Header.Get("Content-Type"); ct != "" && !strings.Contains(strings.ToLower(ct), "image") {
126
+ Warning("Content type of %s is not image, but %s.", filename, ct)
127
+ }
128
+ if path == "" {
129
+ path = "temp"
130
+ }
131
+ if err := os.MkdirAll(path, 0o755); err != nil {
132
+ return "", err
133
+ }
134
+ dest := filepath.Join(path, filename)
135
+ f, err := os.Create(dest)
136
+ if err != nil {
137
+ return "", err
138
+ }
139
+ _, err = io.Copy(f, resp.Body)
140
+ _ = f.Close()
141
+ if err != nil {
142
+ return "", err
143
+ }
144
+ if verbose {
145
+ Info("Image saved as %s", dest)
146
+ }
147
+ abspath, _ := filepath.Abs(dest)
148
+ return abspath, nil
149
+ }
150
+
151
+ type WebImage struct{ Image }
152
+
153
+ type GeneratedImage struct {
154
+ Image
155
+ Cookies map[string]string
156
+ }
157
+
158
+ func (g GeneratedImage) Save(path string, filename string, fullSize bool, verbose bool, skipInvalidFilename bool, insecure bool) (string, error) {
159
+ if len(g.Cookies) == 0 {
160
+ return "", &ValueError{Msg: "GeneratedImage requires cookies."}
161
+ }
162
+ url := g.URL
163
+ if fullSize {
164
+ url = url + "=s2048"
165
+ }
166
+ if filename == "" {
167
+ name := time.Now().Format("20060102150405")
168
+ if len(url) >= 10 {
169
+ name = fmt.Sprintf("%s_%s.png", name, url[len(url)-10:])
170
+ } else {
171
+ name += ".png"
172
+ }
173
+ filename = name
174
+ }
175
+ tmp := g.Image
176
+ tmp.URL = url
177
+ return tmp.Save(path, filename, g.Cookies, verbose, skipInvalidFilename, insecure)
178
+ }
179
+
180
+ // Request parsing & file helpers -------------------------------------------
181
+
182
+ func ParseMessagesAndFiles(rawJSON []byte) ([]RoleText, [][]byte, []string, [][]int, error) {
183
+ var messages []RoleText
184
+ var files [][]byte
185
+ var mimes []string
186
+ var perMsgFileIdx [][]int
187
+
188
+ contents := gjson.GetBytes(rawJSON, "contents")
189
+ if contents.Exists() {
190
+ contents.ForEach(func(_, content gjson.Result) bool {
191
+ role := NormalizeRole(content.Get("role").String())
192
+ var b strings.Builder
193
+ startFile := len(files)
194
+ content.Get("parts").ForEach(func(_, part gjson.Result) bool {
195
+ if text := part.Get("text"); text.Exists() {
196
+ if b.Len() > 0 {
197
+ b.WriteString("\n")
198
+ }
199
+ b.WriteString(text.String())
200
+ }
201
+ if inlineData := part.Get("inlineData"); inlineData.Exists() {
202
+ data := inlineData.Get("data").String()
203
+ if data != "" {
204
+ if dec, err := base64.StdEncoding.DecodeString(data); err == nil {
205
+ files = append(files, dec)
206
+ m := inlineData.Get("mimeType").String()
207
+ if m == "" {
208
+ m = inlineData.Get("mime_type").String()
209
+ }
210
+ mimes = append(mimes, m)
211
+ }
212
+ }
213
+ }
214
+ return true
215
+ })
216
+ messages = append(messages, RoleText{Role: role, Text: b.String()})
217
+ endFile := len(files)
218
+ if endFile > startFile {
219
+ idxs := make([]int, 0, endFile-startFile)
220
+ for i := startFile; i < endFile; i++ {
221
+ idxs = append(idxs, i)
222
+ }
223
+ perMsgFileIdx = append(perMsgFileIdx, idxs)
224
+ } else {
225
+ perMsgFileIdx = append(perMsgFileIdx, nil)
226
+ }
227
+ return true
228
+ })
229
+ }
230
+ return messages, files, mimes, perMsgFileIdx, nil
231
+ }
232
+
233
+ func MaterializeInlineFiles(files [][]byte, mimes []string) ([]string, *interfaces.ErrorMessage) {
234
+ if len(files) == 0 {
235
+ return nil, nil
236
+ }
237
+ paths := make([]string, 0, len(files))
238
+ for i, data := range files {
239
+ ext := MimeToExt(mimes, i)
240
+ f, err := os.CreateTemp("", "gemini-upload-*"+ext)
241
+ if err != nil {
242
+ return nil, &interfaces.ErrorMessage{StatusCode: http.StatusInternalServerError, Error: fmt.Errorf("failed to create temp file: %w", err)}
243
+ }
244
+ if _, err = f.Write(data); err != nil {
245
+ _ = f.Close()
246
+ _ = os.Remove(f.Name())
247
+ return nil, &interfaces.ErrorMessage{StatusCode: http.StatusInternalServerError, Error: fmt.Errorf("failed to write temp file: %w", err)}
248
+ }
249
+ if err = f.Close(); err != nil {
250
+ _ = os.Remove(f.Name())
251
+ return nil, &interfaces.ErrorMessage{StatusCode: http.StatusInternalServerError, Error: fmt.Errorf("failed to close temp file: %w", err)}
252
+ }
253
+ paths = append(paths, f.Name())
254
+ }
255
+ return paths, nil
256
+ }
257
+
258
+ func CleanupFiles(paths []string) {
259
+ for _, p := range paths {
260
+ if p != "" {
261
+ _ = os.Remove(p)
262
+ }
263
+ }
264
+ }
265
+
266
+ func FetchGeneratedImageData(gi GeneratedImage) (string, string, error) {
267
+ path, err := gi.Save("", "", true, false, true, false)
268
+ if err != nil {
269
+ return "", "", err
270
+ }
271
+ defer func() { _ = os.Remove(path) }()
272
+ b, err := os.ReadFile(path)
273
+ if err != nil {
274
+ return "", "", err
275
+ }
276
+ mime := http.DetectContentType(b)
277
+ if !strings.HasPrefix(mime, "image/") {
278
+ if guessed := mimeFromExtension(filepath.Ext(path)); guessed != "" {
279
+ mime = guessed
280
+ } else {
281
+ mime = "image/png"
282
+ }
283
+ }
284
+ return mime, base64.StdEncoding.EncodeToString(b), nil
285
+ }
286
+
287
+ func MimeToExt(mimes []string, i int) string {
288
+ if i < len(mimes) {
289
+ return MimeToPreferredExt(strings.ToLower(mimes[i]))
290
+ }
291
+ return ".png"
292
+ }
293
+
294
+ var preferredExtByMIME = map[string]string{
295
+ "image/png": ".png",
296
+ "image/jpeg": ".jpg",
297
+ "image/jpg": ".jpg",
298
+ "image/webp": ".webp",
299
+ "image/gif": ".gif",
300
+ "image/bmp": ".bmp",
301
+ "image/heic": ".heic",
302
+ "application/pdf": ".pdf",
303
+ }
304
+
305
+ func MimeToPreferredExt(mime string) string {
306
+ normalized := strings.ToLower(strings.TrimSpace(mime))
307
+ if normalized == "" {
308
+ return ".png"
309
+ }
310
+ if ext, ok := preferredExtByMIME[normalized]; ok {
311
+ return ext
312
+ }
313
+ return ".png"
314
+ }
315
+
316
+ func mimeFromExtension(ext string) string {
317
+ cleaned := strings.TrimPrefix(strings.ToLower(ext), ".")
318
+ if cleaned == "" {
319
+ return ""
320
+ }
321
+ if mt, ok := misc.MimeTypes[cleaned]; ok && mt != "" {
322
+ return mt
323
+ }
324
+ return ""
325
+ }
326
+
327
+ // File upload helpers ------------------------------------------------------
328
+
329
+ func uploadFile(path string, proxy string, insecure bool) (string, error) {
330
+ f, err := os.Open(path)
331
+ if err != nil {
332
+ return "", err
333
+ }
334
+ defer f.Close()
335
+
336
+ var buf bytes.Buffer
337
+ mw := multipart.NewWriter(&buf)
338
+ fw, err := mw.CreateFormFile("file", filepath.Base(path))
339
+ if err != nil {
340
+ return "", err
341
+ }
342
+ if _, err := io.Copy(fw, f); err != nil {
343
+ return "", err
344
+ }
345
+ _ = mw.Close()
346
+
347
+ tr := &http.Transport{}
348
+ if proxy != "" {
349
+ if pu, err := url.Parse(proxy); err == nil {
350
+ tr.Proxy = http.ProxyURL(pu)
351
+ }
352
+ }
353
+ if insecure {
354
+ tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
355
+ }
356
+ client := &http.Client{Transport: tr, Timeout: 300 * time.Second}
357
+
358
+ req, _ := http.NewRequest(http.MethodPost, EndpointUpload, &buf)
359
+ for k, v := range HeadersUpload {
360
+ for _, vv := range v {
361
+ req.Header.Add(k, vv)
362
+ }
363
+ }
364
+ req.Header.Set("Content-Type", mw.FormDataContentType())
365
+ req.Header.Set("Accept", "*/*")
366
+ req.Header.Set("Connection", "keep-alive")
367
+
368
+ resp, err := client.Do(req)
369
+ if err != nil {
370
+ return "", err
371
+ }
372
+ defer resp.Body.Close()
373
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
374
+ return "", &APIError{Msg: resp.Status}
375
+ }
376
+ b, err := io.ReadAll(resp.Body)
377
+ if err != nil {
378
+ return "", err
379
+ }
380
+ return string(b), nil
381
+ }
382
+
383
+ func parseFileName(path string) (string, error) {
384
+ if st, err := os.Stat(path); err != nil || st.IsDir() {
385
+ return "", &ValueError{Msg: path + " is not a valid file."}
386
+ }
387
+ return filepath.Base(path), nil
388
+ }
internal/client/gemini-web/models.go ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package geminiwebapi
2
+
3
+ import (
4
+ "net/http"
5
+ "strings"
6
+ "sync"
7
+
8
+ "github.com/luispater/CLIProxyAPI/v5/internal/registry"
9
+ )
10
+
11
+ // Endpoints used by the Gemini web app
12
+ const (
13
+ EndpointGoogle = "https://www.google.com"
14
+ EndpointInit = "https://gemini.google.com/app"
15
+ EndpointGenerate = "https://gemini.google.com/_/BardChatUi/data/assistant.lamda.BardFrontendService/StreamGenerate"
16
+ EndpointRotateCookies = "https://accounts.google.com/RotateCookies"
17
+ EndpointUpload = "https://content-push.googleapis.com/upload"
18
+ )
19
+
20
+ // Default headers
21
+ var (
22
+ HeadersGemini = http.Header{
23
+ "Content-Type": []string{"application/x-www-form-urlencoded;charset=utf-8"},
24
+ "Host": []string{"gemini.google.com"},
25
+ "Origin": []string{"https://gemini.google.com"},
26
+ "Referer": []string{"https://gemini.google.com/"},
27
+ "User-Agent": []string{"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},
28
+ "X-Same-Domain": []string{"1"},
29
+ }
30
+ HeadersRotateCookies = http.Header{
31
+ "Content-Type": []string{"application/json"},
32
+ }
33
+ HeadersUpload = http.Header{
34
+ "Push-ID": []string{"feeds/mcudyrk2a4khkz"},
35
+ }
36
+ )
37
+
38
+ // Model defines available model names and headers
39
+ type Model struct {
40
+ Name string
41
+ ModelHeader http.Header
42
+ AdvancedOnly bool
43
+ }
44
+
45
+ var (
46
+ ModelUnspecified = Model{
47
+ Name: "unspecified",
48
+ ModelHeader: http.Header{},
49
+ AdvancedOnly: false,
50
+ }
51
+ ModelG25Flash = Model{
52
+ Name: "gemini-2.5-flash",
53
+ ModelHeader: http.Header{
54
+ "x-goog-ext-525001261-jspb": []string{"[1,null,null,null,\"71c2d248d3b102ff\",null,null,0,[4]]"},
55
+ },
56
+ AdvancedOnly: false,
57
+ }
58
+ ModelG25Pro = Model{
59
+ Name: "gemini-2.5-pro",
60
+ ModelHeader: http.Header{
61
+ "x-goog-ext-525001261-jspb": []string{"[1,null,null,null,\"4af6c7f5da75d65d\",null,null,0,[4]]"},
62
+ },
63
+ AdvancedOnly: false,
64
+ }
65
+ ModelG20Flash = Model{ // Deprecated, still supported
66
+ Name: "gemini-2.0-flash",
67
+ ModelHeader: http.Header{
68
+ "x-goog-ext-525001261-jspb": []string{"[1,null,null,null,\"f299729663a2343f\"]"},
69
+ },
70
+ AdvancedOnly: false,
71
+ }
72
+ ModelG20FlashThinking = Model{ // Deprecated, still supported
73
+ Name: "gemini-2.0-flash-thinking",
74
+ ModelHeader: http.Header{
75
+ "x-goog-ext-525001261-jspb": []string{"[null,null,null,null,\"7ca48d02d802f20a\"]"},
76
+ },
77
+ AdvancedOnly: false,
78
+ }
79
+ )
80
+
81
+ // ModelFromName returns a model by name or error if not found
82
+ func ModelFromName(name string) (Model, error) {
83
+ switch name {
84
+ case ModelUnspecified.Name:
85
+ return ModelUnspecified, nil
86
+ case ModelG25Flash.Name:
87
+ return ModelG25Flash, nil
88
+ case ModelG25Pro.Name:
89
+ return ModelG25Pro, nil
90
+ case ModelG20Flash.Name:
91
+ return ModelG20Flash, nil
92
+ case ModelG20FlashThinking.Name:
93
+ return ModelG20FlashThinking, nil
94
+ default:
95
+ return Model{}, &ValueError{Msg: "Unknown model name: " + name}
96
+ }
97
+ }
98
+
99
+ // Known error codes returned from server
100
+ const (
101
+ ErrorUsageLimitExceeded = 1037
102
+ ErrorModelInconsistent = 1050
103
+ ErrorModelHeaderInvalid = 1052
104
+ ErrorIPTemporarilyBlocked = 1060
105
+ )
106
+
107
+ var (
108
+ GeminiWebAliasOnce sync.Once
109
+ GeminiWebAliasMap map[string]string
110
+ )
111
+
112
+ // EnsureGeminiWebAliasMap initializes alias lookup lazily.
113
+ func EnsureGeminiWebAliasMap() {
114
+ GeminiWebAliasOnce.Do(func() {
115
+ GeminiWebAliasMap = make(map[string]string)
116
+ for _, m := range registry.GetGeminiModels() {
117
+ if m.ID == "gemini-2.5-flash-lite" {
118
+ continue
119
+ }
120
+ alias := AliasFromModelID(m.ID)
121
+ GeminiWebAliasMap[strings.ToLower(alias)] = strings.ToLower(m.ID)
122
+ }
123
+ })
124
+ }
125
+
126
+ // GetGeminiWebAliasedModels returns Gemini models exposed with web aliases.
127
+ func GetGeminiWebAliasedModels() []*registry.ModelInfo {
128
+ EnsureGeminiWebAliasMap()
129
+ aliased := make([]*registry.ModelInfo, 0)
130
+ for _, m := range registry.GetGeminiModels() {
131
+ if m.ID == "gemini-2.5-flash-lite" {
132
+ continue
133
+ }
134
+ cpy := *m
135
+ cpy.ID = AliasFromModelID(m.ID)
136
+ cpy.Name = cpy.ID
137
+ aliased = append(aliased, &cpy)
138
+ }
139
+ return aliased
140
+ }
141
+
142
+ // MapAliasToUnderlying normalizes web aliases back to canonical Gemini IDs.
143
+ func MapAliasToUnderlying(name string) string {
144
+ EnsureGeminiWebAliasMap()
145
+ n := strings.ToLower(name)
146
+ if u, ok := GeminiWebAliasMap[n]; ok {
147
+ return u
148
+ }
149
+ const suffix = "-web"
150
+ if strings.HasSuffix(n, suffix) {
151
+ return strings.TrimSuffix(n, suffix)
152
+ }
153
+ return name
154
+ }
155
+
156
+ // AliasFromModelID builds the web alias for a Gemini model identifier.
157
+ func AliasFromModelID(modelID string) string {
158
+ return modelID + "-web"
159
+ }
internal/client/gemini-web/persistence.go ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package geminiwebapi
2
+
3
+ import (
4
+ "crypto/sha256"
5
+ "encoding/hex"
6
+ "encoding/json"
7
+ "fmt"
8
+ "os"
9
+ "path/filepath"
10
+ "strings"
11
+ "time"
12
+
13
+ "github.com/luispater/CLIProxyAPI/v5/internal/auth/gemini"
14
+ )
15
+
16
+ // StoredMessage represents a single message in a conversation record.
17
+ type StoredMessage struct {
18
+ Role string `json:"role"`
19
+ Content string `json:"content"`
20
+ Name string `json:"name,omitempty"`
21
+ }
22
+
23
+ // ConversationRecord stores a full conversation with its metadata for persistence.
24
+ type ConversationRecord struct {
25
+ Model string `json:"model"`
26
+ ClientID string `json:"client_id"`
27
+ Metadata []string `json:"metadata,omitempty"`
28
+ Messages []StoredMessage `json:"messages"`
29
+ CreatedAt time.Time `json:"created_at"`
30
+ UpdatedAt time.Time `json:"updated_at"`
31
+ }
32
+
33
+ // Sha256Hex computes the SHA256 hash of a string and returns its hex representation.
34
+ func Sha256Hex(s string) string {
35
+ sum := sha256.Sum256([]byte(s))
36
+ return hex.EncodeToString(sum[:])
37
+ }
38
+
39
+ // RoleText represents a turn in a conversation with a role and text content.
40
+ type RoleText struct {
41
+ Role string
42
+ Text string
43
+ }
44
+
45
+ func ToStoredMessages(msgs []RoleText) []StoredMessage {
46
+ out := make([]StoredMessage, 0, len(msgs))
47
+ for _, m := range msgs {
48
+ out = append(out, StoredMessage{
49
+ Role: m.Role,
50
+ Content: m.Text,
51
+ })
52
+ }
53
+ return out
54
+ }
55
+
56
+ func HashMessage(m StoredMessage) string {
57
+ s := fmt.Sprintf(`{"content":%q,"role":%q}`, m.Content, strings.ToLower(m.Role))
58
+ return Sha256Hex(s)
59
+ }
60
+
61
+ func HashConversation(clientID, model string, msgs []StoredMessage) string {
62
+ var b strings.Builder
63
+ b.WriteString(clientID)
64
+ b.WriteString("|")
65
+ b.WriteString(model)
66
+ for _, m := range msgs {
67
+ b.WriteString("|")
68
+ b.WriteString(HashMessage(m))
69
+ }
70
+ return Sha256Hex(b.String())
71
+ }
72
+
73
+ // ConvStorePath returns the path for account-level metadata persistence based on token file path.
74
+ func ConvStorePath(tokenFilePath string) string {
75
+ wd, err := os.Getwd()
76
+ if err != nil || wd == "" {
77
+ wd = "."
78
+ }
79
+ convDir := filepath.Join(wd, "conv")
80
+ base := strings.TrimSuffix(filepath.Base(tokenFilePath), filepath.Ext(tokenFilePath))
81
+ return filepath.Join(convDir, base+".conv.json")
82
+ }
83
+
84
+ // ConvDataPath returns the path for full conversation persistence based on token file path.
85
+ func ConvDataPath(tokenFilePath string) string {
86
+ wd, err := os.Getwd()
87
+ if err != nil || wd == "" {
88
+ wd = "."
89
+ }
90
+ convDir := filepath.Join(wd, "conv")
91
+ base := strings.TrimSuffix(filepath.Base(tokenFilePath), filepath.Ext(tokenFilePath))
92
+ return filepath.Join(convDir, base+".data.json")
93
+ }
94
+
95
+ // LoadConvStore reads the account-level metadata store from disk.
96
+ func LoadConvStore(path string) (map[string][]string, error) {
97
+ b, err := os.ReadFile(path)
98
+ if err != nil {
99
+ // Missing file is not an error; return empty map
100
+ return map[string][]string{}, nil
101
+ }
102
+ var tmp map[string][]string
103
+ if err := json.Unmarshal(b, &tmp); err != nil {
104
+ return nil, err
105
+ }
106
+ if tmp == nil {
107
+ tmp = map[string][]string{}
108
+ }
109
+ return tmp, nil
110
+ }
111
+
112
+ // SaveConvStore writes the account-level metadata store to disk atomically.
113
+ func SaveConvStore(path string, data map[string][]string) error {
114
+ if data == nil {
115
+ data = map[string][]string{}
116
+ }
117
+ payload, err := json.MarshalIndent(data, "", " ")
118
+ if err != nil {
119
+ return err
120
+ }
121
+ // Ensure directory exists
122
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
123
+ return err
124
+ }
125
+ tmp := path + ".tmp"
126
+ if err := os.WriteFile(tmp, payload, 0o644); err != nil {
127
+ return err
128
+ }
129
+ return os.Rename(tmp, path)
130
+ }
131
+
132
+ // AccountMetaKey builds the key for account-level metadata map.
133
+ func AccountMetaKey(email, modelName string) string {
134
+ return fmt.Sprintf("account-meta|%s|%s", email, modelName)
135
+ }
136
+
137
+ // LoadConvData reads the full conversation data and index from disk.
138
+ func LoadConvData(path string) (map[string]ConversationRecord, map[string]string, error) {
139
+ b, err := os.ReadFile(path)
140
+ if err != nil {
141
+ // Missing file is not an error; return empty sets
142
+ return map[string]ConversationRecord{}, map[string]string{}, nil
143
+ }
144
+ var wrapper struct {
145
+ Items map[string]ConversationRecord `json:"items"`
146
+ Index map[string]string `json:"index"`
147
+ }
148
+ if err := json.Unmarshal(b, &wrapper); err != nil {
149
+ return nil, nil, err
150
+ }
151
+ if wrapper.Items == nil {
152
+ wrapper.Items = map[string]ConversationRecord{}
153
+ }
154
+ if wrapper.Index == nil {
155
+ wrapper.Index = map[string]string{}
156
+ }
157
+ return wrapper.Items, wrapper.Index, nil
158
+ }
159
+
160
+ // SaveConvData writes the full conversation data and index to disk atomically.
161
+ func SaveConvData(path string, items map[string]ConversationRecord, index map[string]string) error {
162
+ if items == nil {
163
+ items = map[string]ConversationRecord{}
164
+ }
165
+ if index == nil {
166
+ index = map[string]string{}
167
+ }
168
+ wrapper := struct {
169
+ Items map[string]ConversationRecord `json:"items"`
170
+ Index map[string]string `json:"index"`
171
+ }{Items: items, Index: index}
172
+ payload, err := json.MarshalIndent(wrapper, "", " ")
173
+ if err != nil {
174
+ return err
175
+ }
176
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
177
+ return err
178
+ }
179
+ tmp := path + ".tmp"
180
+ if err := os.WriteFile(tmp, payload, 0o644); err != nil {
181
+ return err
182
+ }
183
+ return os.Rename(tmp, path)
184
+ }
185
+
186
+ // BuildConversationRecord constructs a ConversationRecord from history and the latest output.
187
+ // Returns false when output is empty or has no candidates.
188
+ func BuildConversationRecord(model, clientID string, history []RoleText, output *ModelOutput, metadata []string) (ConversationRecord, bool) {
189
+ if output == nil || len(output.Candidates) == 0 {
190
+ return ConversationRecord{}, false
191
+ }
192
+ text := ""
193
+ if t := output.Candidates[0].Text; t != "" {
194
+ text = RemoveThinkTags(t)
195
+ }
196
+ final := append([]RoleText{}, history...)
197
+ final = append(final, RoleText{Role: "assistant", Text: text})
198
+ rec := ConversationRecord{
199
+ Model: model,
200
+ ClientID: clientID,
201
+ Metadata: metadata,
202
+ Messages: ToStoredMessages(final),
203
+ CreatedAt: time.Now(),
204
+ UpdatedAt: time.Now(),
205
+ }
206
+ return rec, true
207
+ }
208
+
209
+ // FindByMessageListIn looks up a conversation record by hashed message list.
210
+ // It attempts both the stable client ID and a legacy email-based ID.
211
+ func FindByMessageListIn(items map[string]ConversationRecord, index map[string]string, stableClientID, email, model string, msgs []RoleText) (ConversationRecord, bool) {
212
+ stored := ToStoredMessages(msgs)
213
+ stableHash := HashConversation(stableClientID, model, stored)
214
+ fallbackHash := HashConversation(email, model, stored)
215
+
216
+ // Try stable hash via index indirection first
217
+ if key, ok := index["hash:"+stableHash]; ok {
218
+ if rec, ok2 := items[key]; ok2 {
219
+ return rec, true
220
+ }
221
+ }
222
+ if rec, ok := items[stableHash]; ok {
223
+ return rec, true
224
+ }
225
+ // Fallback to legacy hash (email-based)
226
+ if key, ok := index["hash:"+fallbackHash]; ok {
227
+ if rec, ok2 := items[key]; ok2 {
228
+ return rec, true
229
+ }
230
+ }
231
+ if rec, ok := items[fallbackHash]; ok {
232
+ return rec, true
233
+ }
234
+ return ConversationRecord{}, false
235
+ }
236
+
237
+ // FindConversationIn tries exact then sanitized assistant messages.
238
+ func FindConversationIn(items map[string]ConversationRecord, index map[string]string, stableClientID, email, model string, msgs []RoleText) (ConversationRecord, bool) {
239
+ if len(msgs) == 0 {
240
+ return ConversationRecord{}, false
241
+ }
242
+ if rec, ok := FindByMessageListIn(items, index, stableClientID, email, model, msgs); ok {
243
+ return rec, true
244
+ }
245
+ if rec, ok := FindByMessageListIn(items, index, stableClientID, email, model, SanitizeAssistantMessages(msgs)); ok {
246
+ return rec, true
247
+ }
248
+ return ConversationRecord{}, false
249
+ }
250
+
251
+ // FindReusableSessionIn returns reusable metadata and the remaining message suffix.
252
+ func FindReusableSessionIn(items map[string]ConversationRecord, index map[string]string, stableClientID, email, model string, msgs []RoleText) ([]string, []RoleText) {
253
+ if len(msgs) < 2 {
254
+ return nil, nil
255
+ }
256
+ searchEnd := len(msgs)
257
+ for searchEnd >= 2 {
258
+ sub := msgs[:searchEnd]
259
+ tail := sub[len(sub)-1]
260
+ if strings.EqualFold(tail.Role, "assistant") || strings.EqualFold(tail.Role, "system") {
261
+ if rec, ok := FindConversationIn(items, index, stableClientID, email, model, sub); ok {
262
+ remain := msgs[searchEnd:]
263
+ return rec.Metadata, remain
264
+ }
265
+ }
266
+ searchEnd--
267
+ }
268
+ return nil, nil
269
+ }
270
+
271
+ // CookiesSidecarPath derives the sidecar cookie file path from the main token JSON path.
272
+ func CookiesSidecarPath(mainPath string) string {
273
+ if strings.HasSuffix(mainPath, ".json") {
274
+ return strings.TrimSuffix(mainPath, ".json") + ".cookies"
275
+ }
276
+ return mainPath + ".cookies"
277
+ }
278
+
279
+ // FileExists reports whether the given path exists and is a regular file.
280
+ func FileExists(path string) bool {
281
+ if path == "" {
282
+ return false
283
+ }
284
+ if st, err := os.Stat(path); err == nil && !st.IsDir() {
285
+ return true
286
+ }
287
+ return false
288
+ }
289
+
290
+ // ApplyCookiesSidecarToTokenStorage loads cookies from sidecar into the provided token storage.
291
+ // Returns true when a sidecar was found and applied.
292
+ func ApplyCookiesSidecarToTokenStorage(tokenFilePath string, ts *gemini.GeminiWebTokenStorage) (bool, error) {
293
+ if ts == nil {
294
+ return false, nil
295
+ }
296
+ side := CookiesSidecarPath(tokenFilePath)
297
+ if !FileExists(side) {
298
+ return false, nil
299
+ }
300
+ data, err := os.ReadFile(side)
301
+ if err != nil || len(data) == 0 {
302
+ return false, err
303
+ }
304
+ var latest gemini.GeminiWebTokenStorage
305
+ if err := json.Unmarshal(data, &latest); err != nil {
306
+ return false, err
307
+ }
308
+ if latest.Secure1PSID != "" {
309
+ ts.Secure1PSID = latest.Secure1PSID
310
+ }
311
+ if latest.Secure1PSIDTS != "" {
312
+ ts.Secure1PSIDTS = latest.Secure1PSIDTS
313
+ }
314
+ return true, nil
315
+ }
316
+
317
+ // SaveCookiesSidecar writes the current cookies into a sidecar file next to the token file.
318
+ // This keeps the main token JSON stable until an orderly flush.
319
+ func SaveCookiesSidecar(tokenFilePath string, cookies map[string]string) error {
320
+ side := CookiesSidecarPath(tokenFilePath)
321
+ ts := &gemini.GeminiWebTokenStorage{Type: "gemini-web"}
322
+ if v := cookies["__Secure-1PSID"]; v != "" {
323
+ ts.Secure1PSID = v
324
+ }
325
+ if v := cookies["__Secure-1PSIDTS"]; v != "" {
326
+ ts.Secure1PSIDTS = v
327
+ }
328
+ if err := os.MkdirAll(filepath.Dir(side), 0o700); err != nil {
329
+ return err
330
+ }
331
+ return ts.SaveTokenToFile(side)
332
+ }
333
+
334
+ // FlushCookiesSidecarToMain merges the sidecar cookies into the main token file and removes the sidecar.
335
+ // If sidecar is missing, it will combine the provided base token storage with the latest cookies.
336
+ func FlushCookiesSidecarToMain(tokenFilePath string, cookies map[string]string, base *gemini.GeminiWebTokenStorage) error {
337
+ if tokenFilePath == "" {
338
+ return nil
339
+ }
340
+ side := CookiesSidecarPath(tokenFilePath)
341
+ var merged gemini.GeminiWebTokenStorage
342
+ var fromSidecar bool
343
+ if FileExists(side) {
344
+ if data, err := os.ReadFile(side); err == nil && len(data) > 0 {
345
+ if err2 := json.Unmarshal(data, &merged); err2 == nil {
346
+ fromSidecar = true
347
+ }
348
+ }
349
+ }
350
+ if !fromSidecar {
351
+ if base != nil {
352
+ merged = *base
353
+ }
354
+ if v := cookies["__Secure-1PSID"]; v != "" {
355
+ merged.Secure1PSID = v
356
+ }
357
+ if v := cookies["__Secure-1PSIDTS"]; v != "" {
358
+ merged.Secure1PSIDTS = v
359
+ }
360
+ }
361
+ merged.Type = "gemini-web"
362
+ if err := os.MkdirAll(filepath.Dir(tokenFilePath), 0o700); err != nil {
363
+ return err
364
+ }
365
+ if err := merged.SaveTokenToFile(tokenFilePath); err != nil {
366
+ return err
367
+ }
368
+ if FileExists(side) {
369
+ _ = os.Remove(side)
370
+ }
371
+ return nil
372
+ }
373
+
374
+ // IsSelfPersistedToken compares provided token storage with current cookies.
375
+ // Removed: IsSelfPersistedToken (client-side no longer needs self-originated write detection)
internal/client/gemini-web/prompt.go ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package geminiwebapi
2
+
3
+ import (
4
+ "math"
5
+ "regexp"
6
+ "strings"
7
+ "unicode/utf8"
8
+
9
+ "github.com/tidwall/gjson"
10
+ )
11
+
12
+ var (
13
+ reThink = regexp.MustCompile(`(?s)^\s*<think>.*?</think>\s*`)
14
+ reXMLAnyTag = regexp.MustCompile(`(?s)<\s*[^>]+>`)
15
+ )
16
+
17
+ // NormalizeRole converts a role to a standard format (lowercase, 'model' -> 'assistant').
18
+ func NormalizeRole(role string) string {
19
+ r := strings.ToLower(role)
20
+ if r == "model" {
21
+ return "assistant"
22
+ }
23
+ return r
24
+ }
25
+
26
+ // NeedRoleTags checks if a list of messages requires role tags.
27
+ func NeedRoleTags(msgs []RoleText) bool {
28
+ for _, m := range msgs {
29
+ if strings.ToLower(m.Role) != "user" {
30
+ return true
31
+ }
32
+ }
33
+ return false
34
+ }
35
+
36
+ // AddRoleTag wraps content with a role tag.
37
+ func AddRoleTag(role, content string, unclose bool) string {
38
+ if role == "" {
39
+ role = "user"
40
+ }
41
+ if unclose {
42
+ return "<|im_start|>" + role + "\n" + content
43
+ }
44
+ return "<|im_start|>" + role + "\n" + content + "\n<|im_end|>"
45
+ }
46
+
47
+ // BuildPrompt constructs the final prompt from a list of messages.
48
+ func BuildPrompt(msgs []RoleText, tagged bool, appendAssistant bool) string {
49
+ if len(msgs) == 0 {
50
+ if tagged && appendAssistant {
51
+ return AddRoleTag("assistant", "", true)
52
+ }
53
+ return ""
54
+ }
55
+ if !tagged {
56
+ var sb strings.Builder
57
+ for i, m := range msgs {
58
+ if i > 0 {
59
+ sb.WriteString("\n")
60
+ }
61
+ sb.WriteString(m.Text)
62
+ }
63
+ return sb.String()
64
+ }
65
+ var sb strings.Builder
66
+ for _, m := range msgs {
67
+ sb.WriteString(AddRoleTag(m.Role, m.Text, false))
68
+ sb.WriteString("\n")
69
+ }
70
+ if appendAssistant {
71
+ sb.WriteString(AddRoleTag("assistant", "", true))
72
+ }
73
+ return strings.TrimSpace(sb.String())
74
+ }
75
+
76
+ // RemoveThinkTags strips <think>...</think> blocks from a string.
77
+ func RemoveThinkTags(s string) string {
78
+ return strings.TrimSpace(reThink.ReplaceAllString(s, ""))
79
+ }
80
+
81
+ // SanitizeAssistantMessages removes think tags from assistant messages.
82
+ func SanitizeAssistantMessages(msgs []RoleText) []RoleText {
83
+ out := make([]RoleText, 0, len(msgs))
84
+ for _, m := range msgs {
85
+ if strings.ToLower(m.Role) == "assistant" {
86
+ out = append(out, RoleText{Role: m.Role, Text: RemoveThinkTags(m.Text)})
87
+ } else {
88
+ out = append(out, m)
89
+ }
90
+ }
91
+ return out
92
+ }
93
+
94
+ // AppendXMLWrapHintIfNeeded appends an XML wrap hint to messages containing XML-like blocks.
95
+ func AppendXMLWrapHintIfNeeded(msgs []RoleText, disable bool) []RoleText {
96
+ if disable {
97
+ return msgs
98
+ }
99
+ const xmlWrapHint = "\nFor any xml block, e.g. tool call, always wrap it with: \n`````xml\n...\n`````\n"
100
+ out := make([]RoleText, 0, len(msgs))
101
+ for _, m := range msgs {
102
+ t := m.Text
103
+ if reXMLAnyTag.MatchString(t) {
104
+ t = t + xmlWrapHint
105
+ }
106
+ out = append(out, RoleText{Role: m.Role, Text: t})
107
+ }
108
+ return out
109
+ }
110
+
111
+ // EstimateTotalTokensFromRawJSON estimates token count by summing text parts.
112
+ func EstimateTotalTokensFromRawJSON(rawJSON []byte) int {
113
+ totalChars := 0
114
+ contents := gjson.GetBytes(rawJSON, "contents")
115
+ if contents.Exists() {
116
+ contents.ForEach(func(_, content gjson.Result) bool {
117
+ content.Get("parts").ForEach(func(_, part gjson.Result) bool {
118
+ if t := part.Get("text"); t.Exists() {
119
+ totalChars += utf8.RuneCountInString(t.String())
120
+ }
121
+ return true
122
+ })
123
+ return true
124
+ })
125
+ }
126
+ if totalChars <= 0 {
127
+ return 0
128
+ }
129
+ return int(math.Ceil(float64(totalChars) / 4.0))
130
+ }
internal/client/gemini-web/request.go ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package geminiwebapi
2
+
3
+ import (
4
+ "fmt"
5
+ "strings"
6
+ "unicode/utf8"
7
+
8
+ "github.com/luispater/CLIProxyAPI/v5/internal/config"
9
+ )
10
+
11
+ const continuationHint = "\n(More messages to come, please reply with just 'ok.')"
12
+
13
+ func ChunkByRunes(s string, size int) []string {
14
+ if size <= 0 {
15
+ return []string{s}
16
+ }
17
+ chunks := make([]string, 0, (len(s)/size)+1)
18
+ var buf strings.Builder
19
+ count := 0
20
+ for _, r := range s {
21
+ buf.WriteRune(r)
22
+ count++
23
+ if count >= size {
24
+ chunks = append(chunks, buf.String())
25
+ buf.Reset()
26
+ count = 0
27
+ }
28
+ }
29
+ if buf.Len() > 0 {
30
+ chunks = append(chunks, buf.String())
31
+ }
32
+ if len(chunks) == 0 {
33
+ return []string{""}
34
+ }
35
+ return chunks
36
+ }
37
+
38
+ func MaxCharsPerRequest(cfg *config.Config) int {
39
+ // Read max characters per request from config with a conservative default.
40
+ if cfg != nil {
41
+ if v := cfg.GeminiWeb.MaxCharsPerRequest; v > 0 {
42
+ return v
43
+ }
44
+ }
45
+ return 1_000_000
46
+ }
47
+
48
+ func SendWithSplit(chat *ChatSession, text string, files []string, cfg *config.Config) (ModelOutput, error) {
49
+ // Validate chat session
50
+ if chat == nil {
51
+ return ModelOutput{}, fmt.Errorf("nil chat session")
52
+ }
53
+
54
+ // Resolve max characters per request
55
+ max := MaxCharsPerRequest(cfg)
56
+ if max <= 0 {
57
+ max = 1_000_000
58
+ }
59
+
60
+ // If within limit, send directly
61
+ if utf8.RuneCountInString(text) <= max {
62
+ return chat.SendMessage(text, files)
63
+ }
64
+
65
+ // Decide whether to use continuation hint (enabled by default)
66
+ useHint := true
67
+ if cfg != nil && cfg.GeminiWeb.DisableContinuationHint {
68
+ useHint = false
69
+ }
70
+
71
+ // Compute chunk size in runes. If the hint does not fit, disable it for this request.
72
+ hintLen := 0
73
+ if useHint {
74
+ hintLen = utf8.RuneCountInString(continuationHint)
75
+ }
76
+ chunkSize := max - hintLen
77
+ if chunkSize <= 0 {
78
+ // max is too small to accommodate the hint; fall back to no-hint splitting
79
+ useHint = false
80
+ chunkSize = max
81
+ }
82
+ if chunkSize <= 0 {
83
+ // As a last resort, split by single rune to avoid exceeding the limit
84
+ chunkSize = 1
85
+ }
86
+
87
+ // Split into rune-safe chunks
88
+ chunks := ChunkByRunes(text, chunkSize)
89
+ if len(chunks) == 0 {
90
+ chunks = []string{""}
91
+ }
92
+
93
+ // Send all but the last chunk without files, optionally appending hint
94
+ for i := 0; i < len(chunks)-1; i++ {
95
+ part := chunks[i]
96
+ if useHint {
97
+ part += continuationHint
98
+ }
99
+ if _, err := chat.SendMessage(part, nil); err != nil {
100
+ return ModelOutput{}, err
101
+ }
102
+ }
103
+
104
+ // Send final chunk with files and return the actual output
105
+ return chat.SendMessage(chunks[len(chunks)-1], files)
106
+ }
internal/client/gemini-web/types.go ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package geminiwebapi
2
+
3
+ import (
4
+ "fmt"
5
+ "html"
6
+ )
7
+
8
+ type Candidate struct {
9
+ RCID string
10
+ Text string
11
+ Thoughts *string
12
+ WebImages []WebImage
13
+ GeneratedImages []GeneratedImage
14
+ }
15
+
16
+ func (c Candidate) String() string {
17
+ t := c.Text
18
+ if len(t) > 20 {
19
+ t = t[:20] + "..."
20
+ }
21
+ return fmt.Sprintf("Candidate(rcid='%s', text='%s', images=%d)", c.RCID, t, len(c.WebImages)+len(c.GeneratedImages))
22
+ }
23
+
24
+ func (c Candidate) Images() []Image {
25
+ images := make([]Image, 0, len(c.WebImages)+len(c.GeneratedImages))
26
+ for _, wi := range c.WebImages {
27
+ images = append(images, wi.Image)
28
+ }
29
+ for _, gi := range c.GeneratedImages {
30
+ images = append(images, gi.Image)
31
+ }
32
+ return images
33
+ }
34
+
35
+ type ModelOutput struct {
36
+ Metadata []string
37
+ Candidates []Candidate
38
+ Chosen int
39
+ }
40
+
41
+ func (m ModelOutput) String() string { return m.Text() }
42
+
43
+ func (m ModelOutput) Text() string {
44
+ if len(m.Candidates) == 0 {
45
+ return ""
46
+ }
47
+ return m.Candidates[m.Chosen].Text
48
+ }
49
+
50
+ func (m ModelOutput) Thoughts() *string {
51
+ if len(m.Candidates) == 0 {
52
+ return nil
53
+ }
54
+ return m.Candidates[m.Chosen].Thoughts
55
+ }
56
+
57
+ func (m ModelOutput) Images() []Image {
58
+ if len(m.Candidates) == 0 {
59
+ return nil
60
+ }
61
+ return m.Candidates[m.Chosen].Images()
62
+ }
63
+
64
+ func (m ModelOutput) RCID() string {
65
+ if len(m.Candidates) == 0 {
66
+ return ""
67
+ }
68
+ return m.Candidates[m.Chosen].RCID
69
+ }
70
+
71
+ type Gem struct {
72
+ ID string
73
+ Name string
74
+ Description *string
75
+ Prompt *string
76
+ Predefined bool
77
+ }
78
+
79
+ func (g Gem) String() string {
80
+ return fmt.Sprintf("Gem(id='%s', name='%s', description='%v', prompt='%v', predefined=%v)", g.ID, g.Name, g.Description, g.Prompt, g.Predefined)
81
+ }
82
+
83
+ func decodeHTML(s string) string { return html.UnescapeString(s) }
internal/client/gemini-web_client.go ADDED
@@ -0,0 +1,845 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package client
2
+
3
+ import (
4
+ "bytes"
5
+ "context"
6
+ "encoding/json"
7
+ "errors"
8
+ "fmt"
9
+ "net/http"
10
+ "net/http/cookiejar"
11
+ "path/filepath"
12
+ "strings"
13
+ "sync"
14
+ "time"
15
+
16
+ "github.com/gin-gonic/gin"
17
+ "github.com/luispater/CLIProxyAPI/v5/internal/auth/gemini"
18
+ geminiWeb "github.com/luispater/CLIProxyAPI/v5/internal/client/gemini-web"
19
+ "github.com/luispater/CLIProxyAPI/v5/internal/config"
20
+ . "github.com/luispater/CLIProxyAPI/v5/internal/constant"
21
+ "github.com/luispater/CLIProxyAPI/v5/internal/interfaces"
22
+ "github.com/luispater/CLIProxyAPI/v5/internal/translator/translator"
23
+ "github.com/luispater/CLIProxyAPI/v5/internal/util"
24
+ log "github.com/sirupsen/logrus"
25
+ "github.com/tidwall/gjson"
26
+ "github.com/tidwall/sjson"
27
+ )
28
+
29
+ // This file wires the external-facing client for Gemini Web.
30
+
31
+ // Defaults for Gemini Web behavior that are no longer configurable via YAML.
32
+ const (
33
+ // geminiWebDefaultTimeoutSec defines the per-request HTTP timeout seconds.
34
+ geminiWebDefaultTimeoutSec = 300
35
+ // geminiWebDefaultRefreshIntervalSec defines background cookie auto-refresh interval seconds.
36
+ geminiWebDefaultRefreshIntervalSec = 540
37
+ // geminiWebDefaultPersistIntervalSec defines how often rotated cookies are persisted to disk (3 hours).
38
+ geminiWebDefaultPersistIntervalSec = 10800
39
+ )
40
+
41
+ type GeminiWebClient struct {
42
+ ClientBase
43
+ gwc *geminiWeb.GeminiClient
44
+ tokenFilePath string
45
+ convStore map[string][]string
46
+ convMutex sync.RWMutex
47
+
48
+ // JSON-based conversation persistence
49
+ convData map[string]geminiWeb.ConversationRecord
50
+ convIndex map[string]string
51
+
52
+ // restart-stable id for conversation hashing/lookup
53
+ stableClientID string
54
+
55
+ cookieRotationStarted bool
56
+ cookiePersistCancel context.CancelFunc
57
+ lastPersistedTS string
58
+
59
+ // register models once after successful auth init
60
+ modelsRegistered bool
61
+ }
62
+
63
+ func (c *GeminiWebClient) UnregisterClient() {
64
+ if c.cookiePersistCancel != nil {
65
+ c.cookiePersistCancel()
66
+ c.cookiePersistCancel = nil
67
+ }
68
+ // Flush sidecar cookies to main token file and remove sidecar
69
+ c.flushCookiesSidecarToMain()
70
+ if c.gwc != nil {
71
+ c.gwc.Close(0)
72
+ c.gwc = nil
73
+ }
74
+ c.ClientBase.UnregisterClient()
75
+ }
76
+
77
+ func NewGeminiWebClient(cfg *config.Config, ts *gemini.GeminiWebTokenStorage, tokenFilePath string) (*GeminiWebClient, error) {
78
+ jar, _ := cookiejar.New(nil)
79
+ httpClient := util.SetProxy(cfg, &http.Client{Jar: jar})
80
+
81
+ // derive a restart-stable id from tokens (sha256 of 1PSID, hex prefix)
82
+ stableSuffix := geminiWeb.Sha256Hex(ts.Secure1PSID)
83
+ if len(stableSuffix) > 16 {
84
+ stableSuffix = stableSuffix[:16]
85
+ }
86
+ idPrefix := stableSuffix
87
+ if len(idPrefix) > 8 {
88
+ idPrefix = idPrefix[:8]
89
+ }
90
+ clientID := fmt.Sprintf("gemini-web-%s-%d", idPrefix, time.Now().UnixNano())
91
+
92
+ client := &GeminiWebClient{
93
+ ClientBase: ClientBase{
94
+ RequestMutex: &sync.Mutex{},
95
+ httpClient: httpClient,
96
+ cfg: cfg,
97
+ tokenStorage: ts,
98
+ modelQuotaExceeded: make(map[string]*time.Time),
99
+ },
100
+ tokenFilePath: tokenFilePath,
101
+ convStore: make(map[string][]string),
102
+ convData: make(map[string]geminiWeb.ConversationRecord),
103
+ convIndex: make(map[string]string),
104
+ stableClientID: "gemini-web-" + stableSuffix,
105
+ }
106
+ // Load persisted conversation stores
107
+ if store, err := geminiWeb.LoadConvStore(geminiWeb.ConvStorePath(tokenFilePath)); err == nil {
108
+ client.convStore = store
109
+ }
110
+ if items, index, err := geminiWeb.LoadConvData(geminiWeb.ConvDataPath(tokenFilePath)); err == nil {
111
+ client.convData = items
112
+ client.convIndex = index
113
+ }
114
+
115
+ client.InitializeModelRegistry(clientID)
116
+
117
+ // Prefer sidecar cookies at startup if present
118
+ if ok, err := geminiWeb.ApplyCookiesSidecarToTokenStorage(tokenFilePath, ts); err == nil && ok {
119
+ log.Debugf("Loaded Gemini Web cookies from sidecar: %s", filepath.Base(geminiWeb.CookiesSidecarPath(tokenFilePath)))
120
+ }
121
+
122
+ client.gwc = geminiWeb.NewGeminiClient(ts.Secure1PSID, ts.Secure1PSIDTS, cfg.ProxyURL, geminiWeb.WithAccountLabel(strings.TrimSuffix(filepath.Base(tokenFilePath), ".json")))
123
+ timeoutSec := geminiWebDefaultTimeoutSec
124
+ refreshIntervalSec := cfg.GeminiWeb.TokenRefreshSeconds
125
+ if refreshIntervalSec <= 0 {
126
+ refreshIntervalSec = geminiWebDefaultRefreshIntervalSec
127
+ }
128
+ if err := client.gwc.Init(float64(timeoutSec), false, 300, true, float64(refreshIntervalSec), false); err != nil {
129
+ log.Warnf("Gemini Web init failed for %s: %v. Will retry in background.", client.GetEmail(), err)
130
+ go client.backgroundInitRetry()
131
+ } else {
132
+ client.cookieRotationStarted = true
133
+ // Persist immediately once after successful init to capture fresh cookies
134
+ _ = client.SaveTokenToFile()
135
+ client.startCookiePersist()
136
+ }
137
+ return client, nil
138
+ }
139
+
140
+ func (c *GeminiWebClient) Init() error {
141
+ ts := c.tokenStorage.(*gemini.GeminiWebTokenStorage)
142
+ c.gwc = geminiWeb.NewGeminiClient(ts.Secure1PSID, ts.Secure1PSIDTS, c.cfg.ProxyURL, geminiWeb.WithAccountLabel(c.GetEmail()))
143
+ timeoutSec := geminiWebDefaultTimeoutSec
144
+ refreshIntervalSec := c.cfg.GeminiWeb.TokenRefreshSeconds
145
+ if refreshIntervalSec <= 0 {
146
+ refreshIntervalSec = geminiWebDefaultRefreshIntervalSec
147
+ }
148
+ if err := c.gwc.Init(float64(timeoutSec), false, 300, true, float64(refreshIntervalSec), false); err != nil {
149
+ return err
150
+ }
151
+ c.registerModelsOnce()
152
+ // Persist immediately once after successful init to capture fresh cookies
153
+ _ = c.SaveTokenToFile()
154
+ c.startCookiePersist()
155
+ return nil
156
+ }
157
+
158
+ // IsReady reports whether the underlying Gemini Web client is initialized and running.
159
+ func (c *GeminiWebClient) IsReady() bool {
160
+ return c != nil && c.gwc != nil && c.gwc.Running
161
+ }
162
+
163
+ func (c *GeminiWebClient) registerModelsOnce() {
164
+ if c.modelsRegistered {
165
+ return
166
+ }
167
+ c.RegisterModels(GEMINI, geminiWeb.GetGeminiWebAliasedModels())
168
+ c.modelsRegistered = true
169
+ }
170
+
171
+ // EnsureRegistered registers models if the client is ready and not yet registered.
172
+ // It is safe to call multiple times.
173
+ func (c *GeminiWebClient) EnsureRegistered() {
174
+ if c.IsReady() {
175
+ c.registerModelsOnce()
176
+ }
177
+ }
178
+
179
+ func (c *GeminiWebClient) Type() string { return GEMINI }
180
+ func (c *GeminiWebClient) Provider() string { return GEMINI }
181
+ func (c *GeminiWebClient) CanProvideModel(modelName string) bool {
182
+ geminiWeb.EnsureGeminiWebAliasMap()
183
+ _, ok := geminiWeb.GeminiWebAliasMap[strings.ToLower(modelName)]
184
+ return ok
185
+ }
186
+ func (c *GeminiWebClient) GetEmail() string {
187
+ base := filepath.Base(c.tokenFilePath)
188
+ return strings.TrimSuffix(base, ".json")
189
+ }
190
+ func (c *GeminiWebClient) StableClientID() string {
191
+ if c.stableClientID != "" {
192
+ return c.stableClientID
193
+ }
194
+ sum := geminiWeb.Sha256Hex(c.GetEmail())
195
+ if len(sum) > 16 {
196
+ sum = sum[:16]
197
+ }
198
+ return "gemini-web-" + sum
199
+ }
200
+
201
+ // useReusableContext reports whether JSON-based reusable conversation matching is enabled.
202
+ // Controlled by `gemini-web.context` boolean in config (true enables reuse, default true).
203
+ func (c *GeminiWebClient) useReusableContext() bool {
204
+ if c == nil || c.cfg == nil {
205
+ return true
206
+ }
207
+ return c.cfg.GeminiWeb.Context
208
+ }
209
+
210
+ // chatPrep encapsulates shared request preparation results for both stream and non-stream flows.
211
+ type chatPrep struct {
212
+ chat *geminiWeb.ChatSession
213
+ prompt string
214
+ uploaded []string
215
+ reuse bool
216
+ metaLen int
217
+ handlerType string
218
+ tagged bool
219
+ underlying string
220
+ cleaned []geminiWeb.RoleText
221
+ translatedRaw []byte
222
+ }
223
+
224
+ // prepareChat performs translation, message parsing, metadata reuse, prompt build and StartChat.
225
+ func (c *GeminiWebClient) prepareChat(ctx context.Context, modelName string, rawJSON []byte, isStream bool) (*chatPrep, *interfaces.ErrorMessage) {
226
+ res := &chatPrep{}
227
+ if handler, ok := ctx.Value("handler").(interfaces.APIHandler); ok {
228
+ res.handlerType = handler.HandlerType()
229
+ rawJSON = translator.Request(res.handlerType, c.Type(), modelName, rawJSON, isStream)
230
+ }
231
+ res.translatedRaw = rawJSON
232
+ if c.cfg.RequestLog {
233
+ if ginContext, ok := ctx.Value("gin").(*gin.Context); ok {
234
+ ginContext.Set("API_REQUEST", rawJSON)
235
+ }
236
+ }
237
+ messages, files, mimes, msgFileIdx, err := geminiWeb.ParseMessagesAndFiles(rawJSON)
238
+ if err != nil {
239
+ return nil, &interfaces.ErrorMessage{StatusCode: 400, Error: fmt.Errorf("bad request: %w", err)}
240
+ }
241
+ cleaned := geminiWeb.SanitizeAssistantMessages(messages)
242
+ res.cleaned = cleaned
243
+ res.underlying = geminiWeb.MapAliasToUnderlying(modelName)
244
+ model, err := geminiWeb.ModelFromName(res.underlying)
245
+ if err != nil {
246
+ return nil, &interfaces.ErrorMessage{StatusCode: 400, Error: err}
247
+ }
248
+
249
+ var (
250
+ meta []string
251
+ useMsgs []geminiWeb.RoleText
252
+ filesSubset [][]byte
253
+ mimesSubset []string
254
+ )
255
+ if c.useReusableContext() {
256
+ reuseMeta, remaining := c.findReusableSession(res.underlying, cleaned)
257
+ res.reuse = len(reuseMeta) > 0
258
+ if res.reuse {
259
+ meta = reuseMeta
260
+ if len(remaining) == 1 {
261
+ useMsgs = []geminiWeb.RoleText{remaining[0]}
262
+ } else {
263
+ useMsgs = remaining
264
+ }
265
+ } else {
266
+ meta = nil
267
+ useMsgs = cleaned
268
+ }
269
+ res.tagged = geminiWeb.NeedRoleTags(useMsgs)
270
+ if res.reuse && len(useMsgs) == 1 {
271
+ res.tagged = false
272
+ }
273
+ if res.reuse && len(useMsgs) == 1 && len(messages) > 0 {
274
+ lastIdx := len(messages) - 1
275
+ if lastIdx >= 0 && lastIdx < len(msgFileIdx) {
276
+ for _, fi := range msgFileIdx[lastIdx] {
277
+ if fi >= 0 && fi < len(files) {
278
+ filesSubset = append(filesSubset, files[fi])
279
+ if fi < len(mimes) {
280
+ mimesSubset = append(mimesSubset, mimes[fi])
281
+ } else {
282
+ mimesSubset = append(mimesSubset, "")
283
+ }
284
+ }
285
+ }
286
+ }
287
+ } else {
288
+ filesSubset = files
289
+ mimesSubset = mimes
290
+ }
291
+ res.metaLen = len(meta)
292
+ } else {
293
+ key := geminiWeb.AccountMetaKey(c.GetEmail(), modelName)
294
+ c.convMutex.RLock()
295
+ meta = c.convStore[key]
296
+ c.convMutex.RUnlock()
297
+ useMsgs = cleaned
298
+ res.tagged = geminiWeb.NeedRoleTags(useMsgs)
299
+ filesSubset = files
300
+ mimesSubset = mimes
301
+ res.reuse = false
302
+ res.metaLen = len(meta)
303
+ }
304
+
305
+ uploadedFiles, upErr := geminiWeb.MaterializeInlineFiles(filesSubset, mimesSubset)
306
+ if upErr != nil {
307
+ return nil, upErr
308
+ }
309
+ res.uploaded = uploadedFiles
310
+
311
+ // XML hint follows code-mode only:
312
+ // - code-mode = true -> enable XML wrapping hint
313
+ // - code-mode = false -> disable XML wrapping hint
314
+ enableXMLHint := c.cfg != nil && c.cfg.GeminiWeb.CodeMode
315
+ useMsgs = geminiWeb.AppendXMLWrapHintIfNeeded(useMsgs, !enableXMLHint)
316
+ res.prompt = geminiWeb.BuildPrompt(useMsgs, res.tagged, res.tagged)
317
+ if strings.TrimSpace(res.prompt) == "" {
318
+ return nil, &interfaces.ErrorMessage{StatusCode: 400, Error: errors.New("bad request: empty prompt after filtering system/thought content")}
319
+ }
320
+ c.appendUpstreamRequestLog(ctx, modelName, res.tagged, true, res.prompt, len(uploadedFiles), res.reuse, res.metaLen)
321
+ gem := c.getConfiguredGem()
322
+ res.chat = c.gwc.StartChat(model, gem, meta)
323
+ return res, nil
324
+ }
325
+
326
+ func (c *GeminiWebClient) SendRawMessage(ctx context.Context, modelName string, rawJSON []byte, alt string) ([]byte, *interfaces.ErrorMessage) {
327
+ original := bytes.Clone(rawJSON)
328
+ prep, prepErr := c.prepareChat(ctx, modelName, rawJSON, false)
329
+ if prepErr != nil {
330
+ return nil, prepErr
331
+ }
332
+ defer geminiWeb.CleanupFiles(prep.uploaded)
333
+ log.Debugf("Use Gemini Web account %s for model %s", c.GetEmail(), modelName)
334
+ out, genErr := geminiWeb.SendWithSplit(prep.chat, prep.prompt, prep.uploaded, c.cfg)
335
+ if genErr != nil {
336
+ return nil, c.handleSendError(genErr, modelName)
337
+ }
338
+ gemBytes, errMsg := c.handleSendSuccess(ctx, prep, &out, modelName)
339
+ if errMsg != nil {
340
+ return nil, errMsg
341
+ }
342
+ if translator.NeedConvert(prep.handlerType, c.Type()) {
343
+ var param any
344
+ out := translator.ResponseNonStream(prep.handlerType, c.Type(), ctx, modelName, original, prep.translatedRaw, gemBytes, &param)
345
+ if prep.handlerType == OPENAI && out != "" {
346
+ newID := fmt.Sprintf("chatcmpl-%x", time.Now().UnixNano())
347
+ if v := gjson.Parse(out).Get("id"); v.Exists() {
348
+ out, _ = sjson.Set(out, "id", newID)
349
+ }
350
+ }
351
+ return []byte(out), nil
352
+ }
353
+ return gemBytes, nil
354
+ }
355
+
356
+ func (c *GeminiWebClient) SendRawMessageStream(ctx context.Context, modelName string, rawJSON []byte, alt string) (<-chan []byte, <-chan *interfaces.ErrorMessage) {
357
+ dataChan := make(chan []byte)
358
+ errChan := make(chan *interfaces.ErrorMessage)
359
+ go func() {
360
+ defer close(dataChan)
361
+ defer close(errChan)
362
+ original := bytes.Clone(rawJSON)
363
+ prep, prepErr := c.prepareChat(ctx, modelName, rawJSON, true)
364
+ if prepErr != nil {
365
+ errChan <- prepErr
366
+ return
367
+ }
368
+ defer geminiWeb.CleanupFiles(prep.uploaded)
369
+ log.Debugf("Use Gemini Web account %s for model %s", c.GetEmail(), modelName)
370
+ out, genErr := geminiWeb.SendWithSplit(prep.chat, prep.prompt, prep.uploaded, c.cfg)
371
+ if genErr != nil {
372
+ errChan <- c.handleSendError(genErr, modelName)
373
+ return
374
+ }
375
+ gemBytes, errMsg := c.handleSendSuccess(ctx, prep, &out, modelName)
376
+ if errMsg != nil {
377
+ errChan <- errMsg
378
+ return
379
+ }
380
+ // Branch by handler type:
381
+ // - Native Gemini handler: emit at most two messages (thoughts, then others), no [DONE].
382
+ // - Translated handlers (e.g., OpenAI Responses): split first payload into two (if thoughts exist), then emit translator's [DONE].
383
+ if prep.handlerType == GEMINI {
384
+ root := gjson.ParseBytes(gemBytes)
385
+ parts := root.Get("candidates.0.content.parts")
386
+ if parts.Exists() && parts.IsArray() {
387
+ var thoughtArr, otherArr strings.Builder
388
+ thoughtCount := 0
389
+ thoughtArr.WriteByte('[')
390
+ otherArr.WriteByte('[')
391
+ firstThought := true
392
+ firstOther := true
393
+ parts.ForEach(func(_, part gjson.Result) bool {
394
+ if part.Get("thought").Bool() {
395
+ if !firstThought {
396
+ thoughtArr.WriteByte(',')
397
+ }
398
+ thoughtArr.WriteString(part.Raw)
399
+ firstThought = false
400
+ thoughtCount++
401
+ } else {
402
+ if !firstOther {
403
+ otherArr.WriteByte(',')
404
+ }
405
+ otherArr.WriteString(part.Raw)
406
+ firstOther = false
407
+ }
408
+ return true
409
+ })
410
+ thoughtArr.WriteByte(']')
411
+ otherArr.WriteByte(']')
412
+ if thoughtCount > 0 {
413
+ thoughtOnly, _ := sjson.SetRaw(string(gemBytes), "candidates.0.content.parts", thoughtArr.String())
414
+ // Only when the first chunk contains thoughts, set finishReason to null
415
+ thoughtOnly, _ = sjson.SetRaw(thoughtOnly, "candidates.0.finishReason", "null")
416
+ dataChan <- []byte(thoughtOnly)
417
+ }
418
+ othersOnly, _ := sjson.SetRaw(string(gemBytes), "candidates.0.content.parts", otherArr.String())
419
+ // Do not modify finishReason for non-thought first chunks or subsequent chunks
420
+ dataChan <- []byte(othersOnly)
421
+ return
422
+ }
423
+ // Fallback: no parts array; emit single message
424
+ // No special handling when no parts or no thoughts
425
+ dataChan <- gemBytes
426
+ return
427
+ }
428
+
429
+ // Translated handlers: when code-mode is ON, merge <think> into content and emit a single chunk; otherwise keep split.
430
+ newCtx := context.WithValue(ctx, "alt", alt)
431
+ var param any
432
+ if c.cfg.GeminiWeb.CodeMode {
433
+ combined := mergeThoughtIntoSingleContent(gemBytes)
434
+ lines := translator.Response(prep.handlerType, c.Type(), newCtx, modelName, original, prep.translatedRaw, combined, &param)
435
+ for _, l := range lines {
436
+ if l != "" {
437
+ dataChan <- []byte(l)
438
+ }
439
+ }
440
+ done := translator.Response(prep.handlerType, c.Type(), newCtx, modelName, original, prep.translatedRaw, []byte("[DONE]"), &param)
441
+ for _, l := range done {
442
+ if l != "" {
443
+ dataChan <- []byte(l)
444
+ }
445
+ }
446
+ return
447
+ }
448
+ root := gjson.ParseBytes(gemBytes)
449
+ parts := root.Get("candidates.0.content.parts")
450
+ if parts.Exists() && parts.IsArray() {
451
+ var thoughtArr, otherArr strings.Builder
452
+ thoughtCount := 0
453
+ thoughtArr.WriteByte('[')
454
+ otherArr.WriteByte('[')
455
+ firstThought := true
456
+ firstOther := true
457
+ parts.ForEach(func(_, part gjson.Result) bool {
458
+ if part.Get("thought").Bool() {
459
+ if !firstThought {
460
+ thoughtArr.WriteByte(',')
461
+ }
462
+ thoughtArr.WriteString(part.Raw)
463
+ firstThought = false
464
+ thoughtCount++
465
+ } else {
466
+ if !firstOther {
467
+ otherArr.WriteByte(',')
468
+ }
469
+ otherArr.WriteString(part.Raw)
470
+ firstOther = false
471
+ }
472
+ return true
473
+ })
474
+ thoughtArr.WriteByte(']')
475
+ otherArr.WriteByte(']')
476
+
477
+ if thoughtCount > 0 {
478
+ thoughtOnly, _ := sjson.SetRaw(string(gemBytes), "candidates.0.content.parts", thoughtArr.String())
479
+ // Only when the first chunk contains thoughts, suppress finishReason before translation
480
+ thoughtOnly, _ = sjson.Delete(thoughtOnly, "candidates.0.finishReason")
481
+ // If CodeMode enabled, demote thought parts to content before translating
482
+ if c.cfg.GeminiWeb.CodeMode {
483
+ processed := collapseThoughtPartsToContent([]byte(thoughtOnly))
484
+ lines := translator.Response(prep.handlerType, c.Type(), newCtx, modelName, original, prep.translatedRaw, processed, &param)
485
+ for _, l := range lines {
486
+ if l != "" {
487
+ dataChan <- []byte(l)
488
+ }
489
+ }
490
+ } else {
491
+ lines := translator.Response(prep.handlerType, c.Type(), newCtx, modelName, original, prep.translatedRaw, []byte(thoughtOnly), &param)
492
+ for _, l := range lines {
493
+ if l != "" {
494
+ dataChan <- []byte(l)
495
+ }
496
+ }
497
+ }
498
+ }
499
+ othersOnly, _ := sjson.SetRaw(string(gemBytes), "candidates.0.content.parts", otherArr.String())
500
+ // Do not modify finishReason if there is no thought chunk
501
+ if c.cfg.GeminiWeb.CodeMode {
502
+ processed := collapseThoughtPartsToContent([]byte(othersOnly))
503
+ lines := translator.Response(prep.handlerType, c.Type(), newCtx, modelName, original, prep.translatedRaw, processed, &param)
504
+ for _, l := range lines {
505
+ if l != "" {
506
+ dataChan <- []byte(l)
507
+ }
508
+ }
509
+ } else {
510
+ lines := translator.Response(prep.handlerType, c.Type(), newCtx, modelName, original, prep.translatedRaw, []byte(othersOnly), &param)
511
+ for _, l := range lines {
512
+ if l != "" {
513
+ dataChan <- []byte(l)
514
+ }
515
+ }
516
+ }
517
+ done := translator.Response(prep.handlerType, c.Type(), newCtx, modelName, original, prep.translatedRaw, []byte("[DONE]"), &param)
518
+ for _, l := range done {
519
+ if l != "" {
520
+ dataChan <- []byte(l)
521
+ }
522
+ }
523
+ return
524
+ }
525
+ // Fallback: no parts array; forward as a single translated payload then DONE
526
+ // If code-mode is ON, still merge to a single content block.
527
+ if c.cfg.GeminiWeb.CodeMode {
528
+ processed := mergeThoughtIntoSingleContent(gemBytes)
529
+ lines := translator.Response(prep.handlerType, c.Type(), newCtx, modelName, original, prep.translatedRaw, processed, &param)
530
+ for _, l := range lines {
531
+ if l != "" {
532
+ dataChan <- []byte(l)
533
+ }
534
+ }
535
+ } else {
536
+ lines := translator.Response(prep.handlerType, c.Type(), newCtx, modelName, original, prep.translatedRaw, gemBytes, &param)
537
+ for _, l := range lines {
538
+ if l != "" {
539
+ dataChan <- []byte(l)
540
+ }
541
+ }
542
+ }
543
+ done := translator.Response(prep.handlerType, c.Type(), newCtx, modelName, original, prep.translatedRaw, []byte("[DONE]"), &param)
544
+ for _, l := range done {
545
+ if l != "" {
546
+ dataChan <- []byte(l)
547
+ }
548
+ }
549
+ }()
550
+ return dataChan, errChan
551
+ }
552
+
553
+ func (c *GeminiWebClient) handleSendError(genErr error, modelName string) *interfaces.ErrorMessage {
554
+ log.Errorf("failed to generate content: %v", genErr)
555
+ status := 500
556
+ var eUsage *geminiWeb.UsageLimitExceeded
557
+ var eTempBlock *geminiWeb.TemporarilyBlocked
558
+ if errors.As(genErr, &eUsage) || errors.As(genErr, &eTempBlock) {
559
+ status = 429
560
+ }
561
+ var eModelInvalid *geminiWeb.ModelInvalid
562
+ if status == 500 && errors.As(genErr, &eModelInvalid) {
563
+ status = 400
564
+ }
565
+ var eValue *geminiWeb.ValueError
566
+ if status == 500 && errors.As(genErr, &eValue) {
567
+ status = 400
568
+ }
569
+ var eTimeout *geminiWeb.TimeoutError
570
+ if status == 500 && errors.As(genErr, &eTimeout) {
571
+ status = 504
572
+ }
573
+ if status == 429 {
574
+ now := time.Now()
575
+ c.modelQuotaExceeded[modelName] = &now
576
+ c.SetModelQuotaExceeded(modelName)
577
+ }
578
+ return &interfaces.ErrorMessage{StatusCode: status, Error: genErr}
579
+ }
580
+
581
+ func (c *GeminiWebClient) handleSendSuccess(ctx context.Context, prep *chatPrep, output *geminiWeb.ModelOutput, modelName string) ([]byte, *interfaces.ErrorMessage) {
582
+ delete(c.modelQuotaExceeded, modelName)
583
+ c.ClearModelQuotaExceeded(modelName)
584
+ gemBytes, err := geminiWeb.ConvertOutputToGemini(output, modelName, prep.prompt)
585
+ if err != nil {
586
+ return nil, &interfaces.ErrorMessage{StatusCode: 500, Error: err}
587
+ }
588
+ c.AddAPIResponseData(ctx, gemBytes)
589
+ if output != nil {
590
+ metaAfter := prep.chat.Metadata()
591
+ if len(metaAfter) > 0 {
592
+ key := geminiWeb.AccountMetaKey(c.GetEmail(), modelName)
593
+ c.convMutex.Lock()
594
+ c.convStore[key] = metaAfter
595
+ snapshot := c.convStore
596
+ c.convMutex.Unlock()
597
+ _ = geminiWeb.SaveConvStore(geminiWeb.ConvStorePath(c.tokenFilePath), snapshot)
598
+ }
599
+ if c.useReusableContext() {
600
+ c.storeConversationJSON(prep.underlying, prep.cleaned, prep.chat.Metadata(), output)
601
+ }
602
+ }
603
+ return gemBytes, nil
604
+ }
605
+
606
+ // collapseThoughtPartsToContent flattens Gemini "thought" parts into regular text parts
607
+ // so downstream OpenAI translators emit them as `content` instead of `reasoning_content`.
608
+ // It preserves part order and keeps non-text parts intact.
609
+ func collapseThoughtPartsToContent(gemBytes []byte) []byte {
610
+ parts := gjson.GetBytes(gemBytes, "candidates.0.content.parts")
611
+ if !parts.Exists() || !parts.IsArray() {
612
+ return gemBytes
613
+ }
614
+ arr := parts.Array()
615
+ newParts := make([]json.RawMessage, 0, len(arr))
616
+ for _, part := range arr {
617
+ if t := part.Get("text"); t.Exists() {
618
+ obj, _ := json.Marshal(map[string]string{"text": t.String()})
619
+ newParts = append(newParts, obj)
620
+ } else {
621
+ newParts = append(newParts, json.RawMessage(part.Raw))
622
+ }
623
+ }
624
+ var sb strings.Builder
625
+ sb.WriteByte('[')
626
+ for i, p := range newParts {
627
+ if i > 0 {
628
+ sb.WriteByte(',')
629
+ }
630
+ sb.Write(p)
631
+ }
632
+ sb.WriteByte(']')
633
+ if updated, err := sjson.SetRawBytes(gemBytes, "candidates.0.content.parts", []byte(sb.String())); err == nil {
634
+ return updated
635
+ }
636
+ return gemBytes
637
+ }
638
+
639
+ // mergeThoughtIntoSingleContent merges all thought text and normal text into one text part.
640
+ // The output places the thought text inside <think>...</think> followed by a newline and then the normal text.
641
+ // Non-text parts are ignored for the combined output chunk.
642
+ func mergeThoughtIntoSingleContent(gemBytes []byte) []byte {
643
+ parts := gjson.GetBytes(gemBytes, "candidates.0.content.parts")
644
+ if !parts.Exists() || !parts.IsArray() {
645
+ return gemBytes
646
+ }
647
+ var thought strings.Builder
648
+ var visible strings.Builder
649
+ parts.ForEach(func(_, part gjson.Result) bool {
650
+ if t := part.Get("text"); t.Exists() {
651
+ if part.Get("thought").Bool() {
652
+ thought.WriteString(t.String())
653
+ } else {
654
+ visible.WriteString(t.String())
655
+ }
656
+ }
657
+ return true
658
+ })
659
+ var combined strings.Builder
660
+ if thought.Len() > 0 {
661
+ combined.WriteString("<think>")
662
+ combined.WriteString(thought.String())
663
+ combined.WriteString("</think>\n\n")
664
+ }
665
+ combined.WriteString(visible.String())
666
+
667
+ // Build a single-part array
668
+ obj, _ := json.Marshal(map[string]string{"text": combined.String()})
669
+ var arr strings.Builder
670
+ arr.WriteByte('[')
671
+ arr.Write(obj)
672
+ arr.WriteByte(']')
673
+ if updated, err := sjson.SetRawBytes(gemBytes, "candidates.0.content.parts", []byte(arr.String())); err == nil {
674
+ return updated
675
+ }
676
+ return gemBytes
677
+ }
678
+
679
+ func (c *GeminiWebClient) appendUpstreamRequestLog(ctx context.Context, modelName string, useTags, explicitContext bool, prompt string, filesCount int, reuse bool, metaLen int) {
680
+ if !c.cfg.RequestLog {
681
+ return
682
+ }
683
+ ginContext, ok := ctx.Value("gin").(*gin.Context)
684
+ if !ok || ginContext == nil {
685
+ return
686
+ }
687
+ preview := geminiWeb.BuildUpstreamRequestLog(c.GetEmail(), c.useReusableContext(), useTags, explicitContext, prompt, filesCount, reuse, metaLen, c.getConfiguredGem())
688
+ if existing, exists := ginContext.Get("API_REQUEST"); exists {
689
+ if base, ok2 := existing.([]byte); ok2 {
690
+ merged := append(append([]byte{}, base...), []byte(preview)...)
691
+ ginContext.Set("API_REQUEST", merged)
692
+ }
693
+ }
694
+ }
695
+
696
+ func (c *GeminiWebClient) SendRawTokenCount(ctx context.Context, modelName string, rawJSON []byte, alt string) ([]byte, *interfaces.ErrorMessage) {
697
+ est := geminiWeb.EstimateTotalTokensFromRawJSON(rawJSON)
698
+ return []byte(fmt.Sprintf(`{"totalTokens":%d}`, est)), nil
699
+ }
700
+
701
+ // SaveTokenToFile persists current cookies to a sidecar file via gemini-web helpers.
702
+ func (c *GeminiWebClient) SaveTokenToFile() error {
703
+ ts := c.tokenStorage.(*gemini.GeminiWebTokenStorage)
704
+ if c.gwc != nil && c.gwc.Cookies != nil {
705
+ if v, ok := c.gwc.Cookies["__Secure-1PSID"]; ok && v != "" {
706
+ ts.Secure1PSID = v
707
+ }
708
+ if v, ok := c.gwc.Cookies["__Secure-1PSIDTS"]; ok && v != "" {
709
+ ts.Secure1PSIDTS = v
710
+ }
711
+ }
712
+ log.Debugf("Saving Gemini Web cookies sidecar to %s", filepath.Base(geminiWeb.CookiesSidecarPath(c.tokenFilePath)))
713
+ return geminiWeb.SaveCookiesSidecar(c.tokenFilePath, c.gwc.Cookies)
714
+ }
715
+
716
+ // startCookiePersist periodically writes refreshed cookies into the sidecar file.
717
+ func (c *GeminiWebClient) startCookiePersist() {
718
+ if c.gwc == nil {
719
+ return
720
+ }
721
+ if c.cookiePersistCancel != nil {
722
+ c.cookiePersistCancel()
723
+ c.cookiePersistCancel = nil
724
+ }
725
+ ctx, cancel := context.WithCancel(context.Background())
726
+ c.cookiePersistCancel = cancel
727
+ go func() {
728
+ // Persist cookies at the same cadence as auto-refresh when enabled,
729
+ // otherwise use a coarse default interval.
730
+ persistSec := geminiWebDefaultPersistIntervalSec
731
+ if c.gwc != nil && c.gwc.AutoRefresh {
732
+ if sec := int(c.gwc.RefreshInterval / time.Second); sec > 0 {
733
+ persistSec = sec
734
+ }
735
+ }
736
+ ticker := time.NewTicker(time.Duration(persistSec) * time.Second)
737
+ defer ticker.Stop()
738
+ for {
739
+ select {
740
+ case <-ctx.Done():
741
+ return
742
+ case <-ticker.C:
743
+ if c.gwc != nil && c.gwc.Cookies != nil {
744
+ if err := c.SaveTokenToFile(); err != nil {
745
+ log.Errorf("Failed to persist cookies sidecar for %s: %v", c.GetEmail(), err)
746
+ } else {
747
+ log.Debugf("Persisted cookies sidecar for %s", c.GetEmail())
748
+ }
749
+ }
750
+ }
751
+ }
752
+ }()
753
+ }
754
+
755
+ func (c *GeminiWebClient) IsModelQuotaExceeded(model string) bool {
756
+ if t, ok := c.modelQuotaExceeded[model]; ok {
757
+ return time.Since(*t) <= 30*time.Minute
758
+ }
759
+ return false
760
+ }
761
+
762
+ func (c *GeminiWebClient) GetUserAgent() string {
763
+ if ua := geminiWeb.HeadersGemini.Get("User-Agent"); ua != "" {
764
+ return ua
765
+ }
766
+ return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
767
+ }
768
+
769
+ func (c *GeminiWebClient) GetRequestMutex() *sync.Mutex { return nil }
770
+
771
+ func (c *GeminiWebClient) RefreshTokens(ctx context.Context) error { return c.Init() }
772
+
773
+ func (c *GeminiWebClient) backgroundInitRetry() {
774
+ backoffs := []time.Duration{5 * time.Second, 10 * time.Second, 30 * time.Second, 1 * time.Minute, 2 * time.Minute, 5 * time.Minute}
775
+ i := 0
776
+ for {
777
+ if err := c.Init(); err == nil {
778
+ log.Infof("Gemini Web token recovered for %s", c.GetEmail())
779
+ if !c.cookieRotationStarted {
780
+ c.cookieRotationStarted = true
781
+ }
782
+ c.startCookiePersist()
783
+ return
784
+ }
785
+ d := backoffs[i]
786
+ if i < len(backoffs)-1 {
787
+ i++
788
+ }
789
+ time.Sleep(d)
790
+ }
791
+ }
792
+
793
+ // IsSelfPersistedToken compares provided token storage with currently active cookies.
794
+ // Removed: IsSelfPersistedToken (no longer needed with sidecar-only periodic persistence)
795
+
796
+ // flushCookiesSidecarToMain merges sidecar cookies into the main token file.
797
+ func (c *GeminiWebClient) flushCookiesSidecarToMain() {
798
+ if c.tokenFilePath == "" {
799
+ return
800
+ }
801
+ base := c.tokenStorage.(*gemini.GeminiWebTokenStorage)
802
+ if err := geminiWeb.FlushCookiesSidecarToMain(c.tokenFilePath, c.gwc.Cookies, base); err != nil {
803
+ log.Errorf("Failed to flush cookies sidecar to main for %s: %v", filepath.Base(c.tokenFilePath), err)
804
+ }
805
+ }
806
+
807
+ // findReusableSession and storeConversationJSON live here as client bridges; hashing/records in gemini-web
808
+
809
+ func (c *GeminiWebClient) getConfiguredGem() *geminiWeb.Gem {
810
+ if c.cfg.GeminiWeb.CodeMode {
811
+ return &geminiWeb.Gem{ID: "coding-partner", Name: "Coding partner", Predefined: true}
812
+ }
813
+ return nil
814
+ }
815
+
816
+ // findReusableSession bridges to gemini-web conversation reuse using in-memory stores.
817
+ func (c *GeminiWebClient) findReusableSession(model string, msgs []geminiWeb.RoleText) ([]string, []geminiWeb.RoleText) {
818
+ c.convMutex.RLock()
819
+ items := c.convData
820
+ index := c.convIndex
821
+ c.convMutex.RUnlock()
822
+ return geminiWeb.FindReusableSessionIn(items, index, c.StableClientID(), c.GetEmail(), model, msgs)
823
+ }
824
+
825
+ // storeConversationJSON persists conversation records and updates in-memory indexes.
826
+ func (c *GeminiWebClient) storeConversationJSON(model string, history []geminiWeb.RoleText, metadata []string, output *geminiWeb.ModelOutput) {
827
+ rec, ok := geminiWeb.BuildConversationRecord(model, c.StableClientID(), history, output, metadata)
828
+ if !ok {
829
+ return
830
+ }
831
+ stableID := rec.ClientID
832
+ stableHash := geminiWeb.HashConversation(stableID, model, rec.Messages)
833
+ legacyID := c.GetEmail()
834
+ legacyHash := geminiWeb.HashConversation(legacyID, model, rec.Messages)
835
+ c.convMutex.Lock()
836
+ c.convData[stableHash] = rec
837
+ c.convIndex["hash:"+stableHash] = stableHash
838
+ if legacyID != stableID {
839
+ c.convIndex["hash:"+legacyHash] = stableHash
840
+ }
841
+ items := c.convData
842
+ index := c.convIndex
843
+ c.convMutex.Unlock()
844
+ _ = geminiWeb.SaveConvData(geminiWeb.ConvDataPath(c.tokenFilePath), items, index)
845
+ }
internal/cmd/gemini-web_auth.go ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Package cmd provides command-line interface functionality for the CLI Proxy API.
2
+ package cmd
3
+
4
+ import (
5
+ "bufio"
6
+ "crypto/sha256"
7
+ "encoding/hex"
8
+ "fmt"
9
+ "os"
10
+ "path/filepath"
11
+ "strings"
12
+
13
+ "github.com/luispater/CLIProxyAPI/v5/internal/auth/gemini"
14
+ "github.com/luispater/CLIProxyAPI/v5/internal/config"
15
+ log "github.com/sirupsen/logrus"
16
+ )
17
+
18
+ // DoGeminiWebAuth handles the process of creating a Gemini Web token file.
19
+ // It prompts the user for their cookie values and saves them to a JSON file.
20
+ func DoGeminiWebAuth(cfg *config.Config) {
21
+ reader := bufio.NewReader(os.Stdin)
22
+
23
+ fmt.Print("Enter your __Secure-1PSID cookie value: ")
24
+ secure1psid, _ := reader.ReadString('\n')
25
+ secure1psid = strings.TrimSpace(secure1psid)
26
+
27
+ if secure1psid == "" {
28
+ log.Fatal("The __Secure-1PSID value cannot be empty.")
29
+ return
30
+ }
31
+
32
+ fmt.Print("Enter your __Secure-1PSIDTS cookie value: ")
33
+ secure1psidts, _ := reader.ReadString('\n')
34
+ secure1psidts = strings.TrimSpace(secure1psidts)
35
+
36
+ if secure1psidts == "" {
37
+ log.Fatal("The __Secure-1PSIDTS value cannot be empty.")
38
+ return
39
+ }
40
+
41
+ tokenStorage := &gemini.GeminiWebTokenStorage{
42
+ Secure1PSID: secure1psid,
43
+ Secure1PSIDTS: secure1psidts,
44
+ }
45
+
46
+ // Generate a filename based on the SHA256 hash of the PSID
47
+ hasher := sha256.New()
48
+ hasher.Write([]byte(secure1psid))
49
+ hash := hex.EncodeToString(hasher.Sum(nil))
50
+ fileName := fmt.Sprintf("gemini-web-%s.json", hash[:16])
51
+ filePath := filepath.Join(cfg.AuthDir, fileName)
52
+
53
+ err := tokenStorage.SaveTokenToFile(filePath)
54
+ if err != nil {
55
+ log.Fatalf("Failed to save Gemini Web token to file: %v", err)
56
+ return
57
+ }
58
+
59
+ log.Infof("Successfully saved Gemini Web token to: %s", filePath)
60
+ }
internal/cmd/run.go CHANGED
@@ -48,6 +48,9 @@ import (
48
  // - cfg: The application configuration containing settings like port, auth directory, API keys
49
  // - configPath: The path to the configuration file for watching changes
50
  func StartService(cfg *config.Config, configPath string) {
 
 
 
51
  // Create a pool of API clients, one for each token file found.
52
  cliClients := make(map[string]interfaces.Client)
53
  successfulAuthCount := 0
@@ -141,6 +144,24 @@ func StartService(cfg *config.Config, configPath string) {
141
  cliClients[path] = qwenClient
142
  successfulAuthCount++
143
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  }
145
  }
146
  return nil
@@ -165,6 +186,20 @@ func StartService(cfg *config.Config, configPath string) {
165
  allClients := clientsToSlice(cliClients)
166
  allClients = append(allClients, clientsToSlice(apiKeyClients)...)
167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  // Create and start the API server with the pool of clients in a separate goroutine.
169
  apiServer := api.NewServer(cfg, allClients, configPath)
170
  log.Infof("Starting API server on port %d", cfg.Port)
@@ -184,6 +219,10 @@ func StartService(cfg *config.Config, configPath string) {
184
  fileWatcher, errNewWatcher := watcher.NewWatcher(configPath, cfg.AuthDir, func(newClients map[string]interfaces.Client, newCfg *config.Config) {
185
  // Update the API server with new clients and configuration when files change.
186
  apiServer.UpdateClients(newClients, newCfg)
 
 
 
 
187
  })
188
  if errNewWatcher != nil {
189
  log.Fatalf("failed to create file watcher: %v", errNewWatcher)
@@ -286,10 +325,33 @@ func StartService(cfg *config.Config, configPath string) {
286
  cancelRefresh()
287
  wgRefresh.Wait()
288
 
 
 
 
 
 
 
289
  // Create a context with a timeout for the shutdown process.
290
  ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
291
  _ = cancel
292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
  // Stop the API server gracefully.
294
  if err = apiServer.Stop(ctx); err != nil {
295
  log.Debugf("Error stopping API server: %v", err)
 
48
  // - cfg: The application configuration containing settings like port, auth directory, API keys
49
  // - configPath: The path to the configuration file for watching changes
50
  func StartService(cfg *config.Config, configPath string) {
51
+ // Track the current active clients for graceful shutdown persistence.
52
+ var activeClients map[string]interfaces.Client
53
+ var activeClientsMu sync.RWMutex
54
  // Create a pool of API clients, one for each token file found.
55
  cliClients := make(map[string]interfaces.Client)
56
  successfulAuthCount := 0
 
144
  cliClients[path] = qwenClient
145
  successfulAuthCount++
146
  }
147
+ } else if tokenType == "gemini-web" {
148
+ var ts gemini.GeminiWebTokenStorage
149
+ if err = json.Unmarshal(data, &ts); err == nil {
150
+ log.Info("Initializing gemini web authentication for token...")
151
+ geminiWebClient, errClient := client.NewGeminiWebClient(cfg, &ts, path)
152
+ if errClient != nil {
153
+ log.Errorf("failed to create gemini web client for token %s: %v", path, errClient)
154
+ return errClient
155
+ }
156
+ if geminiWebClient.IsReady() {
157
+ log.Info("Authentication successful.")
158
+ geminiWebClient.EnsureRegistered()
159
+ } else {
160
+ log.Info("Client created. Authentication pending (background retry in progress).")
161
+ }
162
+ cliClients[path] = geminiWebClient
163
+ successfulAuthCount++
164
+ }
165
  }
166
  }
167
  return nil
 
186
  allClients := clientsToSlice(cliClients)
187
  allClients = append(allClients, clientsToSlice(apiKeyClients)...)
188
 
189
+ // Initialize activeClients map for shutdown persistence
190
+ {
191
+ combined := make(map[string]interfaces.Client, len(cliClients)+len(apiKeyClients))
192
+ for k, v := range cliClients {
193
+ combined[k] = v
194
+ }
195
+ for k, v := range apiKeyClients {
196
+ combined[k] = v
197
+ }
198
+ activeClientsMu.Lock()
199
+ activeClients = combined
200
+ activeClientsMu.Unlock()
201
+ }
202
+
203
  // Create and start the API server with the pool of clients in a separate goroutine.
204
  apiServer := api.NewServer(cfg, allClients, configPath)
205
  log.Infof("Starting API server on port %d", cfg.Port)
 
219
  fileWatcher, errNewWatcher := watcher.NewWatcher(configPath, cfg.AuthDir, func(newClients map[string]interfaces.Client, newCfg *config.Config) {
220
  // Update the API server with new clients and configuration when files change.
221
  apiServer.UpdateClients(newClients, newCfg)
222
+ // Keep an up-to-date snapshot for graceful shutdown persistence.
223
+ activeClientsMu.Lock()
224
+ activeClients = newClients
225
+ activeClientsMu.Unlock()
226
  })
227
  if errNewWatcher != nil {
228
  log.Fatalf("failed to create file watcher: %v", errNewWatcher)
 
325
  cancelRefresh()
326
  wgRefresh.Wait()
327
 
328
+ // Stop file watcher early to avoid token save triggering reloads/registrations during shutdown.
329
+ watcherCancel()
330
+ if errStopWatcher := fileWatcher.Stop(); errStopWatcher != nil {
331
+ log.Errorf("error stopping file watcher: %v", errStopWatcher)
332
+ }
333
+
334
  // Create a context with a timeout for the shutdown process.
335
  ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
336
  _ = cancel
337
 
338
+ // Persist tokens/cookies for all active clients before stopping services.
339
+ func() {
340
+ activeClientsMu.RLock()
341
+ snapshot := make([]interfaces.Client, 0, len(activeClients))
342
+ for _, c := range activeClients {
343
+ snapshot = append(snapshot, c)
344
+ }
345
+ activeClientsMu.RUnlock()
346
+ for _, c := range snapshot {
347
+ // Persist tokens/cookies then unregister/cleanup per client.
348
+ _ = c.SaveTokenToFile()
349
+ if u, ok := any(c).(interface{ UnregisterClient() }); ok {
350
+ u.UnregisterClient()
351
+ }
352
+ }
353
+ }()
354
+
355
  // Stop the API server gracefully.
356
  if err = apiServer.Stop(ctx); err != nil {
357
  log.Debugf("Error stopping API server: %v", err)
internal/config/config.go CHANGED
@@ -58,6 +58,37 @@ type Config struct {
58
 
59
  // RemoteManagement nests management-related options under 'remote-management'.
60
  RemoteManagement RemoteManagement `yaml:"remote-management" json:"-"`
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  }
62
 
63
  // RemoteManagement holds management API configuration under 'remote-management'.
@@ -145,6 +176,8 @@ func LoadConfig(configFile string) (*Config, error) {
145
 
146
  // Unmarshal the YAML data into the Config struct.
147
  var config Config
 
 
148
  if err = yaml.Unmarshal(data, &config); err != nil {
149
  return nil, fmt.Errorf("failed to parse config file: %w", err)
150
  }
 
58
 
59
  // RemoteManagement nests management-related options under 'remote-management'.
60
  RemoteManagement RemoteManagement `yaml:"remote-management" json:"-"`
61
+
62
+ // GeminiWeb groups configuration for Gemini Web client
63
+ GeminiWeb GeminiWebConfig `yaml:"gemini-web" json:"gemini-web"`
64
+ }
65
+
66
+ // GeminiWebConfig nests Gemini Web related options under 'gemini-web'.
67
+ type GeminiWebConfig struct {
68
+ // Context enables JSON-based conversation reuse.
69
+ // Defaults to true if not set in YAML (see LoadConfig).
70
+ Context bool `yaml:"context" json:"context"`
71
+
72
+ // CodeMode, when true, enables coding mode behaviors for Gemini Web:
73
+ // - Attach the predefined "Coding partner" Gem
74
+ // - Enable XML wrapping hint for tool markup
75
+ // - Merge <think> content into visible content for tool-friendly output
76
+ CodeMode bool `yaml:"code-mode" json:"code-mode"`
77
+
78
+ // MaxCharsPerRequest caps the number of characters (runes) sent to
79
+ // Gemini Web in a single request. Long prompts will be split into
80
+ // multiple requests with a continuation hint, and only the final
81
+ // request will carry any files. When unset or <=0, a conservative
82
+ // default of 1,000,000 will be used.
83
+ MaxCharsPerRequest int `yaml:"max-chars-per-request" json:"max-chars-per-request"`
84
+
85
+ // DisableContinuationHint, when true, disables the continuation hint for split prompts.
86
+ // The hint is enabled by default.
87
+ DisableContinuationHint bool `yaml:"disable-continuation-hint,omitempty" json:"disable-continuation-hint,omitempty"`
88
+
89
+ // TokenRefreshSeconds controls the background cookie auto-refresh interval in seconds.
90
+ // When unset or <= 0, defaults to 540 seconds.
91
+ TokenRefreshSeconds int `yaml:"token-refresh-seconds" json:"token-refresh-seconds"`
92
  }
93
 
94
  // RemoteManagement holds management API configuration under 'remote-management'.
 
176
 
177
  // Unmarshal the YAML data into the Config struct.
178
  var config Config
179
+ // Set defaults before unmarshal so that absent keys keep defaults.
180
+ config.GeminiWeb.Context = true
181
  if err = yaml.Unmarshal(data, &config); err != nil {
182
  return nil, fmt.Errorf("failed to parse config file: %w", err)
183
  }
internal/watcher/watcher.go CHANGED
@@ -227,6 +227,21 @@ func (w *Watcher) reloadConfig() bool {
227
  if oldConfig.RequestRetry != newConfig.RequestRetry {
228
  log.Debugf(" request-retry: %d -> %d", oldConfig.RequestRetry, newConfig.RequestRetry)
229
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
  if len(oldConfig.APIKeys) != len(newConfig.APIKeys) {
231
  log.Debugf(" api-keys count: %d -> %d", len(oldConfig.APIKeys), len(newConfig.APIKeys))
232
  }
@@ -376,6 +391,11 @@ func (w *Watcher) createClientFromFile(path string, cfg *config.Config) (interfa
376
  if err = json.Unmarshal(data, &ts); err == nil {
377
  return client.NewQwenClient(cfg, &ts), nil
378
  }
 
 
 
 
 
379
  }
380
 
381
  return nil, err
 
227
  if oldConfig.RequestRetry != newConfig.RequestRetry {
228
  log.Debugf(" request-retry: %d -> %d", oldConfig.RequestRetry, newConfig.RequestRetry)
229
  }
230
+ if oldConfig.GeminiWeb.Context != newConfig.GeminiWeb.Context {
231
+ log.Debugf(" gemini-web.context: %t -> %t", oldConfig.GeminiWeb.Context, newConfig.GeminiWeb.Context)
232
+ }
233
+ if oldConfig.GeminiWeb.MaxCharsPerRequest != newConfig.GeminiWeb.MaxCharsPerRequest {
234
+ log.Debugf(" gemini-web.max-chars-per-request: %d -> %d", oldConfig.GeminiWeb.MaxCharsPerRequest, newConfig.GeminiWeb.MaxCharsPerRequest)
235
+ }
236
+ if oldConfig.GeminiWeb.DisableContinuationHint != newConfig.GeminiWeb.DisableContinuationHint {
237
+ log.Debugf(" gemini-web.disable-continuation-hint: %t -> %t", oldConfig.GeminiWeb.DisableContinuationHint, newConfig.GeminiWeb.DisableContinuationHint)
238
+ }
239
+ if oldConfig.GeminiWeb.TokenRefreshSeconds != newConfig.GeminiWeb.TokenRefreshSeconds {
240
+ log.Debugf(" gemini-web.token-refresh-seconds: %d -> %d", oldConfig.GeminiWeb.TokenRefreshSeconds, newConfig.GeminiWeb.TokenRefreshSeconds)
241
+ }
242
+ if oldConfig.GeminiWeb.CodeMode != newConfig.GeminiWeb.CodeMode {
243
+ log.Debugf(" gemini-web.code-mode: %t -> %t", oldConfig.GeminiWeb.CodeMode, newConfig.GeminiWeb.CodeMode)
244
+ }
245
  if len(oldConfig.APIKeys) != len(newConfig.APIKeys) {
246
  log.Debugf(" api-keys count: %d -> %d", len(oldConfig.APIKeys), len(newConfig.APIKeys))
247
  }
 
391
  if err = json.Unmarshal(data, &ts); err == nil {
392
  return client.NewQwenClient(cfg, &ts), nil
393
  }
394
+ } else if tokenType == "gemini-web" {
395
+ var ts gemini.GeminiWebTokenStorage
396
+ if err = json.Unmarshal(data, &ts); err == nil {
397
+ return client.NewGeminiWebClient(cfg, &ts, path)
398
+ }
399
  }
400
 
401
  return nil, err