thuthi-plugin 0.0.0-stage → 0.1.0
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.
- package/.claude-plugin/marketplace.json +55 -0
- package/README.md +13 -2
- package/bin/parallel-browser.js +109 -0
- package/extension/background.js +1329 -0
- package/extension/config.json +1 -0
- package/extension/guard.js +44 -0
- package/extension/manifest.json +10 -0
- package/extension/overlay.js +104 -0
- package/extension/popup.html +34 -0
- package/extension/popup.js +39 -0
- package/extension-reloader/manifest.json +13 -0
- package/extension-reloader/sw.js +17 -0
- package/package.json +13 -4
- package/plugins/thuthi/.claude-plugin/plugin.json +8 -0
- package/plugins/thuthi/context.md +3 -0
- package/plugins/thuthi/hooks/hooks.json +15 -0
- package/plugins/thuthi/skills/setup/SKILL.md +55 -0
- package/plugins/thuthi/skills/setup/scripts/doctor.py +249 -0
- package/plugins/thuthi/skills/setup/scripts/selftest.py +188 -0
- package/plugins/thuthi/tools/claude-switch/claude_switch.py +8 -0
- package/plugins/thuthi/tools/legacy_launcher.py +65 -0
- package/plugins/thuthi/tools/statusline/statusline.py +8 -0
- package/plugins/thuthi-accounts/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-accounts/bin/claude-switch +5 -0
- package/plugins/thuthi-accounts/bin/claude-switch.cmd +4 -0
- package/plugins/thuthi-accounts/hooks/hooks.json +15 -0
- package/plugins/thuthi-accounts/lib/tls.py +68 -0
- package/plugins/thuthi-accounts/lib/usage_store.py +150 -0
- package/plugins/thuthi-accounts/setup_check.py +21 -0
- package/plugins/thuthi-accounts/skills/claude-switch/SKILL.md +48 -0
- package/plugins/thuthi-accounts/tools/claude-switch/claude-switch-tui.py +397 -0
- package/plugins/thuthi-accounts/tools/claude-switch/claude_switch.py +1204 -0
- package/plugins/thuthi-accounts/tools/claude-switch/credstore.py +417 -0
- package/plugins/thuthi-accounts/tools/claude-switch/install.py +301 -0
- package/plugins/thuthi-accounts/tools/claude-switch/tests/selftest.py +491 -0
- package/plugins/thuthi-accounts/tools/statusline/statusline.py +212 -0
- package/plugins/thuthi-agenda-picker/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-agenda-picker/context.md +3 -0
- package/plugins/thuthi-agenda-picker/hooks/hooks.json +15 -0
- package/plugins/thuthi-agenda-picker/lib/pbpage.py +397 -0
- package/plugins/thuthi-agenda-picker/setup_check.py +18 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/SKILL.md +280 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/design-rules.md +110 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/diagram/base.css +33 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/agenda.json +146 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/base.css +33 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/name-B.html +15 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/picker.py +1286 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/selftest.py +771 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/shot.py +117 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/template.html +1029 -0
- package/plugins/thuthi-arch-diagram/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-arch-diagram/lib/pbpage.py +397 -0
- package/plugins/thuthi-arch-diagram/lib/tls.py +68 -0
- package/plugins/thuthi-arch-diagram/setup_check.py +10 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/SKILL.md +125 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/design-rules.md +110 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/example-shop.py +167 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/check.py +194 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/diagramkit.py +682 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/interact_test.py +115 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/render.py +113 -0
- package/plugins/thuthi-browser/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-browser/context.md +3 -0
- package/plugins/thuthi-browser/hooks/hooks.json +15 -0
- package/plugins/thuthi-browser/lib/pbpage.py +397 -0
- package/plugins/thuthi-browser/setup_check.py +93 -0
- package/plugins/thuthi-browser/skills/parallel-browser/SKILL.md +271 -0
- package/plugins/thuthi-browser/skills/parallel-browser/references/api.md +243 -0
- package/plugins/thuthi-browser/skills/parallel-browser/references/install.md +106 -0
- package/plugins/thuthi-demo-video/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-demo-video/lib/pbpage.py +397 -0
- package/plugins/thuthi-demo-video/setup_check.py +14 -0
- package/plugins/thuthi-demo-video/skills/demo-video/SKILL.md +261 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/caption.html +16 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/cursor.js +132 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/demo_video.py +2416 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/example_scenario.py +97 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/frame.html +95 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/overlay.js +129 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/title.html +30 -0
- package/plugins/thuthi-no-more-slop/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-no-more-slop/setup_check.py +10 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/LICENSE +21 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/SKILL.md +235 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/SOURCE.txt +1 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/agents/openai.yaml +6 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/examples.md +289 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/tokens.md +46 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/unslop-fallback.md +36 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/scripts/count_tells.py +426 -0
- package/plugins/thuthi-orca/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-orca/context.md +5 -0
- package/plugins/thuthi-orca/hooks/hooks.json +18 -0
- package/plugins/thuthi-orca/hooks/orca-team-grid.ts +21 -0
- package/plugins/thuthi-orca/setup_check.py +12 -0
- package/plugins/thuthi-orca/skills/orca-new-work/SKILL.md +492 -0
- package/plugins/thuthi-orca/tools/orca-team-grid/bin/tmux +338 -0
- package/plugins/thuthi-orca/tools/orca-team-grid/tests/selftest.py +299 -0
- package/runtime/client.js +69 -0
- package/runtime/daemon.js +503 -0
- package/runtime/focus-monitor.js +53 -0
- package/runtime/keys.js +86 -0
- package/runtime/owner.js +64 -0
- package/runtime/recorder.js +267 -0
- package/runtime/relay.js +95 -0
- package/runtime/session.js +1599 -0
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
#!/usr/bin/env -S uv run --quiet --script
|
|
2
|
+
# /// script
|
|
3
|
+
# requires-python = ">=3.10"
|
|
4
|
+
# dependencies = ["textual>=1.0"]
|
|
5
|
+
# ///
|
|
6
|
+
"""claude-switch TUI — 사용량 라이브 모니터 + 계정 전환.
|
|
7
|
+
|
|
8
|
+
엔진은 옆의 claude_switch.py (python) 그대로다. 이 뷰어는
|
|
9
|
+
읽기: claude-switch --all --json [--fresh] (사용량 캐시·백오프·auto 판정 포함)
|
|
10
|
+
쓰기: claude-switch <email> (Keychain 스왑)
|
|
11
|
+
만 호출한다. 계정 판정/토큰/정책 로직은 전부 엔진 쪽에 있고 여기엔 없다.
|
|
12
|
+
|
|
13
|
+
주기는 셋으로 나뉜다:
|
|
14
|
+
1초 화면 재렌더 — 스냅샷의 절대 epoch 로 리셋 카운트다운·조회 경과를 흐르게 한다 (엔진 호출 없음)
|
|
15
|
+
30초 엔진 조회 — `--all --json`. usage API 는 엔진의 5분 캐시가 막아주므로 여기서 늘어나지 않는다
|
|
16
|
+
5분 usage API — 엔진 TTL. `r` 키는 `--fresh` 로 이 캐시만 건너뛰어 즉시 1회 조회한다
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import asyncio
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import sys
|
|
25
|
+
import time
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
|
|
28
|
+
from rich.text import Text
|
|
29
|
+
from textual import work
|
|
30
|
+
from textual.app import App, ComposeResult
|
|
31
|
+
from textual.binding import Binding
|
|
32
|
+
from textual.widgets import DataTable, Footer, Header, RichLog, Static
|
|
33
|
+
from textual.widgets.data_table import CellDoesNotExist
|
|
34
|
+
|
|
35
|
+
try: # 픽셀 크기를 0 으로 알리는 터미널에서 마우스 이벤트가 ZeroDivisionError 로 앱을 죽이는 textual 버그 회피
|
|
36
|
+
from textual._xterm_parser import XTermParser
|
|
37
|
+
|
|
38
|
+
_parse_mouse_code = XTermParser.parse_mouse_code
|
|
39
|
+
|
|
40
|
+
def _safe_parse_mouse_code(self, code):
|
|
41
|
+
px = getattr(self, "terminal_pixel_size", None)
|
|
42
|
+
if px is not None and (not px[0] or not px[1]):
|
|
43
|
+
self.mouse_pixels = False
|
|
44
|
+
try:
|
|
45
|
+
return _parse_mouse_code(self, code)
|
|
46
|
+
except ZeroDivisionError:
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
XTermParser.parse_mouse_code = _safe_parse_mouse_code
|
|
50
|
+
except (ImportError, AttributeError):
|
|
51
|
+
pass
|
|
52
|
+
|
|
53
|
+
# 엔진 조회 주기(초). usage API 호출 수와는 무관 — 엔진 캐시 TTL(5분)이 상한을 정한다.
|
|
54
|
+
REFRESH_SECONDS = int(os.environ.get("CLAUDE_SWITCH_TUI_INTERVAL", "30"))
|
|
55
|
+
BLOCKS = "▁▂▃▄▅▆▇█"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def find_engine() -> list[str]:
|
|
59
|
+
"""엔진 명령. 엔진은 표준 라이브러리만 쓰므로 TUI 를 띄운 python(uv 환경 포함)으로 그대로 돌린다."""
|
|
60
|
+
env = os.environ.get("CLAUDE_SWITCH_ENGINE")
|
|
61
|
+
path = Path(env) if env else Path(__file__).resolve().parent / "claude_switch.py"
|
|
62
|
+
if not path.is_file():
|
|
63
|
+
sys.exit(f"claude-switch 엔진을 찾을 수 없습니다: {path} (CLAUDE_SWITCH_ENGINE 으로 지정 가능).")
|
|
64
|
+
return [sys.executable, str(path)]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
ENGINE = find_engine()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
async def run_engine(*args: str, timeout: float = 90.0) -> tuple[int, str, str]:
|
|
71
|
+
proc = await asyncio.create_subprocess_exec(
|
|
72
|
+
*ENGINE, *args,
|
|
73
|
+
stdout=asyncio.subprocess.PIPE,
|
|
74
|
+
stderr=asyncio.subprocess.PIPE,
|
|
75
|
+
)
|
|
76
|
+
try:
|
|
77
|
+
out, err = await asyncio.wait_for(proc.communicate(), timeout)
|
|
78
|
+
except asyncio.TimeoutError:
|
|
79
|
+
proc.kill()
|
|
80
|
+
return 124, "", f"timeout ({timeout:.0f}s)"
|
|
81
|
+
return proc.returncode or 0, out.decode("utf-8", "replace"), err.decode("utf-8", "replace")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def rel(epoch: float, now: float) -> str:
|
|
85
|
+
"""리셋까지 남은 시간. 캐시된 값이어도 절대 epoch 이라 표시가 틀어지지 않는다."""
|
|
86
|
+
if not epoch:
|
|
87
|
+
return "?"
|
|
88
|
+
d = epoch - now
|
|
89
|
+
if d <= 0:
|
|
90
|
+
return "now"
|
|
91
|
+
if d < 3600:
|
|
92
|
+
return f"{int(d // 60)}m"
|
|
93
|
+
if d < 86400:
|
|
94
|
+
return f"{int(d // 3600)}h{int((d % 3600) // 60)}m"
|
|
95
|
+
return f"{int(d // 86400)}d{int((d % 86400) // 3600)}h"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def bar(util: float | None) -> str:
|
|
99
|
+
if util is None:
|
|
100
|
+
return " "
|
|
101
|
+
return BLOCKS[min(len(BLOCKS) - 1, max(0, int(util / 100 * len(BLOCKS))))]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def remaining_color(remaining: float | None) -> str:
|
|
105
|
+
if remaining is None:
|
|
106
|
+
return "dim"
|
|
107
|
+
if remaining >= 50:
|
|
108
|
+
return "green"
|
|
109
|
+
if remaining >= 20:
|
|
110
|
+
return "yellow"
|
|
111
|
+
return "red"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def window_cell(win: dict, now: float) -> Text:
|
|
115
|
+
util = win.get("utilization")
|
|
116
|
+
if util is None:
|
|
117
|
+
return Text("-", style="dim")
|
|
118
|
+
remaining = win.get("remaining")
|
|
119
|
+
text = Text()
|
|
120
|
+
text.append(f"{util:5.1f}% ", style=remaining_color(remaining))
|
|
121
|
+
text.append(bar(util), style=remaining_color(remaining))
|
|
122
|
+
text.append(f" {rel(win.get('resets_at') or 0, now)}", style="dim")
|
|
123
|
+
return text
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def scoped_cell(items: list[dict], now: float) -> Text:
|
|
127
|
+
"""모델/서피스별 한도(예: Fable 주간). 엔진이 `scope`가 있는 limits 를 전부 넘겨주므로
|
|
128
|
+
이름을 가정하지 않고 그대로 나열한다. 표시 전용 — score/guard 에는 들어가지 않는다."""
|
|
129
|
+
if not items:
|
|
130
|
+
return Text("-", style="dim")
|
|
131
|
+
text = Text()
|
|
132
|
+
for i, item in enumerate(items):
|
|
133
|
+
if i:
|
|
134
|
+
text.append(" ", style="dim")
|
|
135
|
+
util = item.get("utilization")
|
|
136
|
+
remaining = item.get("remaining")
|
|
137
|
+
label = item.get("label") or "?"
|
|
138
|
+
group = item.get("group") or ""
|
|
139
|
+
if group and group != "weekly":
|
|
140
|
+
label = f"{label}/{group}"
|
|
141
|
+
text.append(f"{label} ", style="bold")
|
|
142
|
+
if util is None:
|
|
143
|
+
text.append("-", style="dim")
|
|
144
|
+
continue
|
|
145
|
+
text.append(f"{util:.0f}% ", style=remaining_color(remaining))
|
|
146
|
+
text.append(bar(util), style=remaining_color(remaining))
|
|
147
|
+
text.append(f" {rel(item.get('resets_at') or 0, now)}", style="dim")
|
|
148
|
+
return text
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def status_cell(acc: dict, now: float) -> Text:
|
|
152
|
+
status = acc.get("status", "")
|
|
153
|
+
source = acc.get("source", "")
|
|
154
|
+
selectable = acc.get("selectable")
|
|
155
|
+
if source == "cached":
|
|
156
|
+
age = int(now - (acc.get("fetched_at") or now))
|
|
157
|
+
if age >= 60:
|
|
158
|
+
status = f"{status} ({age // 60}m 전)"
|
|
159
|
+
style = "dim" if selectable else ("red" if source == "dead" else "yellow")
|
|
160
|
+
return Text(status, style=style)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def score_cell(acc: dict) -> Text:
|
|
164
|
+
score = acc.get("score", -1)
|
|
165
|
+
if score is None or score < 0:
|
|
166
|
+
return Text("-", style="dim")
|
|
167
|
+
if acc.get("guard_pass"):
|
|
168
|
+
return Text(f"{score:.0f}", style="bold")
|
|
169
|
+
return Text(f"{score:.0f} guard", style="yellow")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class ClaudeSwitchTUI(App):
|
|
173
|
+
CSS = """
|
|
174
|
+
Screen { layout: vertical; }
|
|
175
|
+
#statusbar {
|
|
176
|
+
height: 1;
|
|
177
|
+
background: $panel;
|
|
178
|
+
color: $text;
|
|
179
|
+
padding: 0 1;
|
|
180
|
+
}
|
|
181
|
+
DataTable { height: 1fr; }
|
|
182
|
+
#log {
|
|
183
|
+
height: 7;
|
|
184
|
+
border-top: solid $primary;
|
|
185
|
+
padding: 0 1;
|
|
186
|
+
}
|
|
187
|
+
"""
|
|
188
|
+
|
|
189
|
+
BINDINGS = [
|
|
190
|
+
Binding("s", "switch", "전환(enter)"),
|
|
191
|
+
Binding("a", "toggle_auto", "auto"),
|
|
192
|
+
Binding("r", "refresh", "API 즉시 조회"),
|
|
193
|
+
Binding("q", "quit", "종료"),
|
|
194
|
+
]
|
|
195
|
+
|
|
196
|
+
def __init__(self) -> None:
|
|
197
|
+
super().__init__()
|
|
198
|
+
self.auto_on = False # 기본 auto OFF — 'a' 키로 켤 수 있음
|
|
199
|
+
self.snapshot: dict | None = None
|
|
200
|
+
self.next_refresh = time.time() + REFRESH_SECONDS
|
|
201
|
+
self.busy = False
|
|
202
|
+
|
|
203
|
+
def compose(self) -> ComposeResult:
|
|
204
|
+
yield Header(show_clock=True)
|
|
205
|
+
yield Static("불러오는 중…", id="statusbar")
|
|
206
|
+
yield DataTable(id="accounts", cursor_type="row", zebra_stripes=True)
|
|
207
|
+
yield RichLog(id="log", markup=True, wrap=True)
|
|
208
|
+
yield Footer()
|
|
209
|
+
|
|
210
|
+
def on_mount(self) -> None:
|
|
211
|
+
self.title = "claude-switch"
|
|
212
|
+
table = self.query_one("#accounts", DataTable)
|
|
213
|
+
table.add_column(" ", width=2, key="mark")
|
|
214
|
+
table.add_column("EMAIL", key="email")
|
|
215
|
+
table.add_column("5H / RESET", key="five")
|
|
216
|
+
table.add_column("7D / RESET", key="seven")
|
|
217
|
+
table.add_column("SCOPED", key="scoped")
|
|
218
|
+
table.add_column("SCORE", key="score")
|
|
219
|
+
table.add_column("STATUS", key="status")
|
|
220
|
+
self.set_interval(1.0, self.tick)
|
|
221
|
+
self.refresh_data()
|
|
222
|
+
|
|
223
|
+
# ── 로그 ────────────────────────────────────────────────
|
|
224
|
+
def log_line(self, message: str) -> None:
|
|
225
|
+
self.query_one("#log", RichLog).write(
|
|
226
|
+
f"[dim]{time.strftime('%H:%M:%S')}[/dim] {message}"
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
# ── 갱신 루프 ───────────────────────────────────────────
|
|
230
|
+
def tick(self) -> None:
|
|
231
|
+
"""1초마다: 상태줄 + 시간 의존 셀 재렌더. 엔진 조회는 주기가 됐을 때만."""
|
|
232
|
+
self.update_statusbar()
|
|
233
|
+
self.refresh_live_cells()
|
|
234
|
+
if not self.busy and time.time() >= self.next_refresh:
|
|
235
|
+
self.refresh_data()
|
|
236
|
+
|
|
237
|
+
def update_statusbar(self) -> None:
|
|
238
|
+
remain = max(0, int(self.next_refresh - time.time()))
|
|
239
|
+
auto = "[b green]auto ON[/]" if self.auto_on else "[dim]auto OFF[/]"
|
|
240
|
+
current = (self.snapshot or {}).get("current") or "-"
|
|
241
|
+
if self.busy:
|
|
242
|
+
when = "조회 중…"
|
|
243
|
+
else:
|
|
244
|
+
when = f"다음 조회 {remain}s"
|
|
245
|
+
cfg = (self.snapshot or {}).get("auto") or {}
|
|
246
|
+
guards = ""
|
|
247
|
+
if cfg:
|
|
248
|
+
guards = (
|
|
249
|
+
f" · guard 5H≥{cfg.get('guard_5h')}% 7D≥{cfg.get('guard_7d')}%"
|
|
250
|
+
f" · margin {cfg.get('margin')}%"
|
|
251
|
+
)
|
|
252
|
+
self.query_one("#statusbar", Static).update(
|
|
253
|
+
f"{auto} · 현재 [b]{current}[/b] · {when}{guards}"
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
@work(exclusive=True)
|
|
257
|
+
async def refresh_data(self, fresh: bool = False) -> None:
|
|
258
|
+
"""엔진 `--all --json` 조회. fresh=True 면 `--fresh` 로 usage 캐시를 건너뛴다."""
|
|
259
|
+
self.busy = True
|
|
260
|
+
self.update_statusbar()
|
|
261
|
+
try:
|
|
262
|
+
args = ["--all", "--json"] + (["--fresh"] if fresh else [])
|
|
263
|
+
code, out, err = await run_engine(*args)
|
|
264
|
+
if code != 0 or not out.strip():
|
|
265
|
+
self.log_line(f"[red]조회 실패[/] {(err or out).strip()[:120]}")
|
|
266
|
+
return
|
|
267
|
+
try:
|
|
268
|
+
self.snapshot = json.loads(out)
|
|
269
|
+
except json.JSONDecodeError as exc:
|
|
270
|
+
self.log_line(f"[red]JSON 파싱 실패[/] {exc}")
|
|
271
|
+
return
|
|
272
|
+
if fresh:
|
|
273
|
+
live = [a["email"] for a in self.snapshot.get("accounts", []) if a.get("source") == "live"]
|
|
274
|
+
skipped = len(self.snapshot.get("accounts", [])) - len(live)
|
|
275
|
+
note = f" (백오프/dead 로 건너뜀 {skipped})" if skipped else ""
|
|
276
|
+
self.log_line(f"[b]usage API 조회[/] {len(live)}개 계정{note}")
|
|
277
|
+
self.render_table()
|
|
278
|
+
if self.auto_on:
|
|
279
|
+
await self.apply_auto()
|
|
280
|
+
finally:
|
|
281
|
+
self.busy = False
|
|
282
|
+
self.next_refresh = time.time() + REFRESH_SECONDS
|
|
283
|
+
self.update_statusbar()
|
|
284
|
+
|
|
285
|
+
def render_table(self) -> None:
|
|
286
|
+
"""스냅샷이 바뀌었을 때 표 전체를 다시 그린다 (행 키 = email)."""
|
|
287
|
+
snap = self.snapshot or {}
|
|
288
|
+
now = time.time()
|
|
289
|
+
table = self.query_one("#accounts", DataTable)
|
|
290
|
+
cursor = table.cursor_row
|
|
291
|
+
table.clear()
|
|
292
|
+
for acc in snap.get("accounts", []):
|
|
293
|
+
active = acc.get("active")
|
|
294
|
+
email_str = acc.get("email", "")
|
|
295
|
+
|
|
296
|
+
mark = Text("●", style="bold green") if active else Text(" ")
|
|
297
|
+
email = Text(email_str, style="bold" if active else "")
|
|
298
|
+
if not acc.get("selectable"):
|
|
299
|
+
email.stylize("dim")
|
|
300
|
+
|
|
301
|
+
table.add_row(
|
|
302
|
+
mark, email,
|
|
303
|
+
window_cell(acc.get("five_hour", {}), now),
|
|
304
|
+
window_cell(acc.get("seven_day", {}), now),
|
|
305
|
+
scoped_cell(acc.get("scoped") or [], now),
|
|
306
|
+
score_cell(acc),
|
|
307
|
+
status_cell(acc, now),
|
|
308
|
+
key=email_str,
|
|
309
|
+
)
|
|
310
|
+
if cursor is not None and 0 <= cursor < table.row_count:
|
|
311
|
+
table.move_cursor(row=cursor)
|
|
312
|
+
|
|
313
|
+
def refresh_live_cells(self) -> None:
|
|
314
|
+
"""1초마다: 스냅샷은 그대로 두고 시간이 흐르면 바뀌는 셀만 갱신 (엔진 호출 없음)."""
|
|
315
|
+
snap = self.snapshot
|
|
316
|
+
if not snap:
|
|
317
|
+
return
|
|
318
|
+
now = time.time()
|
|
319
|
+
table = self.query_one("#accounts", DataTable)
|
|
320
|
+
for acc in snap.get("accounts", []):
|
|
321
|
+
key = acc.get("email", "")
|
|
322
|
+
try:
|
|
323
|
+
table.update_cell(key, "five", window_cell(acc.get("five_hour", {}), now), update_width=True)
|
|
324
|
+
table.update_cell(key, "seven", window_cell(acc.get("seven_day", {}), now), update_width=True)
|
|
325
|
+
table.update_cell(key, "scoped", scoped_cell(acc.get("scoped") or [], now), update_width=True)
|
|
326
|
+
table.update_cell(key, "status", status_cell(acc, now), update_width=True)
|
|
327
|
+
except CellDoesNotExist:
|
|
328
|
+
# render_table 이 표를 다시 그리는 중이면 다음 틱에 맞춰진다
|
|
329
|
+
continue
|
|
330
|
+
|
|
331
|
+
# ── 동작 ────────────────────────────────────────────────
|
|
332
|
+
async def apply_auto(self) -> None:
|
|
333
|
+
decision = (self.snapshot or {}).get("decision") or {}
|
|
334
|
+
if decision.get("action") != "switch":
|
|
335
|
+
return
|
|
336
|
+
target = decision.get("best")
|
|
337
|
+
if not target:
|
|
338
|
+
return
|
|
339
|
+
self.log_line(f"[b]auto[/] {decision.get('reason', '')}")
|
|
340
|
+
await self.do_switch(target)
|
|
341
|
+
|
|
342
|
+
async def do_switch(self, email: str) -> None:
|
|
343
|
+
code, out, err = await run_engine(email)
|
|
344
|
+
message = (out or err).strip().splitlines()
|
|
345
|
+
message = message[-1] if message else ""
|
|
346
|
+
if code == 0:
|
|
347
|
+
self.log_line(f"[green]전환[/] {message}")
|
|
348
|
+
else:
|
|
349
|
+
self.log_line(f"[red]전환 실패[/] {message}")
|
|
350
|
+
code2, out2, _ = await run_engine("--all", "--json")
|
|
351
|
+
if code2 == 0 and out2.strip():
|
|
352
|
+
try:
|
|
353
|
+
self.snapshot = json.loads(out2)
|
|
354
|
+
self.render_table()
|
|
355
|
+
except json.JSONDecodeError:
|
|
356
|
+
pass
|
|
357
|
+
|
|
358
|
+
def selected_email(self) -> str | None:
|
|
359
|
+
table = self.query_one("#accounts", DataTable)
|
|
360
|
+
if table.row_count == 0 or table.cursor_row is None:
|
|
361
|
+
return None
|
|
362
|
+
accounts = (self.snapshot or {}).get("accounts", [])
|
|
363
|
+
if 0 <= table.cursor_row < len(accounts):
|
|
364
|
+
return accounts[table.cursor_row].get("email")
|
|
365
|
+
return None
|
|
366
|
+
|
|
367
|
+
@work(exclusive=True)
|
|
368
|
+
async def action_switch(self) -> None:
|
|
369
|
+
email = self.selected_email()
|
|
370
|
+
if not email:
|
|
371
|
+
return
|
|
372
|
+
if email == (self.snapshot or {}).get("current"):
|
|
373
|
+
self.log_line(f"[dim]이미 활성 계정: {email}[/dim]")
|
|
374
|
+
return
|
|
375
|
+
await self.do_switch(email)
|
|
376
|
+
|
|
377
|
+
def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None:
|
|
378
|
+
"""DataTable 이 enter 를 소비하므로 여기서 받는다."""
|
|
379
|
+
self.action_switch()
|
|
380
|
+
|
|
381
|
+
def action_toggle_auto(self) -> None:
|
|
382
|
+
self.auto_on = not self.auto_on
|
|
383
|
+
self.log_line(f"auto {'[b green]ON[/]' if self.auto_on else '[dim]OFF[/]'}")
|
|
384
|
+
self.update_statusbar()
|
|
385
|
+
if self.auto_on:
|
|
386
|
+
self.refresh_data()
|
|
387
|
+
|
|
388
|
+
def action_refresh(self) -> None:
|
|
389
|
+
"""r: usage 캐시를 건너뛰고 API 를 즉시 1회 조회 (백오프/dead 계정은 엔진이 계속 건너뜀)."""
|
|
390
|
+
if self.busy:
|
|
391
|
+
self.log_line("[dim]조회 중 — 잠시 후 다시 누르세요[/dim]")
|
|
392
|
+
return
|
|
393
|
+
self.refresh_data(fresh=True)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
if __name__ == "__main__":
|
|
397
|
+
ClaudeSwitchTUI().run()
|