codex-proxy 3.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.
codex_proxy/tui.py ADDED
@@ -0,0 +1,262 @@
1
+ """Rich TUI dashboard for codex-proxy — live metrics, circuit breaker, log tail."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import platform
7
+ import sys
8
+ import threading
9
+ import time
10
+ from collections import deque
11
+
12
+ from . import __version__
13
+
14
+
15
+ def _check_rich():
16
+ """Import guard — raises with install hint if rich is not available."""
17
+ try:
18
+ import rich # noqa: F401
19
+ except ImportError:
20
+ raise ImportError(
21
+ "Rich is required for TUI mode. Install with: pip install codex-proxy[tui]"
22
+ ) from None
23
+
24
+
25
+ class _RingHandler(logging.Handler):
26
+ """Logging handler that keeps the last N records in a deque."""
27
+
28
+ def __init__(self, capacity: int = 50):
29
+ super().__init__()
30
+ self.records: deque[logging.LogRecord] = deque(maxlen=capacity)
31
+
32
+ def emit(self, record: logging.LogRecord) -> None:
33
+ self.records.append(record)
34
+
35
+
36
+ def _read_key() -> str | None:
37
+ """Non-blocking stdin read. Returns key char or None."""
38
+ if platform.system() == "Windows":
39
+ import msvcrt
40
+ if msvcrt.kbhit():
41
+ return msvcrt.getwch()
42
+ return None
43
+ else:
44
+ import select
45
+ import termios # type: ignore[import-not-found]
46
+ import tty # type: ignore[import-not-found]
47
+
48
+ if not sys.stdin.isatty():
49
+ return None
50
+ fd = sys.stdin.fileno()
51
+ old_settings = termios.tcgetattr(fd) # type: ignore[attr-defined]
52
+ try:
53
+ tty.setcbreak(fd) # type: ignore[attr-defined]
54
+ readable, _, _ = select.select([sys.stdin], [], [], 0)
55
+ if readable:
56
+ return sys.stdin.read(1)
57
+ finally:
58
+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) # type: ignore[attr-defined]
59
+ return None
60
+
61
+
62
+ class Dashboard:
63
+ """Rich Live dashboard rendering proxy state."""
64
+
65
+ def __init__(self, state):
66
+
67
+ self.state = state
68
+ self._log_handler = _RingHandler(50)
69
+ self._log_handler.setLevel(logging.DEBUG)
70
+ logging.getLogger("codex-proxy").addHandler(self._log_handler)
71
+ self._running = False
72
+ self._last_action: str = ""
73
+ self._last_action_time: float = 0.0
74
+
75
+ def _render(self):
76
+ from rich.console import Group
77
+ from rich.panel import Panel
78
+ from rich.table import Table
79
+ from rich.text import Text
80
+
81
+ state = self.state
82
+ now = time.time()
83
+ uptime = int(now - state.start_time)
84
+ hours, remainder = divmod(uptime, 3600)
85
+ mins, secs = divmod(remainder, 60)
86
+
87
+ # Header
88
+ header = Text(
89
+ f" codex-proxy v{__version__} uptime {hours:02d}:{mins:02d}:{secs:02d} ",
90
+ style="bold white on blue",
91
+ )
92
+
93
+ # Provider panel
94
+ prov = state.config.provider
95
+ prov_table = Table(show_header=False, box=None, padding=(0, 1))
96
+ prov_table.add_column("key", style="dim")
97
+ prov_table.add_column("val")
98
+ prov_table.add_row("name", prov.display_name)
99
+ prov_table.add_row("url", prov.base_url)
100
+ prov_table.add_row("model", prov.default_model)
101
+ prov_table.add_row("models", ", ".join(prov.models))
102
+ provider_panel = Panel(prov_table, title="Provider", border_style="cyan")
103
+
104
+ # Circuit breaker panel
105
+ cb = state.circuit_breaker
106
+ if cb:
107
+ cb_status = cb.get_status()
108
+ state_str = cb_status.get("state", "UNKNOWN")
109
+ state_colors = {"closed": "green", "open": "red", "half_open": "yellow"}
110
+ color = state_colors.get(state_str, "white")
111
+
112
+ cb_table = Table(show_header=False, box=None, padding=(0, 1))
113
+ cb_table.add_column("key", style="dim")
114
+ cb_table.add_column("val")
115
+ cb_table.add_row("state", Text(state_str, style=f"bold {color}"))
116
+ cb_table.add_row("failures", str(cb_status.get("failure_count", 0)))
117
+ cb_table.add_row("threshold", str(cb_status.get("failure_threshold", 0)))
118
+ if state_str == "open":
119
+ rec = cb_status.get("recovery_timeout", 30)
120
+ last_fail = cb_status.get("last_failure_time", 0)
121
+ remaining = max(0, rec - (now - last_fail))
122
+ cb_table.add_row("recovery in", f"{remaining:.0f}s")
123
+ else:
124
+ cb_table.add_row("recovery", f"{cb_status.get('recovery_timeout', 0)}s")
125
+ cb_panel = Panel(cb_table, title="Circuit Breaker", border_style=color)
126
+ else:
127
+ cb_panel = Panel(Text("disabled", style="dim"), title="Circuit Breaker",
128
+ border_style="dim")
129
+
130
+ # Metrics panel
131
+ total = state.request_count or 1
132
+ success_rate = (state.success_count / total) * 100 if total > 1 else 0
133
+
134
+ met_table = Table(show_header=False, box=None, padding=(0, 1))
135
+ met_table.add_column("key", style="dim")
136
+ met_table.add_column("val")
137
+ met_table.add_row("requests", str(state.request_count))
138
+ met_table.add_row("success", str(state.success_count))
139
+ met_table.add_row("failures", str(state.failure_count))
140
+ met_table.add_row("success rate", f"{success_rate:.1f}%")
141
+ if state.last_request_time:
142
+ ago = now - state.last_request_time
143
+ met_table.add_row("last req", f"{ago:.1f}s ago")
144
+ else:
145
+ met_table.add_row("last req", "never")
146
+ met_table.add_row("store", f"{state.store.size()}/{state.store.max_entries}")
147
+ if state.plugin_registry:
148
+ met_table.add_row("plugins", ", ".join(state.plugin_registry.list_plugins()))
149
+ metrics_panel = Panel(met_table, title="Metrics", border_style="green")
150
+
151
+ # Key Pool panel
152
+ kr = state.key_rotator
153
+ if kr:
154
+ kp_table = Table(show_header=False, box=None, padding=(0, 1))
155
+ kp_table.add_column("key", style="dim")
156
+ kp_table.add_column("val")
157
+ for ks in kr.get_status():
158
+ state_colors = {"closed": "green", "open": "red", "half_open": "yellow"}
159
+ sc = state_colors.get(ks["state"], "white")
160
+ kp_table.add_row(
161
+ ks["key"],
162
+ Text(ks["state"], style=sc) if ks["errors"] == 0
163
+ else Text(f"{ks['state']} (err:{ks['errors']})", style=sc),
164
+ )
165
+ key_pool_panel = Panel(kp_table, title=f"Key Pool ({len(kr._keys)})",
166
+ border_style="magenta")
167
+ else:
168
+ key_pool_panel = None
169
+
170
+ # Log tail panel
171
+ log_lines = []
172
+ for rec in list(self._log_handler.records)[-10:]:
173
+ level_colors = {"DEBUG": "dim", "INFO": "blue", "WARNING": "yellow",
174
+ "ERROR": "red", "CRITICAL": "bold red"}
175
+ color = level_colors.get(rec.levelname, "")
176
+ ts = time.strftime("%H:%M:%S", time.localtime(rec.created))
177
+ log_lines.append(Text(f" {ts} [{rec.levelname}] {rec.message}",
178
+ style=color))
179
+ log_text = Text("\n").join(log_lines) if log_lines else Text(" (no logs yet)",
180
+ style="dim")
181
+ log_panel = Panel(log_text, title="Logs", border_style="blue",
182
+ height=12)
183
+
184
+ # Hotkeys + action feedback
185
+ hotkeys = Text(" r=reload c=clear store t=compact q=quit",
186
+ style="bold white on black")
187
+ action = Text("")
188
+ if self._last_action and (time.time() - self._last_action_time) < 3.0:
189
+ action = Text(f" >> {self._last_action}", style="bold green")
190
+
191
+ panels = [header, provider_panel, cb_panel, metrics_panel]
192
+ if key_pool_panel:
193
+ panels.append(key_pool_panel)
194
+ panels.extend([log_panel, hotkeys, action])
195
+ return Group(*panels)
196
+
197
+ def _handle_key(self, key: str) -> bool:
198
+ """Handle a hotkey press. Returns True if should quit."""
199
+ if key == "q":
200
+ self._running = False
201
+ return True
202
+ elif key == "r":
203
+ from .server import _state, reload_config_internal
204
+ state = _state()
205
+ try:
206
+ reload_config_internal(state)
207
+ self._last_action = "Config reloaded!"
208
+ self._last_action_time = time.time()
209
+ logging.getLogger("codex-proxy").info("Config and services reloaded via TUI")
210
+ except Exception as e:
211
+ self._last_action = f"Reload FAILED: {e}"
212
+ self._last_action_time = time.time()
213
+ logging.getLogger("codex-proxy").error("Reload failed: %s", e)
214
+ elif key == "c":
215
+ from .server import _state
216
+ state = _state()
217
+ cleared = state.store.size()
218
+ state.store._store.clear()
219
+ self._last_action = f"Store cleared ({cleared} entries removed)"
220
+ self._last_action_time = time.time()
221
+ logging.getLogger("codex-proxy").info("Store cleared via TUI")
222
+ elif key == "t":
223
+ from .server import _state
224
+ state = _state()
225
+ self._last_action = (
226
+ f"Compaction: enabled={state.config.compaction.enabled}, "
227
+ f"max={state.config.compaction.max_messages}, "
228
+ f"keep_last={state.config.compaction.keep_last}"
229
+ )
230
+ self._last_action_time = time.time()
231
+ logging.getLogger("codex-proxy").info(
232
+ "Compaction: enabled=%s, max=%d, keep_last=%d",
233
+ state.config.compaction.enabled,
234
+ state.config.compaction.max_messages,
235
+ state.config.compaction.keep_last,
236
+ )
237
+ return False
238
+
239
+ def run(self) -> None:
240
+ """Main dashboard loop — runs in daemon thread."""
241
+ from rich.live import Live
242
+
243
+ self._running = True
244
+ with Live(self._render(), refresh_per_second=2, screen=True) as live:
245
+ while self._running:
246
+ key = _read_key()
247
+ if key and self._handle_key(key.lower()):
248
+ break
249
+ live.update(self._render())
250
+ time.sleep(0.1)
251
+
252
+ logging.getLogger("codex-proxy").removeHandler(self._log_handler)
253
+
254
+
255
+ def start_tui(state) -> None:
256
+ """Spawn the TUI dashboard in a daemon thread."""
257
+ _check_rich()
258
+
259
+ dashboard = Dashboard(state)
260
+ thread = threading.Thread(target=dashboard.run, daemon=True, name="codex-proxy-tui")
261
+ thread.start()
262
+ logging.getLogger("codex-proxy").info("TUI dashboard started")
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: codex-proxy
3
+ Version: 3.1.0
4
+ Summary: Responses API to Chat Completions bridge for OpenAI Codex CLI
5
+ Project-URL: Repository, https://github.com/ZiryaNoov/codex-proxy
6
+ Author-email: ZakPro <zakarinoo@gmail.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Keywords: chat-completions,codex,glm,openai,proxy,responses-api,z.ai
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Software Development :: Libraries
15
+ Requires-Python: >=3.10
16
+ Requires-Dist: fastapi>=0.115
17
+ Requires-Dist: httpx>=0.27
18
+ Requires-Dist: tomli>=2.0; python_version < '3.11'
19
+ Requires-Dist: uvicorn>=0.30
20
+ Provides-Extra: dev
21
+ Requires-Dist: mypy>=1.13; extra == 'dev'
22
+ Requires-Dist: pytest>=8.0; extra == 'dev'
23
+ Requires-Dist: ruff>=0.8; extra == 'dev'
24
+ Provides-Extra: tui
25
+ Requires-Dist: rich>=13.0; extra == 'tui'
@@ -0,0 +1,18 @@
1
+ codex_proxy/__init__.py,sha256=TKstav6h7eDAd9KBaEaMdZ7zJhbi-PM1US2KOmBXErU,101
2
+ codex_proxy/__main__.py,sha256=RhRr-gMXJFJvUY7orau_wM_jdGzbxG4m2alJ0QRS68w,2760
3
+ codex_proxy/circuit_breaker.py,sha256=3p_Clf9UvjoApAyLj3O0jiOGP9BQwVLHOuPdbX_miTg,2789
4
+ codex_proxy/compaction.py,sha256=FwmJ9lQgP-tV9wRX4UxJaqr470ng4uuYfCmMFPBbP-o,1212
5
+ codex_proxy/config.py,sha256=mDDe-rssYB34rP_4G7oFnsFr8IzEBKhuY26Sf5Pg6JI,9905
6
+ codex_proxy/key_rotation.py,sha256=y8ZUE1tNJFSh8amWPFurk00De2KfeCJY4_MTc0EOAPU,3307
7
+ codex_proxy/plugins.py,sha256=oclA9xxsUgxFnqK-iqhbRA7EBD4NzhY1hid-pVq8SS0,3357
8
+ codex_proxy/plugins_builtin.py,sha256=z1qhiOJ7jhPkGw85CeSEsfeFs1RHfJN4w8kqDd2LkHw,1023
9
+ codex_proxy/providers.py,sha256=N3s9ThaF1x6A3ZP2z8ydF_Xawx8weuqzrXtJkZTLyUI,3546
10
+ codex_proxy/server.py,sha256=LDFTkp8u6LbAiuLilo_mOsjqX8HGN1EiPT5ZK8zEPFU,25010
11
+ codex_proxy/store.py,sha256=H754uBzBgH5WyjGyhNCpCV9mFxoldesjvpAsDxS6m2o,3525
12
+ codex_proxy/translator.py,sha256=yOQByttW9twCXAv4IXhMPzIV1or8KRFBeJD-ZGYibQs,13814
13
+ codex_proxy/tui.py,sha256=P_CrvIwrFETAA9twdy3yAIJUDkmXLskBjEF4qGEd3MM,10594
14
+ codex_proxy-3.1.0.dist-info/METADATA,sha256=INcRn0ukumPHJIQe0RB4yJJSSwyiGDaba4G-4um2p9c,973
15
+ codex_proxy-3.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
16
+ codex_proxy-3.1.0.dist-info/entry_points.txt,sha256=vQFCHbRMPhUjNMimQwZkTUCvSlafoJiaHvSq5oa-tW4,58
17
+ codex_proxy-3.1.0.dist-info/licenses/LICENSE,sha256=fnOBfz0EP7_EU9F0PCbDbM7g8Rc4GqGfcvHVWNkaOCI,1063
18
+ codex_proxy-3.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ codex-proxy = codex_proxy.__main__:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ZakPro
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.