Repository navigation
Expand file tree
/
Copy pathtui.py
More file actions
540 lines (472 loc) · 22.5 KB
/
Copy pathtui.py
File metadata and controls
540 lines (472 loc) · 22.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
# SPDX-License-Identifier: GPL-3.0-or-later
"""Codex Keeper - Minimal stdlib curses TUI for GPT-6 responses monitoring."""
import argparse
import curses
import json
import queue
import sys
import threading
import time
import unicodedata
from client import MODEL, prepare_request, request_once, request_with_retry, Result
PRICING_NOTE = "参考估算(非账单): 输入 $10 · 缓存 $1 · 输出 $50 / 百万 tokens"
def char_width(c: str) -> int:
return 2 if unicodedata.east_asian_width(c) in ("F", "W") else 1
def str_width(s: str) -> int:
return sum(char_width(c) for c in s)
def truncate_str(s: str, max_w: int) -> str:
if max_w <= 0:
return ""
cur, res = 0, []
for c in s:
w = char_width(c)
if cur + w > max_w:
break
res.append(c)
cur += w
return "".join(res)
def clean_text(s: str) -> str:
return "".join(" " if ord(c) < 32 or 127 <= ord(c) <= 159 else c for c in s)
def safe_addstr(win, y: int, x: int, text: str, max_w: int = 0, attr: int = 0):
try:
my, mx = win.getmaxyx()
if not (0 <= y < my and 0 <= x < mx):
return
avail = mx - x
if max_w > 0:
avail = min(avail, max_w)
if avail <= 0:
return
clipped = truncate_str(text, avail)
if y == my - 1 and str_width(clipped) >= (mx - x):
clipped = truncate_str(clipped, mx - x - 1)
if clipped:
win.addstr(y, x, clipped, attr)
except curses.error:
pass
class CodexTUI:
def __init__(self, mode: str = "keeper"):
self.mode = mode
self.phase = "keeper" if mode == "keeper" else "probe"
self.prepared = prepare_request() if self.phase == "probe" else None
self.probe_prompt = json.loads(self.prepared[1])["input"][0]["content"][0]["text"] if self.prepared else ""
self.probe_done = False
self.handoff_pending = False
self.key: str = ""
self.interval: int = 1 if self.phase == "probe" else 120
self.countdown: float = float(self.interval)
self.paused: bool = False
self.is_requesting: bool = False
self.request_start_time: float = 0.0
self.history: list[Result] = []
self.selected_idx: int = 0
self.queue: queue.Queue[list[Result]] = queue.Queue()
# Cumulative session reference cost
self.session_cost: float = 0.0
self.known_cost_count: int = 0
self.missing_cost_count: int = 0
# Settings state: 0: Key, 1: Interval
self.settings_open: bool = True
self.is_first_setup: bool = True
self.settings_focus: int = 0
self.edit_key: str = ""
self.edit_interval: str = str(self.interval)
self.notice_msg: str = "请输入 API Key (按 Tab 切换到间隔,Enter 启动)"
self.notice_is_error: bool = False
self.log_warning: str = ""
self.has_colors: bool = False
def get_cost_summary(self) -> str:
if self.known_cost_count == 0:
return "未知"
if self.missing_cost_count > 0:
return f"${self.session_cost:.5f} (部分)"
return f"${self.session_cost:.5f}"
def trigger_request(self):
if self.probe_done or self.is_requesting or not self.key:
return
if self.handoff_pending and (self.paused or self.settings_open):
return
self.handoff_pending = False
self.is_requesting = True
self.request_start_time = time.monotonic()
threading.Thread(
target=lambda k: self.queue.put(
[request_once(k, prepared=self.prepared)] if self.phase == "probe" else request_with_retry(k)
),
args=(self.key,),
daemon=True,
).start()
def process_results(self, batch: list[Result]):
self.log_warning = ""
for res in batch:
self.log_warning = getattr(res, "log_error", "") or self.log_warning
self.history.append(res)
if len(self.history) > 20:
self.history.pop(0)
if res.cost_usd is not None:
self.session_cost += res.cost_usd
self.known_cost_count += 1
else:
self.missing_cost_count += 1
self.notice_msg = f"完成: {'成功' if res.success else '失败'}"
self.notice_is_error = not res.success
if self.phase == "probe" and res.http_status == 200:
if self.mode == "auto":
self.phase = "keeper"
self.interval = 120
self.edit_interval = "120"
self.handoff_pending = True
self.notice_msg = "HTTP 200,已转入保活"
else:
self.probe_done = True
self.is_requesting = False
self.selected_idx = len(self.history) - 1
self.countdown = 0.0 if self.handoff_pending else float(self.interval)
def advance_time(self, dt: float):
if not self.probe_done and not self.paused and not self.is_requesting and not self.settings_open and not self.is_first_setup:
self.countdown -= dt
if self.countdown <= 0:
self.countdown = float(self.interval)
self.trigger_request()
def run(self, stdscr):
curses.curs_set(0)
stdscr.timeout(100)
try:
if curses.has_colors():
curses.start_color()
curses.use_default_colors()
curses.init_pair(1, curses.COLOR_GREEN, -1) # Success
curses.init_pair(2, curses.COLOR_RED, -1) # Error
curses.init_pair(3, curses.COLOR_CYAN, -1) # Accent
curses.init_pair(4, curses.COLOR_YELLOW, -1) # Warning / Status
self.has_colors = True
except curses.error:
self.has_colors = False
last_time = time.monotonic()
while True:
# Poll worker results
processed = False
try:
while True:
self.process_results(self.queue.get_nowait())
processed = True
except queue.Empty:
pass
now = time.monotonic()
dt = 0.0 if processed else now - last_time
last_time = now
self.advance_time(dt)
stdscr.erase()
my, mx = stdscr.getmaxyx()
if my < 12 or mx < 45:
msg = f"窗口过小 ({mx}x{my}),请放大终端"
safe_addstr(stdscr, my // 2, max(0, (mx - str_width(msg)) // 2), msg, mx, curses.A_BOLD)
else:
self.draw_ui(stdscr, my, mx)
stdscr.refresh()
try:
ch = stdscr.getch()
except curses.error:
continue
if ch in (-1, curses.KEY_RESIZE):
continue
if (self.handle_settings_input(ch) if self.settings_open else self.handle_main_input(ch)):
break
def handle_settings_input(self, ch: int) -> bool:
if ch in (9, curses.KEY_DOWN, curses.KEY_UP): # Tab / Arrow toggle
self.settings_focus = 1 - self.settings_focus
elif ch == 27: # Esc
if self.is_first_setup:
return True
self.settings_open = False
self.notice_msg = "已取消修改"
self.notice_is_error = False
elif ch in (10, 13, curses.KEY_ENTER):
k = self.edit_key.strip()
if not k:
self.notice_msg = "错误: API Key 不能为空 (按 Tab 切换)"
self.notice_is_error = True
self.settings_focus = 0
return False
try:
v = int(self.edit_interval.strip())
if not 1 <= v <= 86400:
raise ValueError
except ValueError:
self.notice_msg = "错误: 间隔需在 1-86400 秒之间 (按 Tab 切换)"
self.notice_is_error = True
self.settings_focus = 1
return False
self.key, self.interval = k, v
self.countdown = 0.0 if self.handoff_pending else float(self.interval)
self.settings_open = False
self.notice_is_error = False
if self.is_first_setup:
self.is_first_setup = False
self.notice_msg = "启动中..."
self.trigger_request()
else:
self.notice_msg = "设置已保存"
elif ch in (curses.KEY_BACKSPACE, 127, 8):
if self.settings_focus == 0 and self.edit_key:
self.edit_key = self.edit_key[:-1]
elif self.settings_focus == 1 and self.edit_interval:
self.edit_interval = self.edit_interval[:-1]
elif 32 <= ch <= 126:
if self.settings_focus == 0 and len(self.edit_key) < 128:
self.edit_key += chr(ch)
elif self.settings_focus == 1 and chr(ch).isdigit() and len(self.edit_interval) < 5:
self.edit_interval += chr(ch)
return False
def handle_main_input(self, ch: int) -> bool:
if ch in (ord('q'), ord('Q')):
return True
elif ch in (ord('s'), ord('S')):
self.settings_open = True
self.settings_focus = 0
self.edit_key, self.edit_interval = self.key, str(self.interval)
self.notice_msg = "按 Tab 切换输入框,Enter 保存,Esc 取消"
self.notice_is_error = False
elif self.probe_done and ch in (ord('p'), ord('P'), ord('r'), ord('R')):
self.notice_msg = "HTTP 200 后已停止,请重新启动程序以再次探测"
self.notice_is_error = False
elif ch in (ord('p'), ord('P')):
self.paused = not self.paused
self.notice_msg = "已暂停倒计时" if self.paused else "已恢复倒计时"
self.notice_is_error = False
elif ch in (ord('r'), ord('R')):
if self.is_requesting:
self.notice_msg = "正在请求中,请稍候"
self.notice_is_error = False
else:
self.notice_msg = "立即触发请求..."
self.notice_is_error = False
self.trigger_request()
elif ch == curses.KEY_UP and self.history:
self.selected_idx = max(0, self.selected_idx - 1)
elif ch == curses.KEY_DOWN and self.history:
self.selected_idx = min(len(self.history) - 1, self.selected_idx + 1)
return False
def draw_ui(self, win, my: int, mx: int):
c_green = curses.color_pair(1) if self.has_colors else curses.A_BOLD
c_red = curses.color_pair(2) if self.has_colors else curses.A_BOLD
c_cyan = curses.color_pair(3) if self.has_colors else curses.A_BOLD
c_yellow = curses.color_pair(4) if self.has_colors else curses.A_BOLD
# Status indicator
if self.probe_done:
st_text, st_attr = "[已停止 HTTP 200]", c_green
elif self.is_first_setup:
st_text, st_attr = "[等待配置]", c_cyan
elif self.is_requesting:
label = "探测中" if self.phase == "probe" else "请求中"
st_text, st_attr = f"[{label} {time.monotonic() - self.request_start_time:.1f}s]", c_yellow | curses.A_BOLD
elif self.paused:
st_text, st_attr = "[已暂停]", c_yellow
else:
label = "重试倒计时" if self.phase == "probe" else "倒计时"
st_text, st_attr = f"[{label} {max(0, int(self.countdown))}s]", c_green
# Line 0: Header
cost_sum = self.get_cost_summary()
if mx >= 80:
safe_addstr(win, 0, 0, "Codex Probe" if self.phase == "probe" else "Codex Keeper", mx, curses.A_BOLD)
safe_addstr(win, 0, 14, f"· {MODEL}", mx - 14, curses.A_DIM)
safe_addstr(win, 0, 32, f"· {st_text}", mx - 32, st_attr)
cost_line = f"· 参考: {cost_sum}"
safe_addstr(win, 0, max(50, mx - str_width(cost_line)), cost_line, mx, 0)
shortcuts = "[S] 设置 [P] 暂停/继续 [R] 立即请求 [↑/↓] 浏览记录 [Q] 退出"
else:
name = "Probe" if self.phase == "probe" else "Codex"
safe_addstr(win, 0, 0, f"{name} · {st_text} · 参考:{cost_sum}", mx, curses.A_BOLD)
shortcuts = "[S]设置 [P]暂停 [R]请求 [↑/↓]浏览 [Q]退出"
# Line 1: Pricing Note
pricing_text = PRICING_NOTE if mx >= 70 else "参考估算: 输入 $10 · 缓存 $1 · 输出 $50 / 百万 tokens"
safe_addstr(win, 1, 0, pricing_text, mx, curses.A_DIM)
# Line 2: Logging warning or shortcuts
if self.log_warning:
safe_addstr(win, 2, 0, self.log_warning, mx, c_red | curses.A_BOLD)
else:
safe_addstr(win, 2, 0, shortcuts, mx, c_cyan)
# Settings overlay or divider line
top_y = self.draw_settings_dialog(win, mx, 3) if self.settings_open else 4
if not self.settings_open:
safe_addstr(win, 3, 0, "─" * mx, mx, curses.A_DIM)
body_h = my - top_y
if body_h < 4:
return
if mx >= 80:
left_w = mx // 2
right_w = mx - left_w - 1
self.draw_outputs_panel(win, top_y, 0, body_h, left_w)
for y in range(top_y, my):
safe_addstr(win, y, left_w, "│", 1, curses.A_DIM)
self.draw_history_panel(win, top_y, left_w + 1, body_h, right_w)
else:
hist_h = min(8, body_h // 2)
self.draw_history_panel(win, top_y, 0, hist_h, mx)
safe_addstr(win, top_y + hist_h, 0, "─" * mx, mx, curses.A_DIM)
self.draw_outputs_panel(win, top_y + hist_h + 1, 0, body_h - hist_h - 1, mx)
def draw_settings_dialog(self, win, mx: int, y: int) -> int:
c_red = curses.color_pair(2) if self.has_colors else curses.A_BOLD
c_cyan = curses.color_pair(3) if self.has_colors else curses.A_BOLD
title = "─[ 设置 (API Key 仅内存留存,回车确认) ]"
safe_addstr(win, y, 0, "┌" + title + "─" * max(0, mx - 2 - str_width(title)) + "┐", mx, c_cyan)
# Draw interior rows with clean borders
for r in range(1, 5):
safe_addstr(win, y + r, 0, "│" + " " * max(0, mx - 2) + "│", mx, 0)
safe_addstr(win, y + r, 0, "│", 1, c_cyan)
safe_addstr(win, y + r, mx - 1, "│", 1, c_cyan)
# API Key field
f0 = (self.settings_focus == 0)
k_mask = "*" * len(self.edit_key) + ("_" if f0 else "")
ptr0 = "▸" if f0 else " "
safe_addstr(win, y + 1, 3, f"{ptr0} API Key: [ ", mx - 4, c_cyan if f0 else 0)
safe_addstr(win, y + 1, 18, k_mask, mx - 34, curses.A_BOLD if f0 else 0)
safe_addstr(win, y + 1, max(19, mx - 15), " ] (仅内存)", 13, c_cyan if f0 else 0)
# Interval field
f1 = (self.settings_focus == 1)
i_val = self.edit_interval + ("_" if f1 else "")
ptr1 = "▸" if f1 else " "
safe_addstr(win, y + 2, 3, f"{ptr1} 请求间隔: [ ", mx - 4, c_cyan if f1 else 0)
safe_addstr(win, y + 2, 18, i_val, 8, curses.A_BOLD if f1 else 0)
safe_addstr(win, y + 2, 27, " ] 秒 (1-86400)", 16, c_cyan if f1 else 0)
# Action instructions
if mx >= 70:
ctrl_hint = "[Tab] 切换输入 [Enter] 确认启动 [Esc] 退出" if self.is_first_setup else "[Tab] 切换输入 [Enter] 保存设置 [Esc] 取消"
else:
ctrl_hint = "[Tab]切换 [Enter]确认 [Esc]退出" if self.is_first_setup else "[Tab]切换 [Enter]保存 [Esc]取消"
safe_addstr(win, y + 3, 5, f"操作: {ctrl_hint}", mx - 6, 0)
# Status / Notice message
notice_attr = (c_red | curses.A_BOLD) if self.notice_is_error else curses.A_DIM
safe_addstr(win, y + 4, 5, f"提示: {self.notice_msg}", mx - 6, notice_attr)
safe_addstr(win, y + 5, 0, "└" + "─" * (mx - 2) + "┘", mx, c_cyan)
return y + 6
def draw_outputs_panel(self, win, y: int, x: int, h: int, w: int):
c_green = curses.color_pair(1) if self.has_colors else curses.A_BOLD
c_red = curses.color_pair(2) if self.has_colors else curses.A_BOLD
c_cyan = curses.color_pair(3) if self.has_colors else curses.A_BOLD
if self.phase == "probe":
safe_addstr(win, y, x, "【当前探测】", w, curses.A_BOLD)
body, body_attr = "等待首次请求...", curses.A_DIM
if self.is_requesting:
body = "等待当前响应..."
elif self.history:
latest = self.history[-1]
body = latest.text if latest.success else f"错误: {latest.error or '请求失败'}"
body_attr = c_green if latest.success else c_red
if h < 3 or w <= 4:
return
safe_addstr(win, y + 1, x, "固定提示词", w, curses.A_BOLD)
remaining, row = self.probe_prompt, 2
# Wrap only the prompt, reserving the existing two response rows.
while remaining and row < 2 + max(1, h - 4):
line = truncate_str(remaining, w - 4)
if not line:
break
safe_addstr(win, y + row, x + 4, line, w - 4, c_cyan)
remaining = remaining[len(line):]
row += 1
if row < h:
safe_addstr(win, y + row, x, "当前响应", w, curses.A_BOLD)
if row + 1 < h:
safe_addstr(win, y + row + 1, x + 4, body, w - 4, body_attr)
return
safe_addstr(win, y, x, "【最新诗句输出】", w, curses.A_BOLD)
if not self.history:
safe_addstr(win, y + 2, x + 2, "等待首次请求...", w - 2, curses.A_DIM)
return
# Each output takes 2 lines: header + poem/error
max_items = (h - 1) // 2
if max_items <= 0:
return
# Keep selected record in view, showing recent window
start_idx = max(0, min(self.selected_idx - max_items // 2, len(self.history) - max_items))
recent = self.history[start_idx:start_idx + max_items]
curr_y = y + 1
for i, r in enumerate(recent):
actual_idx = start_idx + i
is_sel = (actual_idx == self.selected_idx)
ptr = "▸" if is_sel else " "
poet = getattr(r, "poet", "").strip()
if r.success:
tag = f"[{poet}]" if poet else "[成功]"
tag_attr = (c_cyan | curses.A_BOLD) if poet else c_green
else:
code_str = f"HTTP {r.http_status}" if r.http_status is not None else "无响应"
tag = f"[{poet} · {code_str}]" if poet else f"[{code_str}]"
tag_attr = c_red | curses.A_BOLD
# Line 1: Pointer, Index, Timestamp, Poet/Status
hdr_left = f"{ptr} #{actual_idx+1:02d} {r.timestamp} "
safe_addstr(win, curr_y, x, hdr_left, w, curses.A_BOLD if is_sel else 0)
safe_addstr(win, curr_y, x + str_width(hdr_left), tag, w - str_width(hdr_left), tag_attr)
# Line 2: Content (poem or actual error text)
if r.success:
body = clean_text(r.text if r.text else "无输出")
body_attr = curses.A_BOLD if is_sel else 0
else:
body = f"错误: {clean_text(r.error if r.error else '请求失败')}"
body_attr = c_red # Clearly readable, not dim!
safe_addstr(win, curr_y + 1, x + 4, body, w - 4, body_attr)
curr_y += 2
def draw_history_panel(self, win, y: int, x: int, h: int, w: int):
c_green = curses.color_pair(1) if self.has_colors else curses.A_BOLD
c_red = curses.color_pair(2) if self.has_colors else curses.A_BOLD
title = f"【请求记录】 ({len(self.history)}/20)"
safe_addstr(win, y, x, title, w, curses.A_BOLD)
if not self.history:
safe_addstr(win, y + 2, x + 2, "暂无请求记录", w - 2, curses.A_DIM)
return
item_lines = 3 if w < 48 else 2
fits = (h - 1) // item_lines
if fits <= 0:
return
start = max(0, min(self.selected_idx - fits // 2, len(self.history) - fits))
curr_y = y + 1
for i in range(start, min(len(self.history), start + fits)):
r = self.history[i]
sel = (i == self.selected_idx)
ptr = "▸" if sel else " "
code = str(r.http_status) if r.http_status is not None else "无"
stat = f"[{'成功' if r.success else '失败'} {code}]"
cost = f"${r.cost_usd:.5f}" if r.cost_usd is not None else "未知"
stat_attr = (c_green | (curses.A_BOLD if sel else 0)) if r.success else (c_red | (curses.A_BOLD if sel else 0))
# Line 1: Pointer, Index, Stat, Elapsed, Cost
line1_prefix = f"{ptr} #{i+1:02d} "
safe_addstr(win, curr_y, x, line1_prefix, w, curses.A_BOLD if sel else 0)
prefix_w = str_width(line1_prefix)
safe_addstr(win, curr_y, x + prefix_w, stat, w - prefix_w, stat_attr)
stat_w = str_width(stat)
meta = f" {r.elapsed_s:.1f}s {cost}"
safe_addstr(win, curr_y, x + prefix_w + stat_w, meta, w - prefix_w - stat_w, curses.A_BOLD if sel else 0)
# Token rows
attr_tok = 0 if sel else curses.A_DIM
if w < 48:
if r.usage:
u = r.usage
l2 = f" 入: {u.input_tokens:<7} 缓: {u.cached_input_tokens:<7}"
l3 = f" 出: {u.output_tokens:<7} 总: {u.total_tokens:<7}"
else:
l2 = " Tokens: 未知"
l3 = ""
safe_addstr(win, curr_y + 1, x, l2, w, attr_tok)
if l3:
safe_addstr(win, curr_y + 2, x, l3, w, attr_tok)
else:
if r.usage:
u = r.usage
t_str = f"Tokens: 入:{u.input_tokens} 缓:{u.cached_input_tokens} 出:{u.output_tokens} 总:{u.total_tokens}"
else:
t_str = "Tokens: 未知"
safe_addstr(win, curr_y + 1, x + 4, t_str, w - 4, attr_tok)
curr_y += item_lines
def main():
parser = argparse.ArgumentParser(description="Codex Keeper - GPT-6 监控 TUI")
parser.add_argument("--mode", choices=("keeper", "probe", "auto"), default="keeper")
args = parser.parse_args()
app = CodexTUI(mode=args.mode)
try:
curses.wrapper(app.run)
except KeyboardInterrupt:
pass
sys.exit(0)
if __name__ == "__main__":
main()