proxygmn 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
proxygmn/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
proxygmn/cli.py ADDED
@@ -0,0 +1,259 @@
1
+ import sys
2
+ import os
3
+ import shutil
4
+ import subprocess
5
+ import threading
6
+ import time
7
+ import uuid
8
+ from rich.console import Console
9
+ from rich.panel import Panel
10
+ from rich.table import Table
11
+ from rich.prompt import Prompt, Confirm
12
+
13
+ from proxygmn.config import load_config, save_config, find_available_port, validate_api_key
14
+ from proxygmn.onboarding import run_onboarding
15
+ from proxygmn.proxy import run_proxy_server, key_manager
16
+
17
+ console = Console()
18
+
19
+ def mask_key(api_key: str) -> str:
20
+ if len(api_key) > 8:
21
+ return f"{api_key[:6]}...{api_key[-4:]}"
22
+ return "********"
23
+
24
+ def launch_gemini_cli(direct_run: bool = False):
25
+ config = load_config()
26
+ keys = [k for k in config.get("keys", []) if k.get("enabled", True)]
27
+ if not keys:
28
+ console.print("[red]Nenhuma API Key ativa encontrada. Cadastre ao menos uma chave.[/red]")
29
+ if not run_onboarding():
30
+ return
31
+
32
+ port = find_available_port(int(config.get("port", 8787)))
33
+ stop_event = threading.Event()
34
+
35
+ # Start proxy in background thread
36
+ proxy_thread = threading.Thread(target=run_proxy_server, args=(port, stop_event), daemon=True)
37
+ proxy_thread.start()
38
+ time.sleep(0.5) # Give it a moment to bind
39
+
40
+ # Check if 'gemini' CLI tool is available
41
+ gemini_path = shutil.which("gemini")
42
+ if not gemini_path:
43
+ console.print("[yellow]Aviso: O comando 'gemini' não foi encontrado no PATH do sistema.[/yellow]")
44
+ console.print("Tentando executar 'gemini' diretamente mesmo assim...")
45
+ gemini_cmd = "gemini"
46
+ else:
47
+ gemini_cmd = gemini_path
48
+
49
+ env = os.environ.copy()
50
+ env["GOOGLE_GEMINI_BASE_URL"] = f"http://127.0.0.1:{port}"
51
+ env["GEMINI_API_KEY"] = "proxygmn-local"
52
+
53
+ if not direct_run:
54
+ console.print(f"[bold green]✔ Proxy local rodando em http://127.0.0.1:{port}[/bold green]")
55
+ console.print("[bold cyan]Iniciando o Gemini CLI... (Pressione Ctrl+C para sair)[/bold cyan]\n")
56
+
57
+ try:
58
+ subprocess.run([gemini_cmd], env=env)
59
+ except FileNotFoundError:
60
+ console.print(f"[bold red]Erro: O executável do Gemini CLI não pôde ser iniciado.[/bold red]")
61
+ console.print("Certifique-se de que o Google Gemini CLI está instalado no seu ambiente.")
62
+ except KeyboardInterrupt:
63
+ pass
64
+ finally:
65
+ stop_event.set()
66
+ proxy_thread.join(timeout=2.0)
67
+ if not direct_run:
68
+ console.print("\n[dim]Proxy local encerrado com sucesso.[/dim]")
69
+
70
+ def view_and_test_keys():
71
+ config = load_config()
72
+ keys = config.get("keys", [])
73
+ if not keys:
74
+ console.print("[yellow]Nenhuma chave cadastrada.[/yellow]")
75
+ return
76
+
77
+ table = Table(title="Chaves Cadastradas (proxygmn)")
78
+ table.add_column("ID", style="dim")
79
+ table.add_column("Apelido", style="cyan")
80
+ table.add_column("API Key", style="magenta")
81
+ table.add_column("Status", style="green")
82
+ table.add_column("Cooldown", style="yellow")
83
+
84
+ now = time.time()
85
+ for k in keys:
86
+ kid = k["id"]
87
+ label = k["label"]
88
+ masked = mask_key(k["api_key"])
89
+ enabled = "[green]Ativa[/green]" if k.get("enabled", True) else "[red]Desativada[/red]"
90
+
91
+ cooldown_expiry = key_manager.cooldowns.get(kid, 0)
92
+ if now < cooldown_expiry:
93
+ cd_left = int(cooldown_expiry - now)
94
+ cd_status = f"[red]Cooldown ({cd_left}s)[/red]"
95
+ else:
96
+ cd_status = "[green]Pronta[/green]"
97
+
98
+ table.add_row(kid, label, masked, enabled, cd_status)
99
+
100
+ console.print(table)
101
+
102
+ if Confirm.ask("\nDeseja testar a conexão de todas as chaves agora?"):
103
+ for k in keys:
104
+ console.print(f"Testando [cyan]{k['label']}[/cyan] ({mask_key(k['api_key'])})...", end=" ")
105
+ valid, msg = validate_api_key(k['api_key'])
106
+ if valid:
107
+ console.print(f"[bold green]✔ {msg}[/bold green]")
108
+ else:
109
+ console.print(f"[bold red]✖ {msg}[/bold red]")
110
+
111
+ def add_new_key():
112
+ console.print("\n[bold cyan]Adicionar Nova API Key (Google AI Studio)[/bold cyan]")
113
+ api_key = Prompt.ask("Cole a API Key").strip()
114
+ if not api_key:
115
+ console.print("[red]Chave vazia.[/red]")
116
+ return
117
+
118
+ console.print("[dim]Validando chave...[/dim]")
119
+ valid, msg = validate_api_key(api_key)
120
+ if not valid:
121
+ console.print(f"[bold red]✖ {msg}[/bold red]")
122
+ if not Confirm.ask("Deseja salvar mesmo assim?"):
123
+ return
124
+
125
+ label = Prompt.ask("Apelido para a chave", default="Chave Adicional").strip()
126
+ config = load_config()
127
+ new_key = {
128
+ "id": str(uuid.uuid4())[:8],
129
+ "label": label or "Chave Adicional",
130
+ "api_key": api_key,
131
+ "provider": "google_ai_studio",
132
+ "enabled": True
133
+ }
134
+ config["keys"].append(new_key)
135
+
136
+ # Adjust delay automatically
137
+ if len(config["keys"]) >= 2 and config["delay_seconds"] > 0:
138
+ if Confirm.ask("Você tem 2 ou mais chaves. Deseja zerar o delay automático para velocidade máxima (rotação e fallback ativos)?", default=True):
139
+ config["delay_seconds"] = 0.0
140
+
141
+ save_config(config)
142
+ console.print("[bold green]✔ Chave adicionada com sucesso![/bold green]")
143
+
144
+ def manage_keys_toggle_remove():
145
+ config = load_config()
146
+ keys = config.get("keys", [])
147
+ if not keys:
148
+ console.print("[yellow]Nenhuma chave cadastrada.[/yellow]")
149
+ return
150
+
151
+ table = Table(title="Gerenciar Chaves")
152
+ table.add_column("#", style="cyan")
153
+ table.add_column("ID", style="dim")
154
+ table.add_column("Apelido")
155
+ table.add_column("Status")
156
+
157
+ for idx, k in enumerate(keys, 1):
158
+ status = "Ativa" if k.get("enabled", True) else "Desativada"
159
+ table.add_row(str(idx), k["id"], k["label"], status)
160
+
161
+ console.print(table)
162
+ choice = Prompt.ask("Escolha o número da chave para gerenciar (ou 0 para voltar)", default="0")
163
+ if not choice.isdigit() or int(choice) == 0:
164
+ return
165
+
166
+ idx = int(choice) - 1
167
+ if 0 <= idx < len(keys):
168
+ target = keys[idx]
169
+ action = Prompt.ask(
170
+ f"O que deseja fazer com [cyan]{target['label']}[/cyan]?",
171
+ choices=["alternar", "remover", "cancelar"],
172
+ default="alternar"
173
+ )
174
+ if action == "alternar":
175
+ target["enabled"] = not target.get("enabled", True)
176
+ save_config(config)
177
+ console.print("[green]Status alterado com sucesso![/green]")
178
+ elif action == "remover":
179
+ if Confirm.ask(f"Tem certeza que deseja remover '{target['label']}'?"):
180
+ config["keys"].pop(idx)
181
+ save_config(config)
182
+ console.print("[green]Chave removida![/green]")
183
+
184
+ def configure_delay():
185
+ config = load_config()
186
+ current_delay = config.get("delay_seconds", 4.2)
187
+
188
+ console.print(Panel(
189
+ f"[bold]Modo 1 Conta / Ritmo Calmo (Delay Atual: {current_delay}s)[/bold]\n\n"
190
+ "Quando você utiliza apenas uma chave, o Google AI Studio impõe limite rígido de requisições por minuto (RPM).\n"
191
+ "Aumentar o delay insere uma pausa inteligente entre as chamadas para evitar erros HTTP 429,\n"
192
+ "respeitando o teto da sua conta ao custo de maior tempo de execução.\n"
193
+ "Se você possui 2+ chaves, o ideal é 0.0s (rotação e fallback cuidam do limite).",
194
+ title="⚙️ Configuração de Delay",
195
+ border_style="yellow"
196
+ ))
197
+
198
+ new_delay_str = Prompt.ask("Digite o novo delay em segundos (ex: 4.2 ou 0.0)", default=str(current_delay))
199
+ try:
200
+ new_delay = float(new_delay_str)
201
+ if new_delay < 0:
202
+ raise ValueError()
203
+ config["delay_seconds"] = new_delay
204
+ save_config(config)
205
+ console.print(f"[bold green]✔ Delay atualizado para {new_delay}s com sucesso![/bold green]")
206
+ except ValueError:
207
+ console.print("[red]Valor inválido. Insira um número decimal positivo.[/red]")
208
+
209
+ def main():
210
+ if len(sys.argv) > 1 and sys.argv[1] == "run":
211
+ launch_gemini_cli(direct_run=True)
212
+ return
213
+
214
+ config = load_config()
215
+ if not config.get("keys"):
216
+ if not run_onboarding():
217
+ console.print("[red]Nenhuma chave configurada. Encerrando.[/red]")
218
+ return
219
+
220
+ while True:
221
+ console.clear()
222
+ title_panel = Panel(
223
+ "[bold cyan]proxygmn[/bold cyan] — Proxy Local & Gerenciador para Google Gemini CLI\n"
224
+ "[dim]100% Local • Zero Servidores Externos • Zero Telemetria[/dim]",
225
+ border_style="cyan"
226
+ )
227
+ console.print(title_panel)
228
+
229
+ console.print("\n[bold]Menu Principal:[/bold]")
230
+ console.print(" [1] [green]Iniciar Gemini CLI com Proxy ativo[/green]")
231
+ console.print(" [2] [cyan]Consultar chaves cadastradas e testar status[/cyan]")
232
+ console.print(" [3] [yellow]Adicionar nova API Key (Google AI Studio)[/yellow]")
233
+ console.print(" [4] [magenta]Remover ou ativar/desativar API Key[/magenta]")
234
+ console.print(" [5] [blue]Configurar delay entre requisições (Modo Ritmo Calmo)[/blue]")
235
+ console.print(" [0] [red]Sair[/red]\n")
236
+
237
+ choice = Prompt.ask("Escolha uma opção", choices=["0", "1", "2", "3", "4", "5"], default="1")
238
+
239
+ if choice == "0":
240
+ console.print("[cyan]Até logo![/cyan]")
241
+ break
242
+ elif choice == "1":
243
+ launch_gemini_cli(direct_run=False)
244
+ Prompt.ask("\nPressione Enter para voltar ao menu...")
245
+ elif choice == "2":
246
+ view_and_test_keys()
247
+ Prompt.ask("\nPressione Enter para voltar ao menu...")
248
+ elif choice == "3":
249
+ add_new_key()
250
+ Prompt.ask("\nPressione Enter para voltar ao menu...")
251
+ elif choice == "4":
252
+ manage_keys_toggle_remove()
253
+ Prompt.ask("\nPressione Enter para voltar ao menu...")
254
+ elif choice == "5":
255
+ configure_delay()
256
+ Prompt.ask("\nPressione Enter para voltar ao menu...")
257
+
258
+ if __name__ == "__main__":
259
+ main()
proxygmn/config.py ADDED
@@ -0,0 +1,83 @@
1
+ import json
2
+ import os
3
+ import socket
4
+ import urllib.request
5
+ import urllib.error
6
+ from pathlib import Path
7
+
8
+ CONFIG_DIR = Path.home() / ".config" / "proxygmn"
9
+ CONFIG_PATH = CONFIG_DIR / "config.json"
10
+
11
+ DEFAULT_CONFIG = {
12
+ "provider": "google_ai_studio",
13
+ "port": 8787,
14
+ "delay_seconds": 4.2,
15
+ "keys": []
16
+ }
17
+
18
+ def get_config_dir() -> Path:
19
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
20
+ try:
21
+ os.chmod(CONFIG_DIR, 0o700)
22
+ except Exception:
23
+ pass
24
+ return CONFIG_DIR
25
+
26
+ def load_config() -> dict:
27
+ if not CONFIG_PATH.exists():
28
+ return DEFAULT_CONFIG.copy()
29
+ try:
30
+ with open(CONFIG_PATH, "r", encoding="utf-8") as f:
31
+ data = json.load(f)
32
+ # Ensure defaults
33
+ for k, v in DEFAULT_CONFIG.items():
34
+ if k not in data:
35
+ data[k] = v
36
+ return data
37
+ except Exception:
38
+ return DEFAULT_CONFIG.copy()
39
+
40
+ def save_config(config_data: dict) -> None:
41
+ d = get_config_dir()
42
+ if not CONFIG_PATH.exists():
43
+ CONFIG_PATH.touch()
44
+ try:
45
+ os.chmod(CONFIG_PATH, 0o600)
46
+ except Exception:
47
+ pass
48
+ with open(CONFIG_PATH, "w", encoding="utf-8") as f:
49
+ json.dump(config_data, f, indent=2)
50
+ try:
51
+ os.chmod(CONFIG_PATH, 0o600)
52
+ except Exception:
53
+ pass
54
+
55
+ def find_available_port(start_port: int = 8787) -> int:
56
+ port = start_port
57
+ for _ in range(50):
58
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
59
+ try:
60
+ s.bind(("127.0.0.1", port))
61
+ return port
62
+ except OSError:
63
+ port += 1
64
+ return start_port
65
+
66
+ def validate_api_key(api_key: str) -> tuple[bool, str]:
67
+ url = f"https://generativelanguage.googleapis.com/v1beta/models?key={api_key}"
68
+ req = urllib.request.Request(url, headers={"User-Agent": "proxygmn/0.1.0"})
69
+ try:
70
+ with urllib.request.urlopen(req, timeout=10) as response:
71
+ if response.status == 200:
72
+ return True, "Chave válida com sucesso!"
73
+ except urllib.error.HTTPError as e:
74
+ if e.code == 400 or e.code == 403:
75
+ return False, f"Chave inválida ou sem permissão (HTTP {e.code})."
76
+ elif e.code == 429:
77
+ # 429 means rate limit, but the key itself exists and is valid!
78
+ return True, "Chave válida (limite de taxa atingido momentaneamente)."
79
+ else:
80
+ return False, f"Erro HTTP {e.code} ao validar chave."
81
+ except Exception as e:
82
+ return False, f"Erro de conexão ao validar chave: {e}"
83
+ return False, "Falha desconhecida na validação."
proxygmn/onboarding.py ADDED
@@ -0,0 +1,61 @@
1
+ import uuid
2
+ from rich.console import Console
3
+ from rich.panel import Panel
4
+ from rich.prompt import Prompt
5
+ from proxygmn.config import load_config, save_config, validate_api_key
6
+
7
+ console = Console()
8
+
9
+ def run_onboarding() -> bool:
10
+ """Runs the first-time setup onboarding. Returns True if a key was added."""
11
+ console.clear()
12
+
13
+ welcome_text = (
14
+ "[bold cyan]Bem-vindo ao proxygmn![/bold cyan]\n\n"
15
+ "O proxygmn roda [green]100% localmente[/green] no seu computador.\n"
16
+ "• Zero servidores externos intermediários.\n"
17
+ "• Zero telemetria ou coleta de dados.\n"
18
+ "• Soberania total das suas chaves em [yellow]~/.config/proxygmn/config.json[/yellow]."
19
+ )
20
+
21
+ console.print(Panel(welcome_text, title="🚀 Onboarding - Configuração Inicial", border_style="cyan"))
22
+ console.print("\nPara começar, precisamos cadastrar sua primeira API Key do Google AI Studio.\n")
23
+
24
+ while True:
25
+ api_key = Prompt.ask("[bold yellow]Cole sua API Key do Google AI Studio[/bold yellow]").strip()
26
+ if not api_key:
27
+ console.print("[red]A chave não pode estar vazia.[/red]")
28
+ continue
29
+
30
+ console.print("[dim]Validando chave junto à API do Google...[/dim]")
31
+ valid, msg = validate_api_key(api_key)
32
+
33
+ if valid:
34
+ console.print(f"[bold green]✔ {msg}[/bold green]\n")
35
+
36
+ label = Prompt.ask("[cyan]Apelido para esta chave[/cyan]", default="Chave Principal").strip()
37
+
38
+ config = load_config()
39
+ new_key = {
40
+ "id": str(uuid.uuid4())[:8],
41
+ "label": label or "Chave Principal",
42
+ "api_key": api_key,
43
+ "provider": "google_ai_studio",
44
+ "enabled": True
45
+ }
46
+
47
+ config["keys"].append(new_key)
48
+ # If 1 key, default delay is 4.2; if 2+, 0.0
49
+ if len(config["keys"]) == 1:
50
+ config["delay_seconds"] = 4.2
51
+ else:
52
+ config["delay_seconds"] = 0.0
53
+
54
+ save_config(config)
55
+ console.print(f"[bold green]✔ Chave salva com sucesso![/bold green]")
56
+ return True
57
+ else:
58
+ console.print(f"[bold red]✖ {msg}[/bold red]")
59
+ retry = Prompt.ask("Deseja tentar novamente?", choices=["s", "n"], default="s")
60
+ if retry == "n":
61
+ return False
proxygmn/proxy.py ADDED
@@ -0,0 +1,249 @@
1
+ import http.server
2
+ import socketserver
3
+ import threading
4
+ import time
5
+ import urllib.request
6
+ import urllib.error
7
+ import urllib.parse
8
+ import json
9
+ import logging
10
+ from pathlib import Path
11
+ from proxygmn.config import load_config
12
+
13
+ LOG_PATH = Path.home() / ".config" / "proxygmn" / "proxy.log"
14
+
15
+ def setup_logger():
16
+ log_dir = LOG_PATH.parent
17
+ log_dir.mkdir(parents=True, exist_ok=True)
18
+ logger = logging.getLogger("proxygmn")
19
+ logger.setLevel(logging.INFO)
20
+ if not logger.handlers:
21
+ handler = logging.FileHandler(LOG_PATH, encoding="utf-8")
22
+ formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
23
+ handler.setFormatter(formatter)
24
+ logger.addHandler(handler)
25
+ return logger
26
+
27
+ logger = setup_logger()
28
+
29
+ class KeyManager:
30
+ def __init__(self):
31
+ self.lock = threading.Lock()
32
+ self.index = 0
33
+ self.cooldowns = {} # key_id -> float (timestamp until cooldown)
34
+ self.last_used = {} # key_id -> float (timestamp)
35
+ self.refresh()
36
+
37
+ def refresh(self):
38
+ config = load_config()
39
+ self.delay = float(config.get("delay_seconds", 4.2))
40
+ raw_keys = config.get("keys", [])
41
+ self.keys = [k for k in raw_keys if k.get("enabled", True)]
42
+ if self.keys:
43
+ self.index = self.index % len(self.keys)
44
+ else:
45
+ self.index = 0
46
+
47
+ def get_next_key(self):
48
+ with self.lock:
49
+ self.refresh()
50
+ if not self.keys:
51
+ return None
52
+
53
+ now = time.time()
54
+ tried = 0
55
+ n = len(self.keys)
56
+
57
+ while tried < n:
58
+ key_info = self.keys[self.index]
59
+ self.index = (self.index + 1) % n
60
+ tried += 1
61
+
62
+ kid = key_info["id"]
63
+ # Check cooldown
64
+ if now < self.cooldowns.get(kid, 0):
65
+ continue
66
+
67
+ # Rate limiter check for this key
68
+ last = self.last_used.get(kid, 0)
69
+ elapsed = now - last
70
+ if elapsed < self.delay:
71
+ sleep_time = self.delay - elapsed
72
+ logger.info(f"Rate limiting key {kid}: sleeping for {sleep_time:.2f}s")
73
+ time.sleep(sleep_time)
74
+
75
+ self.last_used[kid] = time.time()
76
+ return key_info
77
+
78
+ # If all in cooldown, pick the one with earliest cooldown expiry
79
+ earliest_kid = min(self.keys, key_id=lambda k: self.cooldowns.get(k["id"], 0))
80
+ logger.warning(f"All keys in cooldown. Forcing use of key {earliest_kid['id']}")
81
+ return earliest_kid
82
+
83
+ def report_failure(self, kid, status_code):
84
+ with self.lock:
85
+ cooldown_time = time.time() + 60
86
+ self.cooldowns[kid] = cooldown_time
87
+ logger.error(f"Key {kid} failed with HTTP {status_code}. Placed in cooldown until {cooldown_time}")
88
+
89
+ key_manager = KeyManager()
90
+
91
+ class ProxyHandler(http.server.BaseHTTPRequestHandler):
92
+ def log_message(self, format, *args):
93
+ # Suppress stdout logging completely, use file logger
94
+ logger.info(f"{self.client_address[0]} - {format % args}")
95
+
96
+ def do_POST(self):
97
+ self.handle_request_proxy("POST")
98
+
99
+ def do_GET(self):
100
+ self.handle_request_proxy("GET")
101
+
102
+ def do_OPTIONS(self):
103
+ self.send_response(200)
104
+ self.send_header("Access-Control-Allow-Origin", "*")
105
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
106
+ self.send_header("Access-Control-Allow-Headers", "X-goog-api-key, Content-Type")
107
+ self.end_headers()
108
+
109
+ def handle_request_proxy(self, method):
110
+ parsed_path = urllib.parse.urlparse(self.path)
111
+ path_and_query = parsed_path.path
112
+ if parsed_path.query:
113
+ path_and_query += f"?{parsed_path.query}"
114
+
115
+ content_length = int(self.headers.get('Content-Length', 0))
116
+ body = self.rfile.read(content_length) if content_length > 0 else None
117
+
118
+ # Extract incoming headers
119
+ headers = {}
120
+ for header, value in self.headers.items():
121
+ if header.lower() in ['host', 'content-length', 'transfer-encoding', 'connection']:
122
+ continue
123
+ headers[header] = value
124
+
125
+ max_attempts = max(1, len(key_manager.keys))
126
+ attempt = 0
127
+ resp = None
128
+ target_url = ""
129
+ used_key = None
130
+
131
+ while attempt < max_attempts:
132
+ used_key = key_manager.get_next_key()
133
+ if not used_key:
134
+ self.send_error(503, "No active API keys configured in proxygmn.")
135
+ return
136
+
137
+ api_key = used_key["api_key"]
138
+ kid = used_key["id"]
139
+
140
+ # Construct target URL
141
+ # Google AI Studio base: https://generativelanguage.googleapis.com
142
+ base_url = "https://generativelanguage.googleapis.com"
143
+
144
+ # Inject key into query params or header
145
+ parsed_url = urllib.parse.urlparse(base_url + path_and_query)
146
+ query_params = urllib.parse.parse_qsl(parsed_url.query, keep_blank_values=True)
147
+
148
+ # Update or add key parameter
149
+ new_params = [(k, v) for k, v in query_params if k != 'key']
150
+ new_params.append(('key', api_key))
151
+
152
+ encoded_query = urllib.parse.urlencode(new_params)
153
+ target_url = urllib.parse.urlunparse((
154
+ parsed_url.scheme,
155
+ parsed_url.netloc,
156
+ parsed_url.path,
157
+ parsed_url.params,
158
+ encoded_query,
159
+ parsed_url.fragment
160
+ ))
161
+
162
+ req_headers = headers.copy()
163
+ req_headers["User-Agent"] = "proxygmn-proxy/0.1.0"
164
+ req_headers["x-goog-api-key"] = api_key
165
+
166
+ req = urllib.request.Request(target_url, data=body, headers=req_headers, method=method)
167
+
168
+ try:
169
+ resp = urllib.request.urlopen(req, timeout=120)
170
+ break # Success!
171
+ except urllib.error.HTTPError as e:
172
+ status = e.code
173
+ if status in (429, 503):
174
+ logger.warning(f"Key {kid} hit HTTP {status}. Rotating key...")
175
+ key_manager.report_failure(kid, status)
176
+ attempt += 1
177
+ continue
178
+ else:
179
+ # Non-retryable HTTP error, forward response as is
180
+ self.forward_error_response(e)
181
+ return
182
+ except Exception as e:
183
+ logger.error(f"Network error with key {kid}: {e}")
184
+ key_manager.report_failure(kid, 500)
185
+ attempt += 1
186
+ continue
187
+
188
+ if resp is None:
189
+ self.send_error(503, "All available Gemini API keys exhausted or in cooldown.")
190
+ return
191
+
192
+ # Forward successful response with streaming support
193
+ try:
194
+ self.send_response(resp.status)
195
+ for header, value in resp.headers.items():
196
+ if header.lower() in ['transfer-encoding', 'connection', 'content-length']:
197
+ continue
198
+ self.send_header(header, value)
199
+ self.send_header('Transfer-Encoding', 'chunked')
200
+ self.end_headers()
201
+
202
+ # Stream chunks in real-time
203
+ chunk_size = 4096
204
+ while True:
205
+ chunk = resp.read(chunk_size)
206
+ if not chunk:
207
+ break
208
+ # Write chunk in HTTP chunked transfer encoding format
209
+ self.wfile.write(f"{len(chunk):X}\r\n".encode('utf-8'))
210
+ self.wfile.write(chunk)
211
+ self.wfile.write(b"\r\n")
212
+ self.wfile.flush()
213
+
214
+ # End of chunked transfer
215
+ self.wfile.write(b"0\r\n\r\n")
216
+ self.wfile.flush()
217
+ except Exception as e:
218
+ logger.error(f"Error streaming response: {e}")
219
+ finally:
220
+ resp.close()
221
+
222
+ def forward_error_response(self, e):
223
+ try:
224
+ self.send_response(e.code)
225
+ for header, value in e.headers.items():
226
+ if header.lower() in ['transfer-encoding', 'connection', 'content-length']:
227
+ continue
228
+ self.send_header(header, value)
229
+ body = e.read()
230
+ self.send_header('Content-Length', str(len(body)))
231
+ self.end_headers()
232
+ self.wfile.write(body)
233
+ self.wfile.flush()
234
+ except Exception as ex:
235
+ logger.error(f"Error forwarding error response: {ex}")
236
+
237
+ class ThreadingHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
238
+ daemon_threads = True
239
+
240
+ def run_proxy_server(port: int, stop_event: threading.Event):
241
+ server = ThreadingHTTPServer(("127.0.0.1", port), ProxyHandler)
242
+ logger.info(f"Proxy server started on port {port}")
243
+
244
+ server.timeout = 0.5
245
+ while not stop_event.is_set():
246
+ server.handle_request()
247
+
248
+ server.server_close()
249
+ logger.info("Proxy server stopped.")
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: proxygmn
3
+ Version: 0.1.0
4
+ Summary: Local HTTP proxy and TUI manager for Google Gemini CLI with key rotation, auto-fallback, and rate limiting.
5
+ License: MIT
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: Programming Language :: Python :: 3.10
8
+ Classifier: Programming Language :: Python :: 3.11
9
+ Classifier: Programming Language :: Python :: 3.12
10
+ Classifier: Programming Language :: Python :: 3.13
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: rich>=13.0.0
17
+ Dynamic: license-file
18
+
19
+ # proxygmn
20
+
21
+ [Português](#português) | [English](#english)
22
+
23
+ ---
24
+
25
+ ## Português
26
+
27
+ O **proxygmn** é um proxy HTTP local e gerenciador TUI 100% local para o **Google Gemini CLI**, projetado para garantir soberania total dos seus dados e chaves, sem servidores externos intermediários e sem qualquer telemetria.
28
+
29
+ ### Filosofia 100% Local
30
+ - **Zero Servidores Externos:** Todo o tráfego HTTP é redirecionado diretamente do seu terminal para a API oficial do Google AI Studio (`generativelanguage.googleapis.com`).
31
+ - **Zero Telemetria:** Nenhuma informação sobre uso, prompts ou chaves sai da sua máquina.
32
+ - **Soberania de Dados:** Suas chaves ficam armazenadas estritamente em `~/.config/proxygmn/config.json` com permissão restrita `0600`.
33
+
34
+ ### O Dilema do Rate Limit e a Troca Honesta
35
+ Contas gratuitas do Google AI Studio possuem limites rígidos de requisições por minuto (RPM) — tipicamente 15 RPM.
36
+ - **Com 1 chave:** Para evitar erros `429 (Too Many Requests)`, o `proxygmn` insere um **delay automático inteligente** entre as chamadas (padrão de 4.2 segundos), garantindo estabilidade ao custo de velocidade.
37
+ - **Com 2+ chaves:** O `proxygmn` faz **rotação round-robin** entre as chaves e **fallback automático** (em caso de 429 ou 503, troca de chave instantaneamente sem falhar a requisição), permitindo velocidade máxima sem pausas.
38
+
39
+ ---
40
+
41
+ ## English
42
+
43
+ **proxygmn** is a 100% local HTTP proxy and TUI manager for the **Google Gemini CLI**, built to ensure complete data sovereignty and key privacy, with zero intermediate servers and zero telemetry.
44
+
45
+ ### 100% Local Philosophy
46
+ - **Zero External Servers:** All HTTP traffic is routed directly from your terminal to the official Google AI Studio API (`generativelanguage.googleapis.com`).
47
+ - **Zero Telemetry:** No usage data, prompts, or keys ever leave your machine.
48
+ - **Data Sovereignty:** Your keys are stored securely in `~/.config/proxygmn/config.json` with strict `0600` permissions.
49
+
50
+ ### Rate Limit Dilemma & Honest Trade-Off
51
+ Free tier Google AI Studio accounts have strict Requests Per Minute (RPM) limits — typically 15 RPM.
52
+ - **With 1 key:** To prevent `429 (Too Many Requests)` errors, `proxygmn` enforces an **intelligent automatic delay** between calls (default 4.2s), ensuring stability at the expense of speed.
53
+ - **With 2+ keys:** `proxygmn` performs **round-robin rotation** and **automatic fallback** (instantly switching keys on 429 or 503 without failing the request), enabling maximum speed without pauses.
@@ -0,0 +1,11 @@
1
+ proxygmn/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
2
+ proxygmn/cli.py,sha256=uTYXJxgCqZlOJz50wf7KlX9ymG-Sb7BJYPuHpmaJIF0,9994
3
+ proxygmn/config.py,sha256=Xh0ir7hOGVBaOMK44PIImA8Dt4LYMGxGHCcsUN0--Is,2620
4
+ proxygmn/onboarding.py,sha256=nW8m-vXF2Bce9Kg-G1mUQrwYGe_QhvJtbvP9mIX2eQM,2463
5
+ proxygmn/proxy.py,sha256=t7mKiBvhICekE2zlkf2vUE9uHCeRLNDGU1734KBkZRE,9141
6
+ proxygmn-0.1.0.dist-info/licenses/LICENSE,sha256=3zJrdMtyYeZY8g-n42j_9CRkXUjjVcnaeZz4ZJr3Vrw,54
7
+ proxygmn-0.1.0.dist-info/METADATA,sha256=rj6sYqUzWztyyjCPn0tTdWs0LEocdt5cexWxIxj8Yec,3168
8
+ proxygmn-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ proxygmn-0.1.0.dist-info/entry_points.txt,sha256=m-2hAM5aZOl7WaVi8O1yJRnZumoppea9mM_4i8E2ntY,47
10
+ proxygmn-0.1.0.dist-info/top_level.txt,sha256=Fi5O8US-DbjOGpnEBHFCQD8rjwi0n7lezX7soLC0ZcE,9
11
+ proxygmn-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ proxygmn = proxygmn.cli:main
@@ -0,0 +1 @@
1
+ MIT License - Copyright (c) 2026 Tiago Rabelo da Silva
@@ -0,0 +1 @@
1
+ proxygmn