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.
Files changed (115) hide show
  1. package/.claude-plugin/marketplace.json +55 -0
  2. package/README.md +13 -2
  3. package/bin/parallel-browser.js +109 -0
  4. package/extension/background.js +1329 -0
  5. package/extension/config.json +1 -0
  6. package/extension/guard.js +44 -0
  7. package/extension/manifest.json +10 -0
  8. package/extension/overlay.js +104 -0
  9. package/extension/popup.html +34 -0
  10. package/extension/popup.js +39 -0
  11. package/extension-reloader/manifest.json +13 -0
  12. package/extension-reloader/sw.js +17 -0
  13. package/package.json +13 -4
  14. package/plugins/thuthi/.claude-plugin/plugin.json +8 -0
  15. package/plugins/thuthi/context.md +3 -0
  16. package/plugins/thuthi/hooks/hooks.json +15 -0
  17. package/plugins/thuthi/skills/setup/SKILL.md +55 -0
  18. package/plugins/thuthi/skills/setup/scripts/doctor.py +249 -0
  19. package/plugins/thuthi/skills/setup/scripts/selftest.py +188 -0
  20. package/plugins/thuthi/tools/claude-switch/claude_switch.py +8 -0
  21. package/plugins/thuthi/tools/legacy_launcher.py +65 -0
  22. package/plugins/thuthi/tools/statusline/statusline.py +8 -0
  23. package/plugins/thuthi-accounts/.claude-plugin/plugin.json +9 -0
  24. package/plugins/thuthi-accounts/bin/claude-switch +5 -0
  25. package/plugins/thuthi-accounts/bin/claude-switch.cmd +4 -0
  26. package/plugins/thuthi-accounts/hooks/hooks.json +15 -0
  27. package/plugins/thuthi-accounts/lib/tls.py +68 -0
  28. package/plugins/thuthi-accounts/lib/usage_store.py +150 -0
  29. package/plugins/thuthi-accounts/setup_check.py +21 -0
  30. package/plugins/thuthi-accounts/skills/claude-switch/SKILL.md +48 -0
  31. package/plugins/thuthi-accounts/tools/claude-switch/claude-switch-tui.py +397 -0
  32. package/plugins/thuthi-accounts/tools/claude-switch/claude_switch.py +1204 -0
  33. package/plugins/thuthi-accounts/tools/claude-switch/credstore.py +417 -0
  34. package/plugins/thuthi-accounts/tools/claude-switch/install.py +301 -0
  35. package/plugins/thuthi-accounts/tools/claude-switch/tests/selftest.py +491 -0
  36. package/plugins/thuthi-accounts/tools/statusline/statusline.py +212 -0
  37. package/plugins/thuthi-agenda-picker/.claude-plugin/plugin.json +9 -0
  38. package/plugins/thuthi-agenda-picker/context.md +3 -0
  39. package/plugins/thuthi-agenda-picker/hooks/hooks.json +15 -0
  40. package/plugins/thuthi-agenda-picker/lib/pbpage.py +397 -0
  41. package/plugins/thuthi-agenda-picker/setup_check.py +18 -0
  42. package/plugins/thuthi-agenda-picker/skills/agenda-picker/SKILL.md +280 -0
  43. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/design-rules.md +110 -0
  44. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/diagram/base.css +33 -0
  45. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/agenda.json +146 -0
  46. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-dark.svg +5 -0
  47. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-light.svg +5 -0
  48. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-dark.svg +5 -0
  49. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-light.svg +5 -0
  50. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-dark.svg +5 -0
  51. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-light.svg +5 -0
  52. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/base.css +33 -0
  53. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/name-B.html +15 -0
  54. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-dark.svg +5 -0
  55. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-light.svg +5 -0
  56. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/picker.py +1286 -0
  57. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/selftest.py +771 -0
  58. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/shot.py +117 -0
  59. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/template.html +1029 -0
  60. package/plugins/thuthi-arch-diagram/.claude-plugin/plugin.json +9 -0
  61. package/plugins/thuthi-arch-diagram/lib/pbpage.py +397 -0
  62. package/plugins/thuthi-arch-diagram/lib/tls.py +68 -0
  63. package/plugins/thuthi-arch-diagram/setup_check.py +10 -0
  64. package/plugins/thuthi-arch-diagram/skills/arch-diagram/SKILL.md +125 -0
  65. package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/design-rules.md +110 -0
  66. package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/example-shop.py +167 -0
  67. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/check.py +194 -0
  68. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/diagramkit.py +682 -0
  69. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/interact_test.py +115 -0
  70. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/render.py +113 -0
  71. package/plugins/thuthi-browser/.claude-plugin/plugin.json +9 -0
  72. package/plugins/thuthi-browser/context.md +3 -0
  73. package/plugins/thuthi-browser/hooks/hooks.json +15 -0
  74. package/plugins/thuthi-browser/lib/pbpage.py +397 -0
  75. package/plugins/thuthi-browser/setup_check.py +93 -0
  76. package/plugins/thuthi-browser/skills/parallel-browser/SKILL.md +271 -0
  77. package/plugins/thuthi-browser/skills/parallel-browser/references/api.md +243 -0
  78. package/plugins/thuthi-browser/skills/parallel-browser/references/install.md +106 -0
  79. package/plugins/thuthi-demo-video/.claude-plugin/plugin.json +9 -0
  80. package/plugins/thuthi-demo-video/lib/pbpage.py +397 -0
  81. package/plugins/thuthi-demo-video/setup_check.py +14 -0
  82. package/plugins/thuthi-demo-video/skills/demo-video/SKILL.md +261 -0
  83. package/plugins/thuthi-demo-video/skills/demo-video/scripts/caption.html +16 -0
  84. package/plugins/thuthi-demo-video/skills/demo-video/scripts/cursor.js +132 -0
  85. package/plugins/thuthi-demo-video/skills/demo-video/scripts/demo_video.py +2416 -0
  86. package/plugins/thuthi-demo-video/skills/demo-video/scripts/example_scenario.py +97 -0
  87. package/plugins/thuthi-demo-video/skills/demo-video/scripts/frame.html +95 -0
  88. package/plugins/thuthi-demo-video/skills/demo-video/scripts/overlay.js +129 -0
  89. package/plugins/thuthi-demo-video/skills/demo-video/scripts/title.html +30 -0
  90. package/plugins/thuthi-no-more-slop/.claude-plugin/plugin.json +9 -0
  91. package/plugins/thuthi-no-more-slop/setup_check.py +10 -0
  92. package/plugins/thuthi-no-more-slop/skills/no-more-slop/LICENSE +21 -0
  93. package/plugins/thuthi-no-more-slop/skills/no-more-slop/SKILL.md +235 -0
  94. package/plugins/thuthi-no-more-slop/skills/no-more-slop/SOURCE.txt +1 -0
  95. package/plugins/thuthi-no-more-slop/skills/no-more-slop/agents/openai.yaml +6 -0
  96. package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/examples.md +289 -0
  97. package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/tokens.md +46 -0
  98. package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/unslop-fallback.md +36 -0
  99. package/plugins/thuthi-no-more-slop/skills/no-more-slop/scripts/count_tells.py +426 -0
  100. package/plugins/thuthi-orca/.claude-plugin/plugin.json +9 -0
  101. package/plugins/thuthi-orca/context.md +5 -0
  102. package/plugins/thuthi-orca/hooks/hooks.json +18 -0
  103. package/plugins/thuthi-orca/hooks/orca-team-grid.ts +21 -0
  104. package/plugins/thuthi-orca/setup_check.py +12 -0
  105. package/plugins/thuthi-orca/skills/orca-new-work/SKILL.md +492 -0
  106. package/plugins/thuthi-orca/tools/orca-team-grid/bin/tmux +338 -0
  107. package/plugins/thuthi-orca/tools/orca-team-grid/tests/selftest.py +299 -0
  108. package/runtime/client.js +69 -0
  109. package/runtime/daemon.js +503 -0
  110. package/runtime/focus-monitor.js +53 -0
  111. package/runtime/keys.js +86 -0
  112. package/runtime/owner.js +64 -0
  113. package/runtime/recorder.js +267 -0
  114. package/runtime/relay.js +95 -0
  115. package/runtime/session.js +1599 -0
@@ -0,0 +1,1204 @@
1
+ #!/usr/bin/env python3
2
+ """claude-switch: 단일 config dir + 이메일 기반 다중 계정 스왑 (macOS · Linux · Windows, python3 3.9 표준 라이브러리만).
3
+
4
+ - state 는 ~/.claude 하나 (세션 · 메모리 · todos · settings 전부 공유)
5
+ - 계정 식별자 = oauthAccount.emailAddress
6
+ - 스왑 = 활성 자격증명의 claudeAiOauth 교체 (credstore.py: macOS Keychain / 파일 / Windows 자격 증명 관리자)
7
+ + .claude.json 의 oauthAccount 패치
8
+ - 자동 등록: 매 실행마다 현재 활성 상태를 해당 이메일 백업으로 sync → /login 으로 새 계정 추가 시 등록 명령 불필요
9
+ - 사용량 저장소는 statusline 과 같이 쓴다 (lib/usage_store.py)
10
+
11
+ thuthi-accounts 플러그인의 tools/claude-switch/ 에 있다. 터미널의 claude-switch 는 thuthi:setup 이 만든 shim 이 이 파일을 실행한다.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import re
19
+ import shutil
20
+ import subprocess
21
+ import sys
22
+ import tempfile
23
+ import time
24
+ import unicodedata
25
+ import urllib.error
26
+ import urllib.request
27
+ from concurrent.futures import ThreadPoolExecutor
28
+ from datetime import datetime, timezone
29
+ from pathlib import Path
30
+ from typing import Optional
31
+
32
+ HERE = Path(__file__).resolve().parent
33
+ sys.path.insert(0, str(HERE.parents[1] / "lib"))
34
+ sys.path.insert(0, str(HERE))
35
+ import usage_store as us # noqa: E402
36
+ import tls # noqa: E402
37
+ import credstore as cs # noqa: E402
38
+
39
+ # Claude Code 가 쓰는 공개 OAuth 클라이언트 (subscription 로그인 공용).
40
+ # refresh endpoint / client_id 는 공식 문서가 아닌 역공학 정보라 바뀔 수 있다. 시험은 CLAUDE_SWITCH_*_BASE 로 가짜 서버를 쓴다.
41
+ API_BASE = os.environ.get("CLAUDE_SWITCH_API_BASE", "https://api.anthropic.com")
42
+ CONSOLE_BASE = os.environ.get("CLAUDE_SWITCH_CONSOLE_BASE", "https://console.anthropic.com")
43
+ OAUTH_TOKEN_URL = f"{CONSOLE_BASE}/v1/oauth/token"
44
+ OAUTH_CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e"
45
+ OAUTH_PROFILE_URL = f"{API_BASE}/api/oauth/profile"
46
+ OAUTH_USAGE_URL = f"{API_BASE}/api/oauth/usage"
47
+ TOKEN_REFRESH_BUFFER_MS = 60000 # 만료까지 이 시간 이하면 선제적으로 refresh
48
+
49
+ # 사용량 캐시는 전 계정 5분 통일 — 갱신 루프(auto/TUI)가 얼마나 자주 돌든 usage API 는 계정당 최대 5분에 한 번.
50
+ # `--all --fresh`(TUI 의 r 키)는 이 TTL 만 0 으로 만들어 즉시 재조회한다 — 백오프/dead 판정은 그대로.
51
+ USAGE_TTL = 300
52
+ BACKOFF_BASE = 300 # 조회 실패 시 계정별 지수 백오프 (초): 5m → 10m → 20m → … → 1h
53
+ BACKOFF_MAX = 3600
54
+ SWAP_APPLY_S = 30 # 실행 중인 claude 가 새 자격증명을 읽기까지 (macOS Keychain 캐시 30s 실측)
55
+
56
+ # auto 기본값
57
+ AUTO = {"interval": 5, "guard5": 20, "guard7": 10, "margin": 10, "fallback": "",
58
+ "once": False, "dry": False, "hot": True}
59
+
60
+ STATE = us.state_dir()
61
+ CURRENT_FILE = STATE / "current"
62
+ IDENTITY_CACHE = STATE / "identity-cache"
63
+
64
+
65
+ def eprint(*a):
66
+ print(*a, file=sys.stderr)
67
+
68
+
69
+ def now_s() -> int:
70
+ return int(time.time())
71
+
72
+
73
+ def now_ms() -> int:
74
+ return int(time.time() * 1000)
75
+
76
+
77
+ # ─── HTTP (회사 TLS 검사 대응: OS · 환경 변수의 CA 를 더 싣는다) ───
78
+
79
+ def http_json(method: str, url: str, headers: dict, body: Optional[dict] = None, timeout: float = 8):
80
+ """→ (status, json 또는 None). 네트워크 오류는 status 0."""
81
+ data = json.dumps(body).encode() if body is not None else None
82
+ req = urllib.request.Request(url, data=data, method=method,
83
+ headers={"User-Agent": "claude-switch/2.0", "Accept": "application/json", **headers})
84
+ if data is not None:
85
+ req.add_header("Content-Type", "application/json")
86
+ ctx = tls.ssl_context() if url.startswith("https:") else None
87
+ try:
88
+ with urllib.request.urlopen(req, timeout=timeout, context=ctx) as r:
89
+ raw = r.read()
90
+ status = r.status
91
+ except urllib.error.HTTPError as e:
92
+ raw, status = e.read() or b"", e.code
93
+ except (urllib.error.URLError, OSError, ValueError):
94
+ return 0, None
95
+ try:
96
+ return status, json.loads(raw.decode("utf-8", "replace"))
97
+ except ValueError:
98
+ return status, None
99
+
100
+
101
+ def oauth_headers(token: str) -> dict:
102
+ return {"Authorization": f"Bearer {token}", "anthropic-beta": "oauth-2025-04-20"}
103
+
104
+
105
+ # ─── 상태 파일 ────────────────────────────────────────────────
106
+
107
+ def active_account() -> str:
108
+ return us.read_text(CURRENT_FILE).strip()
109
+
110
+
111
+ def set_current(email: str) -> None:
112
+ us.write_atomic(CURRENT_FILE, email + "\n")
113
+
114
+
115
+ def oauth_of(blob: Optional[dict]) -> dict:
116
+ v = (blob or {}).get("claudeAiOauth")
117
+ return v if isinstance(v, dict) else {}
118
+
119
+
120
+ def access_token_of(blob: Optional[dict]) -> str:
121
+ return str(oauth_of(blob).get("accessToken") or "")
122
+
123
+
124
+ def token_fingerprint(blob: Optional[dict]) -> str:
125
+ at = access_token_of(blob)
126
+ return hashlib.sha256(at.encode()).hexdigest() if at else ""
127
+
128
+
129
+ def identity_lookup(fp: str) -> str:
130
+ if not fp:
131
+ return ""
132
+ for line in us.read_text(IDENTITY_CACHE).splitlines():
133
+ p = line.split()
134
+ if len(p) == 2 and p[0] == fp:
135
+ return p[1]
136
+ return ""
137
+
138
+
139
+ def identity_store(fp: str, email: str) -> None:
140
+ if not fp or not email:
141
+ return
142
+ rest = [ln for ln in us.read_text(IDENTITY_CACHE).splitlines() if ln.split()[:1] != [fp] and ln.strip()]
143
+ us.write_atomic(IDENTITY_CACHE, "\n".join([f"{fp} {email}", *rest][:50]) + "\n", mode=0o600)
144
+
145
+
146
+ def identity_forget(email: str) -> None:
147
+ rest = [ln for ln in us.read_text(IDENTITY_CACHE).splitlines() if ln.split()[1:2] != [email] and ln.strip()]
148
+ us.write_atomic(IDENTITY_CACHE, "\n".join(rest) + ("\n" if rest else ""), mode=0o600)
149
+
150
+
151
+ def rt_fingerprint(email: str) -> str:
152
+ """저장된 refresh token 의 지문 (앞 16자). 토큰 자체는 남기지 않는다."""
153
+ rt = str(oauth_of(store_for(email).get()).get("refreshToken") or "")
154
+ return hashlib.sha256(rt.encode()).hexdigest()[:16] if rt else ""
155
+
156
+
157
+ def dead_mark(email: str, reason: str = "재로그인 필요") -> None:
158
+ # 그때의 refresh token 지문을 같이 남긴다. 재로그인으로 토큰이 바뀌면 dead_live 가 표시를 걷는다.
159
+ us.write_atomic(us.dead_dir() / us.slug(email), f"{reason}\nrt:{rt_fingerprint(email)}\n")
160
+
161
+
162
+ def dead_live(email: str) -> str:
163
+ """dead 표시가 아직 유효하면 사유, 아니면 "".
164
+
165
+ dead 계정은 네트워크를 타지 않아 표시를 지울 기회가 없었다. 그래서 claude-switch --add 로 다시 로그인해도
166
+ "refresh token 만료" 가 계속 떴다 (2026-10-11). 표시한 뒤 refresh token 이 바뀌었거나 지문이 없는 옛 표시면
167
+ 표시 · 백오프를 걷고 한 번 다시 확인한다. 정말 죽었으면 그 확인에서 다시 표시된다."""
168
+ raw = us.read_text(us.dead_dir() / us.slug(email))
169
+ if not raw.strip():
170
+ return ""
171
+ lines = raw.splitlines()
172
+ fp = next((ln[3:].strip() for ln in lines[1:] if ln.startswith("rt:")), None)
173
+ if fp is None or fp != rt_fingerprint(email):
174
+ dead_clear(email)
175
+ backoff_clear(email)
176
+ return ""
177
+ return lines[0].strip()
178
+
179
+
180
+ def dead_clear(email: str) -> None:
181
+ try:
182
+ (us.dead_dir() / us.slug(email)).unlink()
183
+ except OSError:
184
+ pass
185
+
186
+
187
+ def backoff_record_failure(email: str) -> None:
188
+ f = us.backoff_dir() / us.slug(email)
189
+ parts = us.read_text(f).split()
190
+ n = (us.to_int(parts[1]) if len(parts) > 1 else 0) + 1
191
+ d = min(BACKOFF_BASE * (2 ** (n - 1)), BACKOFF_MAX)
192
+ us.write_atomic(f, f"{now_s() + d} {n}\n")
193
+
194
+
195
+ def backoff_clear(email: str) -> None:
196
+ try:
197
+ (us.backoff_dir() / us.slug(email)).unlink()
198
+ except OSError:
199
+ pass
200
+
201
+
202
+ # ─── 계정 · 토큰 소유자 판정 ─────────────────────────────────────
203
+ # .claude.json 의 oauthAccount 는 실행 중인 claude 가 자기 메모리 스냅샷으로 되돌릴 수 있어서
204
+ # (특히 auto hot-swap 직후) 소유자 판정의 근거로 쓰면 백업 슬롯이 오염된다 → 토큰 자체를 근거로 판정한다.
205
+
206
+ ACCOUNTS: list = []
207
+
208
+
209
+ def discover_accounts() -> None:
210
+ ACCOUNTS[:] = us.accounts()
211
+
212
+
213
+ def identify_token_owner(blob: dict) -> str:
214
+ at = access_token_of(blob)
215
+ if not at:
216
+ return ""
217
+ status, j = http_json("GET", OAUTH_PROFILE_URL, oauth_headers(at))
218
+ return str(((j or {}).get("account") or {}).get("email") or "") if status == 200 else ""
219
+
220
+
221
+ def resolve_active_owner(blob: dict) -> str:
222
+ """활성 토큰이 어느 계정 것인지 (비용 낮은 순): 백업 토큰 일치 → identity 캐시 → profile API →
223
+ 실패 시에만 .claude.json (current 와 어긋나면 판정 포기, 오염 방지)."""
224
+ at = access_token_of(blob)
225
+ if not at:
226
+ return ""
227
+ for email in us.accounts():
228
+ if access_token_of(cs.backup_store(email).get()) == at:
229
+ return email
230
+ fp = token_fingerprint(blob)
231
+ email = identity_lookup(fp)
232
+ if email:
233
+ return email
234
+ email = identify_token_owner(blob)
235
+ if email:
236
+ identity_store(fp, email)
237
+ return email
238
+ cur = active_account()
239
+ json_email = str(((cs.load_json(cs.claude_json_path()) or {}).get("oauthAccount") or {}).get("emailAddress") or "")
240
+ if json_email and (not cur or cur == json_email):
241
+ return json_email
242
+ return ""
243
+
244
+
245
+ def auto_sync_current() -> None:
246
+ """현재 활성 상태를 소유 계정의 백업 슬롯에 sync. 신규 계정 자동 등록 · refresh 된 토큰 보존."""
247
+ blob = cs.active_store().get()
248
+ if not oauth_of(blob):
249
+ return
250
+ email = resolve_active_owner(blob)
251
+ if not email:
252
+ eprint("Warning: 활성 토큰의 소유 계정을 판정하지 못해 sync를 건너뜁니다 (네트워크 확인).")
253
+ return
254
+ d = us.backup_dir() / email
255
+ d.mkdir(parents=True, exist_ok=True)
256
+ cj = cs.load_json(cs.claude_json_path()) or {}
257
+ oa = cj.get("oauthAccount")
258
+ # oauthAccount 스냅샷은 .claude.json 이 같은 계정을 가리킬 때만 갱신 (어긋나면 stale 값이므로 무시)
259
+ if isinstance(oa, dict) and oa.get("emailAddress") == email:
260
+ us.write_atomic(d / "oauth-account.json", json.dumps(oa, ensure_ascii=False) + "\n")
261
+ elif not (d / "oauth-account.json").exists():
262
+ us.write_atomic(d / "oauth-account.json", json.dumps({"emailAddress": email}) + "\n")
263
+ bs = cs.backup_store(email)
264
+ if oauth_of(bs.get()) != oauth_of(blob): # 바뀌었을 때만 쓴다 (auto 루프가 매번 쓰지 않게)
265
+ bs.set({"claudeAiOauth": oauth_of(blob)})
266
+ set_current(email)
267
+
268
+
269
+ def resolve_email(query: str) -> Optional[str]:
270
+ if query in ACCOUNTS:
271
+ return query
272
+ matches = [a for a in ACCOUNTS if a.startswith(query)]
273
+ if len(matches) == 1:
274
+ return matches[0]
275
+ if matches:
276
+ eprint(f"Error: '{query}'에 해당하는 계정이 여러 개입니다: {' '.join(matches)}")
277
+ else:
278
+ eprint(f"Error: '{query}'에 해당하는 계정 없음")
279
+ eprint(f"등록된 계정: {' '.join(ACCOUNTS) or '(없음)'}")
280
+ return None
281
+
282
+
283
+ def store_for(email: str):
284
+ return cs.active_store() if email == active_account() else cs.backup_store(email)
285
+
286
+
287
+ # ─── Token refresh ────────────────────────────────────────────
288
+
289
+ def refresh_token(store, is_active: bool):
290
+ """→ (rc, access). rc 0 = 성공, 1 = 일시 실패, 2 = refresh token 폐기/만료 (재시도해도 영원히 실패)."""
291
+ blob = store.get()
292
+ rt = str(oauth_of(blob).get("refreshToken") or "")
293
+ if not rt:
294
+ return 1, ""
295
+ status, j = http_json("POST", OAUTH_TOKEN_URL, {}, {"grant_type": "refresh_token", "refresh_token": rt,
296
+ "client_id": OAUTH_CLIENT_ID}, timeout=10)
297
+ if j is None:
298
+ return 1, ""
299
+ err = j.get("error")
300
+ if err:
301
+ msg = err if isinstance(err, str) else str((err or {}).get("type") or (err or {}).get("message") or "error")
302
+ return (2 if re.search(r"invalid_grant|invalid_request|revoked", msg) else 1), ""
303
+ w = j.get("claudeAiOauth") if isinstance(j.get("claudeAiOauth"), dict) else {}
304
+ new_at = w.get("accessToken") or j.get("access_token")
305
+ new_rt = w.get("refreshToken") or j.get("refresh_token")
306
+ new_exp = w.get("expiresAt")
307
+ if not new_exp and j.get("expires_in") is not None:
308
+ new_exp = now_ms() + int(j["expires_in"]) * 1000
309
+ scopes = w.get("scopes") or (j["scope"].split(" ") if isinstance(j.get("scope"), str) else None)
310
+ if not (new_at and new_rt and new_exp):
311
+ return 1, ""
312
+ # 기존 JSON 에 새 필드만 merge (subscriptionType, rateLimitTier 등 보존)
313
+ blob = dict(blob or {})
314
+ o = dict(oauth_of(blob))
315
+ o.update(accessToken=new_at, refreshToken=new_rt, expiresAt=int(new_exp))
316
+ if isinstance(scopes, list):
317
+ o["scopes"] = scopes
318
+ blob["claudeAiOauth"] = o
319
+ if is_active:
320
+ with cs.storage_lock():
321
+ ok = store.set(blob)
322
+ else:
323
+ ok = store.set(blob)
324
+ return (0, new_at) if ok else (1, "")
325
+
326
+
327
+ def get_access_token_for(email: str) -> str:
328
+ is_active = email == active_account()
329
+ store = cs.active_store() if is_active else cs.backup_store(email)
330
+ o = oauth_of(store.get())
331
+ if not o:
332
+ return ""
333
+ exp = us.to_int(o.get("expiresAt"))
334
+ if exp and exp <= now_ms() + TOKEN_REFRESH_BUFFER_MS:
335
+ rc, at = refresh_token(store, is_active)
336
+ if rc == 0 and at:
337
+ return at
338
+ if rc == 2: # 되살릴 수 없는 refresh token → 표시해 두고 이후 사이클에서 아예 건너뛴다
339
+ dead_mark(email, "refresh token 만료/무효 — 재로그인 필요")
340
+ # 그 외 실패는 일시적일 수 있으니 만료 토큰이라도 반환 (status 에 반영됨)
341
+ return str(o.get("accessToken") or "")
342
+
343
+
344
+ def account_local_state(email: str) -> str:
345
+ """네트워크 0회. ok / refreshable / dead (dead 판정이 없으면 죽은 계정에 매 사이클 실패할 요청을 던져 rate limit 을 자초한다)."""
346
+ if dead_live(email):
347
+ return "dead"
348
+ o = oauth_of(store_for(email).get())
349
+ if not o:
350
+ return "dead"
351
+ at, rt = o.get("accessToken"), o.get("refreshToken")
352
+ exp, rexp = us.to_int(o.get("expiresAt")), us.to_int(o.get("refreshTokenExpiresAt"))
353
+ now = now_ms()
354
+ if at and exp > now + TOKEN_REFRESH_BUFFER_MS:
355
+ return "ok"
356
+ if not rt or (0 < rexp <= now):
357
+ return "dead"
358
+ return "refreshable"
359
+
360
+
361
+ # ─── Usage API ────────────────────────────────────────────────
362
+
363
+ def _ep(ts) -> int:
364
+ """ISO 시각 → epoch. 소수초 · 오프셋 형식이 어긋나도 0(알 수 없음)으로 흡수 (parse error 가 백오프로 번지지 않게)."""
365
+ if not ts:
366
+ return 0
367
+ try:
368
+ s = re.sub(r"\.\d+", "", str(ts))
369
+ s = re.sub(r"(Z|[+-]00:?00)$", "+00:00", s)
370
+ dt = datetime.fromisoformat(s)
371
+ if dt.tzinfo is None:
372
+ dt = dt.replace(tzinfo=timezone.utc)
373
+ return int(dt.timestamp())
374
+ except ValueError:
375
+ return 0
376
+
377
+
378
+ def _num(v) -> str:
379
+ if v is None or v == "":
380
+ return ""
381
+ if isinstance(v, float):
382
+ return repr(v)
383
+ return str(v)
384
+
385
+
386
+ def _clean(v) -> str:
387
+ return re.sub(r"[:,|\t\n]", "_", str(v))
388
+
389
+
390
+ def query_usage(token: str):
391
+ """→ (five, five_ep, seven, seven_ep, scoped, status). 상대시간이 아닌 절대 epoch — 캐시해도 표시가 틀어지지 않는다.
392
+ scoped: 응답 limits[] 중 scope 가 있는 항목 전부 (label:group:percent:reset_epoch, ',' 로 이음). 표시 전용."""
393
+ if not token:
394
+ return "-", 0, "-", 0, "", "no token"
395
+ status, j = http_json("GET", OAUTH_USAGE_URL, oauth_headers(token), timeout=5)
396
+ if j is None:
397
+ return "-", 0, "-", 0, "", "API error"
398
+ err = j.get("error")
399
+ if err:
400
+ msg = err.get("message") or err.get("type") if isinstance(err, dict) else err
401
+ return "-", 0, "-", 0, "", str(msg or "error")[:24]
402
+ try:
403
+ fh, sd = j.get("five_hour") or {}, j.get("seven_day") or {}
404
+ five, seven = _num(fh.get("utilization")), _num(sd.get("utilization"))
405
+ items = []
406
+ limits = j.get("limits") if isinstance(j.get("limits"), list) else []
407
+ for it in limits:
408
+ if not isinstance(it, dict) or it.get("scope") is None:
409
+ continue
410
+ sc = it.get("scope") or {}
411
+ model = sc.get("model") if isinstance(sc, dict) else None
412
+ label = ((model or {}).get("display_name") if isinstance(model, dict) else None) \
413
+ or ((model or {}).get("id") if isinstance(model, dict) else None) \
414
+ or (sc.get("surface") if isinstance(sc, dict) else None) or it.get("kind") or "scoped"
415
+ pct = it.get("percent") if it.get("percent") is not None else it.get("utilization")
416
+ items.append(f"{_clean(label)}:{_clean(it.get('group') or it.get('kind') or '')}:{_num(pct)}:{_ep(it.get('resets_at'))}")
417
+ scoped = ",".join(items)
418
+ f_ep, s_ep = _ep(fh.get("resets_at")), _ep(sd.get("resets_at"))
419
+ except (AttributeError, TypeError):
420
+ return "-", 0, "-", 0, "", "parse error"
421
+ if not five and not seven:
422
+ return "-", 0, "-", 0, "", "parse error"
423
+ return five or "?", f_ep, seven or "?", s_ep, scoped, "OK"
424
+
425
+
426
+ def scoped_all_future(scoped: str, now: int) -> bool:
427
+ for item in filter(None, scoped.split(",")):
428
+ ep = us.to_int(item.rsplit(":", 1)[-1])
429
+ if 0 < ep <= now:
430
+ return False
431
+ return True
432
+
433
+
434
+ def build_row(email: str) -> dict:
435
+ """원본 행 (auto 계산 · 표시 · JSON 공용). source: live | cached | backoff | dead"""
436
+ now = now_s()
437
+ row = dict(email=email, five="-", five_ep=0, seven="-", seven_ep=0, status="", source="", fetched=0, scoped="")
438
+ if account_local_state(email) == "dead": # 죽은 계정은 네트워크를 아예 타지 않는다
439
+ row.update(status=dead_live(email) or "재로그인 필요", source="dead")
440
+ return row
441
+ c = us.read(email)
442
+ if c.fetched > 0 and now - c.fetched < USAGE_TTL:
443
+ fresh = not (0 < c.five_ep <= now) and not (0 < c.seven_ep <= now) and scoped_all_future(c.scoped, now)
444
+ if fresh:
445
+ row.update(five=c.five, five_ep=c.five_ep, seven=c.seven, seven_ep=c.seven_ep,
446
+ status="OK", source="cached", fetched=c.fetched, scoped=c.scoped)
447
+ return row
448
+ until = us.backoff_until(email)
449
+ if until > now: # 백오프 중이면 네트워크 스킵 (남은 캐시 값은 보여주되 선택 대상에서는 제외)
450
+ row.update(five=c.five or "-", five_ep=c.five_ep, seven=c.seven or "-", seven_ep=c.seven_ep,
451
+ status=f"backoff {(until - now + 59) // 60}m", source="backoff", fetched=c.fetched, scoped=c.scoped)
452
+ return row
453
+ five, f_ep, seven, s_ep, scoped, status = query_usage(get_access_token_for(email))
454
+ if status == "OK":
455
+ us.write(email, us.Usage(five, f_ep, seven, s_ep, now_s(), scoped))
456
+ backoff_clear(email)
457
+ dead_clear(email)
458
+ else:
459
+ backoff_record_failure(email)
460
+ row.update(five=five, five_ep=f_ep, seven=seven, seven_ep=s_ep, status=status, source="live", fetched=now,
461
+ scoped=scoped)
462
+ return row
463
+
464
+
465
+ def build_all_rows() -> list:
466
+ if not ACCOUNTS:
467
+ return []
468
+ with ThreadPoolExecutor(max_workers=min(8, len(ACCOUNTS))) as ex:
469
+ return list(ex.map(build_row, ACCOUNTS))
470
+
471
+
472
+ # ─── 표시 ─────────────────────────────────────────────────────
473
+
474
+ def rel(ep: int, now: int) -> str:
475
+ if ep <= 0:
476
+ return "?"
477
+ d = ep - now
478
+ if d <= 0:
479
+ return "now"
480
+ if d < 3600:
481
+ return f"{d // 60}m"
482
+ if d < 86400:
483
+ return f"{d // 3600}h{(d % 3600) // 60}m"
484
+ return f"{d // 86400}d{(d % 86400) // 3600}h"
485
+
486
+
487
+ def cell(util: str, ep: int, now: int) -> str:
488
+ return "-" if util in ("-", "", "?") else f"{util}% / {rel(ep, now)}"
489
+
490
+
491
+ def age(t: int, now: int) -> str:
492
+ if t <= 0:
493
+ return ""
494
+ d = now - t
495
+ if d < 60:
496
+ return ""
497
+ return f" ({d // 60}m 전)" if d < 3600 else f" ({d // 3600}h 전)"
498
+
499
+
500
+ def scoped_cell(s: str, now: int) -> str:
501
+ out = []
502
+ for item in filter(None, s.split(",")):
503
+ f = item.split(":")
504
+ if len(f) < 3 or f[2] == "":
505
+ continue
506
+ label = f[0] if not f[1] or f[1] == "weekly" else f"{f[0]}/{f[1]}"
507
+ out.append(f"{label} {f[2]}% / {rel(us.to_int(f[3] if len(f) > 3 else 0), now)}")
508
+ return ", ".join(out) or "-"
509
+
510
+
511
+ def width(s: str) -> int:
512
+ return sum(2 if unicodedata.east_asian_width(c) in "WF" else 1 for c in s)
513
+
514
+
515
+ def print_table(rows: list, indent: str = "") -> None:
516
+ """`column -t` 처럼 칸을 맞춘다 (한글은 두 칸)."""
517
+ ws = [max(width(r[i]) for r in rows) for i in range(len(rows[0]))]
518
+ for r in rows:
519
+ print(indent + " ".join(c + " " * (ws[i] - width(c)) for i, c in enumerate(r)).rstrip())
520
+
521
+
522
+ def display_cells(row: dict, now: int) -> list:
523
+ st = row["status"] + (age(row["fetched"], now) if row["source"] == "cached" else "")
524
+ return [cell(row["five"], row["five_ep"], now), cell(row["seven"], row["seven_ep"], now),
525
+ scoped_cell(row["scoped"], now), st]
526
+
527
+
528
+ # ─── auto 판정 ────────────────────────────────────────────────
529
+
530
+ def _isnum(v: str) -> bool:
531
+ return bool(re.fullmatch(r"\d+(\.\d+)?", v or ""))
532
+
533
+
534
+ def score_rows(rows: list) -> list:
535
+ """r5/r7 = 잔여 용량 %, score = r5 * r7. 측정 불가(status != OK, 파싱 실패) 계정은 score -1 → 선택 대상에서 제외"""
536
+ out = []
537
+ for r in rows:
538
+ if r["status"] == "OK" and _isnum(r["five"]) and _isnum(r["seven"]):
539
+ r5 = max(100 - float(r["five"]), 0.0)
540
+ r7 = max(100 - float(r["seven"]), 0.0)
541
+ out.append(dict(email=r["email"], score=round(r5 * r7, 2), r5=round(r5, 1), r7=round(r7, 1),
542
+ guard=r5 >= AUTO["guard5"] and r7 >= AUTO["guard7"], status=r["status"]))
543
+ else:
544
+ out.append(dict(email=r["email"], score=-1.0, r5=-1.0, r7=-1.0, guard=False, status=r["status"]))
545
+ return out
546
+
547
+
548
+ def auto_best(scored: list, require_guard: bool, cur: str) -> str:
549
+ """우선순위: score → min(r5,r7) → 현재 계정 유지 → 입력 순서"""
550
+ best, bs, bm = "", 0.0, 0.0
551
+ for s in scored:
552
+ if s["score"] < 0 or (require_guard and not s["guard"]):
553
+ continue
554
+ m = min(s["r5"], s["r7"])
555
+ if not best:
556
+ better = True
557
+ elif s["score"] != bs:
558
+ better = s["score"] > bs
559
+ elif m != bm:
560
+ better = m > bm
561
+ elif (s["email"] == cur) != (best == cur):
562
+ better = s["email"] == cur
563
+ else:
564
+ better = False
565
+ if better:
566
+ best, bs, bm = s["email"], s["score"], m
567
+ return best
568
+
569
+
570
+ def fmt_score(v) -> str:
571
+ return "-" if v is None or v < 0 else f"{v:.0f}"
572
+
573
+
574
+ def beats_margin(b: float, a: float, m: int) -> bool:
575
+ if a <= 0:
576
+ return True
577
+ if b <= 0:
578
+ return False
579
+ return b * 100 >= a * (100 + m)
580
+
581
+
582
+ def auto_decide(scored: list, cur: str):
583
+ """→ (action, best, reason). action: keep | switch"""
584
+ by = {s["email"]: s for s in scored}
585
+ best, tag, used_fallback = auto_best(scored, True, cur), "", False
586
+ if not best and AUTO["fallback"]:
587
+ fb = resolve_email(AUTO["fallback"]) or ""
588
+ if fb and by.get(fb, {}).get("score", -1) >= 0:
589
+ best, used_fallback, tag = fb, True, " (fallback)"
590
+ if not best:
591
+ best = auto_best(scored, False, cur)
592
+ if best:
593
+ tag = " (guard 통과 계정 없음)"
594
+ if not best:
595
+ return "keep", "", "선택 가능한 계정 없음"
596
+ cur_score = by.get(cur, {}).get("score", -1.0)
597
+ best_score = by[best]["score"]
598
+ if best == cur:
599
+ return "keep", best, f"이미 최적 (score {fmt_score(cur_score)})"
600
+ if not used_fallback and not beats_margin(best_score, cur_score, AUTO["margin"]):
601
+ return "keep", best, (f"후보 {best} (score {fmt_score(best_score)})가 margin {AUTO['margin']}% 미달 "
602
+ f"(현재 score {fmt_score(cur_score)})")
603
+ return "switch", best, f"score {fmt_score(cur_score)} → {fmt_score(best_score)}{tag}"
604
+
605
+
606
+ # ─── JSON 출력 (TUI 등 외부 도구용) ───────────────────────────
607
+ # 사용량 조회 정책(캐시 · 백오프)과 선택 정책(guard · score · margin)을 그대로 통과시킨다.
608
+
609
+ def _f(v):
610
+ try:
611
+ return float(v)
612
+ except (TypeError, ValueError):
613
+ return None
614
+
615
+
616
+ def all_json() -> dict:
617
+ cur = active_account()
618
+ rows = build_all_rows()
619
+ scored = score_rows(rows)
620
+ action, best, reason = auto_decide(scored, cur)
621
+ accounts = []
622
+ for r, s in zip(rows, scored):
623
+ scoped = []
624
+ for item in filter(None, r["scoped"].split(",")):
625
+ f = item.split(":")
626
+ u = _f(f[2]) if len(f) > 2 else None
627
+ scoped.append({"label": f[0], "group": f[1] if len(f) > 1 else "", "utilization": u,
628
+ "remaining": None if u is None else max(100 - u, 0),
629
+ "resets_at": us.to_int(f[3] if len(f) > 3 else 0)})
630
+ accounts.append({
631
+ "email": r["email"], "active": r["email"] == cur, "status": r["status"], "source": r["source"],
632
+ "fetched_at": r["fetched"],
633
+ "five_hour": {"utilization": _f(r["five"]), "remaining": s["r5"] if s["r5"] >= 0 else None,
634
+ "resets_at": r["five_ep"]},
635
+ "seven_day": {"utilization": _f(r["seven"]), "remaining": s["r7"] if s["r7"] >= 0 else None,
636
+ "resets_at": r["seven_ep"]},
637
+ # 모델/서피스별 한도 (표시 전용 — score/guard 에는 반영되지 않음)
638
+ "scoped": scoped,
639
+ "score": s["score"], "guard_pass": s["guard"], "selectable": s["score"] >= 0,
640
+ })
641
+ return {
642
+ "generated_at": now_s(), "current": cur or None,
643
+ "auto": {"guard_5h": AUTO["guard5"], "guard_7d": AUTO["guard7"], "margin": AUTO["margin"],
644
+ "interval_min": AUTO["interval"]},
645
+ "decision": {"action": action, "best": best or None, "reason": reason},
646
+ "accounts": accounts,
647
+ }
648
+
649
+
650
+ # ─── Swap ─────────────────────────────────────────────────────
651
+
652
+ def restore_account(target: str) -> bool:
653
+ backup = oauth_of(cs.backup_store(target).get())
654
+ if not backup:
655
+ eprint(f"Error: '{target}'의 백업 토큰을 찾을 수 없습니다")
656
+ return False
657
+ active = cs.active_store()
658
+ with cs.storage_lock() as held:
659
+ if not held:
660
+ eprint("Warning: 자격증명 쓰기 락 획득 실패 — 락 없이 진행합니다.")
661
+ # 실행 중인 claude 가 같은 슬롯에 refresh 토큰을 쓰는 경합에 대비해 write → read-back 검증.
662
+ # claudeAiOauth 만 갈아 끼우고 나머지 키(mcpOAuth 등)는 이 PC 것 그대로 둔다.
663
+ for attempt in (1, 2):
664
+ blob = dict(active.get() or {})
665
+ blob["claudeAiOauth"] = backup
666
+ active.set(blob)
667
+ if access_token_of(active.get()) == backup.get("accessToken"):
668
+ break
669
+ if attempt == 2:
670
+ eprint(f"Error: 자격증명 쓰기 검증 실패 ({target}, {active.label}). 다른 프로세스와 경합 중일 수 있습니다.")
671
+ return False
672
+ time.sleep(0.3)
673
+ identity_store(token_fingerprint({"claudeAiOauth": backup}), target)
674
+ # .claude.json oauthAccount 패치
675
+ oa = cs.load_json(us.backup_dir() / target / "oauth-account.json")
676
+ cjp = cs.claude_json_path()
677
+ cj = cs.load_json(cjp)
678
+ if oa and cj is not None:
679
+ cj["oauthAccount"] = oa
680
+ try:
681
+ us.write_atomic(cjp, json.dumps(cj, ensure_ascii=False, indent=2) + "\n")
682
+ except OSError:
683
+ eprint("Warning: .claude.json oauthAccount 패치 실패")
684
+ set_current(target)
685
+ us.mark_switched()
686
+ return True
687
+
688
+
689
+ def do_switch(target: str) -> bool:
690
+ if active_account() == target:
691
+ return True
692
+ # auto_sync_current() 가 직전에 돌았으므로 떠나는 계정 상태는 최신으로 백업돼 있다
693
+ return restore_account(target)
694
+
695
+
696
+ # ─── Commands ─────────────────────────────────────────────────
697
+
698
+ HEADER = ["EMAIL", "5H / RESET", "7D / RESET", "SCOPED", "STATUS"]
699
+
700
+
701
+ def cmd_all() -> int:
702
+ if not ACCOUNTS:
703
+ print("등록된 계정이 없습니다.")
704
+ print("새 계정 추가: claude-switch --add")
705
+ return 0
706
+ cur, now = active_account(), now_s()
707
+ rows = [[" ", *HEADER]]
708
+ for r in build_all_rows():
709
+ rows.append(["*" if r["email"] == cur else " ", r["email"], *display_cells(r, now)])
710
+ print_table(rows)
711
+ return 0
712
+
713
+
714
+ def cmd_switch(query: str) -> int:
715
+ email = resolve_email(query)
716
+ if not email:
717
+ return 1
718
+ cur = active_account()
719
+ if cur == email:
720
+ print(f"이미 활성 계정입니다: {email}")
721
+ return 0
722
+ if not do_switch(email):
723
+ return 1
724
+ print(f"Switched: {cur} → {email}")
725
+ return 0
726
+
727
+
728
+ def cmd_picker() -> int:
729
+ if not ACCOUNTS:
730
+ eprint("등록된 계정이 없습니다.")
731
+ eprint("새 계정 추가: claude-switch --add")
732
+ return 1
733
+ cur, now = active_account(), now_s()
734
+ rows = build_all_rows()
735
+ table = [[" ", *HEADER]] + [["*" if r["email"] == cur else " ", r["email"], *display_cells(r, now)] for r in rows]
736
+ ws = [max(width(t[i]) for t in table) for i in range(len(table[0]))]
737
+ lines = [" ".join(c + " " * (ws[i] - width(c)) for i, c in enumerate(t)).rstrip() for t in table]
738
+ if shutil.which("fzf"):
739
+ r = subprocess.run(["fzf", f"--header={lines[0]}", "--prompt=Claude account> ", "--height=40%",
740
+ "--reverse", "--no-sort"], input="\n".join(lines[1:]), text=True, stdout=subprocess.PIPE)
741
+ choice = r.stdout.strip()
742
+ if r.returncode != 0 or not choice:
743
+ return 0
744
+ selected = next((a for a in ACCOUNTS if a in choice), "")
745
+ else: # fzf 가 없으면 번호로 고른다
746
+ print(" " + lines[0])
747
+ for i, ln in enumerate(lines[1:], 1):
748
+ print(f"{i:2} {ln}")
749
+ try:
750
+ ans = input("번호 (Enter = 취소): ").strip()
751
+ except EOFError:
752
+ return 0
753
+ if not ans:
754
+ return 0
755
+ selected = rows[int(ans) - 1]["email"] if ans.isdigit() and 0 < int(ans) <= len(rows) else ""
756
+ if not selected:
757
+ eprint("Error: 계정 추출 실패")
758
+ return 1
759
+ return cmd_switch(selected)
760
+
761
+
762
+ # ─── 계정 추가: claude auth login 을 시크릿 창으로 ──────────────
763
+ # 일반 창은 기존 claude.ai 세션 계정으로 바로 authorize 돼 버려서 항상 시크릿 창을 쓴다.
764
+
765
+ PRIVATE_FLAGS = {"chrome": "--incognito", "edge": "--inprivate", "brave": "--incognito", "whale": "--incognito",
766
+ "vivaldi": "--incognito", "chromium": "--incognito", "firefox": "--private-window"}
767
+
768
+
769
+ def _kind(s: str) -> str:
770
+ s = s.lower()
771
+ for k in ("edge", "chrome", "brave", "whale", "vivaldi", "chromium", "firefox"):
772
+ if k in s or (k == "edge" and "msedge" in s):
773
+ return k
774
+ return ""
775
+
776
+
777
+ def private_browser() -> Optional[list]:
778
+ """기본 브라우저를 시크릿 창으로 여는 명령 (URL 은 뒤에 붙인다). 못 찾으면 None."""
779
+ if sys.platform == "darwin":
780
+ r = subprocess.run(["defaults", "read",
781
+ str(Path.home() / "Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure"),
782
+ "LSHandlers"], capture_output=True, text=True)
783
+ bid = ""
784
+ role = ""
785
+ for line in r.stdout.splitlines():
786
+ if line.strip().startswith("{"):
787
+ role = ""
788
+ m = re.search(r"LSHandlerRole(All|Viewer) = \"?([^\";]+)", line)
789
+ if m:
790
+ role = m.group(2)
791
+ if "LSHandlerURLScheme = https;" in line and role:
792
+ bid = role
793
+ break
794
+ apps = {"com.microsoft.edgemac": "Microsoft Edge", "com.google.chrome": "Google Chrome",
795
+ "com.brave.browser": "Brave Browser", "com.naver.whale": "Whale", "com.vivaldi.vivaldi": "Vivaldi",
796
+ "org.mozilla.firefox": "Firefox"}
797
+ app = next((v for k, v in apps.items() if bid.lower().startswith(k)), "")
798
+ if not app or not any((d / f"{app}.app").is_dir() for d in (Path("/Applications"), Path.home() / "Applications")):
799
+ return None
800
+ return ["open", "-na", app, "--args", PRIVATE_FLAGS[_kind(app)]]
801
+ if sys.platform == "win32":
802
+ try:
803
+ import winreg
804
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\Shell\Associations"
805
+ r"\UrlAssociations\https\UserChoice") as k:
806
+ prog = winreg.QueryValueEx(k, "ProgId")[0]
807
+ with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, prog + r"\shell\open\command") as k:
808
+ cmd = winreg.QueryValueEx(k, "")[0]
809
+ except OSError:
810
+ return None
811
+ m = re.match(r'\s*"([^"]+)"|\s*(\S+)', cmd)
812
+ exe = (m.group(1) or m.group(2)) if m else ""
813
+ kind = _kind(prog) or _kind(exe)
814
+ return [exe, PRIVATE_FLAGS[kind]] if exe and kind else None
815
+ # Linux: xdg-settings 의 .desktop 이름으로 고른다
816
+ try:
817
+ desk = subprocess.run(["xdg-settings", "get", "default-web-browser"], capture_output=True, text=True).stdout
818
+ except OSError:
819
+ desk = ""
820
+ kind = _kind(desk)
821
+ names = {"chrome": ["google-chrome", "google-chrome-stable"], "edge": ["microsoft-edge", "microsoft-edge-stable"],
822
+ "brave": ["brave-browser"], "chromium": ["chromium", "chromium-browser"], "firefox": ["firefox"],
823
+ "vivaldi": ["vivaldi"], "whale": ["naver-whale"]}
824
+ exe = next((shutil.which(n) for n in names.get(kind, []) if shutil.which(n)), None)
825
+ return [exe, PRIVATE_FLAGS[kind]] if exe else None
826
+
827
+
828
+ def browser_wrapper(cmd: list) -> str:
829
+ """claude 는 $BROWSER 를 "<명령> <url>" 로 부르므로 인자를 붙일 수 없다 → 래퍼 스크립트를 경유한다."""
830
+ if sys.platform == "win32":
831
+ fd, path = tempfile.mkstemp(prefix="claude-switch-browser-", suffix=".cmd")
832
+ body = "@start \"\" " + " ".join(f'"{c}"' for c in cmd) + ' "%~1"\r\n'
833
+ else:
834
+ fd, path = tempfile.mkstemp(prefix="claude-switch-browser-")
835
+ body = "#!/bin/sh\nexec " + " ".join("'" + c.replace("'", "'\\''") + "'" for c in cmd) + ' "$1"\n'
836
+ with os.fdopen(fd, "w") as f:
837
+ f.write(body)
838
+ os.chmod(path, 0o755)
839
+ return path
840
+
841
+
842
+ def cmd_add(email_hint: str = "") -> int:
843
+ print("새 Claude Code 계정 추가\n\n진행 절차:\n 1. claude auth login을 실행합니다.\n"
844
+ " 2. 시크릿 창이 열리면 추가할 계정으로 로그인합니다.\n 3. 로그인 완료 후 자동으로 새 계정이 등록됩니다.")
845
+ if email_hint:
846
+ print(f" (이메일 힌트: {email_hint})")
847
+ print("(일반 창은 기존 claude.ai 세션 계정으로 바로 authorize 돼버려서 항상 시크릿 창을 씁니다)")
848
+ try:
849
+ ans = input("계속 진행할까요? [Y/n] ").strip()
850
+ except EOFError:
851
+ ans = "n"
852
+ if ans[:1] in ("n", "N"):
853
+ print("취소.")
854
+ return 0
855
+ claude = shutil.which("claude")
856
+ if not claude:
857
+ eprint("Error: claude (Claude Code) 를 찾을 수 없습니다.")
858
+ return 1
859
+ env = dict(os.environ)
860
+ wrapper = ""
861
+ cmd = private_browser()
862
+ print()
863
+ if cmd:
864
+ wrapper = browser_wrapper(cmd)
865
+ env["BROWSER"] = wrapper
866
+ print(f"→ 시크릿 창으로 엽니다 ({os.path.basename(cmd[0]) if cmd[0] != 'open' else cmd[2]}). "
867
+ "안 뜨면 아래 URL을 시크릿 창에 직접 붙여넣으세요.")
868
+ else:
869
+ # 아무 창도 안 열리게 한다 (Claude Code 자신도 bg 세션에 쓰는 방식)
870
+ env["BROWSER"] = "cmd /c rem" if sys.platform == "win32" else "true"
871
+ print("→ 기본 브라우저를 시크릿 창으로 자동으로 열 수 없어 브라우저를 열지 않습니다.")
872
+ print(" 곧 출력되는 URL을 복사해 시크릿 창에 붙여넣으세요.")
873
+ sb = (cs.load_json(cs.config_dir() / "settings.json") or {}).get("browser")
874
+ if sb:
875
+ eprint(f'Warning: settings.json 에 browser="{sb}" 가 있어 위 방식이 무시되고 그 브라우저로 열립니다.')
876
+ print("\n─── claude auth login 실행 ───")
877
+ try:
878
+ rc = subprocess.call([claude, "auth", "login", *(["--email", email_hint] if email_hint else [])], env=env)
879
+ finally:
880
+ if wrapper:
881
+ try:
882
+ os.unlink(wrapper)
883
+ except OSError:
884
+ pass
885
+ if rc != 0:
886
+ eprint("Error: claude auth login 실패")
887
+ return 1
888
+ print("\n─── 상태 sync 중... ───")
889
+ auto_sync_current()
890
+ discover_accounts()
891
+ new = active_account() # 방금 로그인한 계정. 예전 dead · 백오프 표시를 걷어 바로 다시 조회한다
892
+ if new:
893
+ dead_clear(new)
894
+ backoff_clear(new)
895
+ print("\n=== 현재 등록된 계정 ===")
896
+ cmd_all()
897
+ print("\n참고: 현재 활성 계정은 방금 로그인한 계정입니다.\n다른 계정으로 스왑: claude-switch <email-or-prefix>")
898
+ return 0
899
+
900
+
901
+ def cmd_remove(query: str) -> int:
902
+ email = resolve_email(query)
903
+ if not email:
904
+ return 1
905
+ if email == active_account():
906
+ eprint("Error: 현재 활성 계정은 제거할 수 없습니다. 먼저 다른 계정으로 스왑하세요.")
907
+ return 1
908
+ print(f"제거 대상: {email}")
909
+ print(f" - {us.backup_dir() / email}/ (oauthAccount 백업)")
910
+ print(f" - {cs.backup_store(email).label}")
911
+ print(" - usage 캐시 / 백오프 / dead 표시 / identity 캐시 항목")
912
+ try:
913
+ ans = input("정말 제거할까요? [y/N] ").strip()
914
+ except EOFError:
915
+ ans = ""
916
+ if ans[:1] not in ("y", "Y"):
917
+ print("취소.")
918
+ return 0
919
+ cs.backup_store(email).delete()
920
+ shutil.rmtree(us.backup_dir() / email, ignore_errors=True)
921
+ us.delete(email)
922
+ identity_forget(email)
923
+ print(f"Removed: {email}")
924
+ return 0
925
+
926
+
927
+ # ─── auto: 사용량 기반 자동 전환 ───────────────────────────────
928
+
929
+ def auto_log(msg: str) -> None:
930
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
931
+
932
+
933
+ def claude_running() -> bool:
934
+ """claude 세션이 떠 있는지 (프로세스 이름이 정확히 claude 인 것만)."""
935
+ try:
936
+ if sys.platform == "win32":
937
+ r = subprocess.run(["tasklist", "/FI", "IMAGENAME eq claude.exe", "/NH"], capture_output=True, text=True)
938
+ return "claude.exe" in r.stdout.lower()
939
+ return subprocess.run(["pgrep", "-x", "claude"], capture_output=True).returncode == 0
940
+ except OSError:
941
+ return False
942
+
943
+
944
+ def auto_print_table(rows: list, scored: list, cur: str) -> None:
945
+ now = now_s()
946
+ table = [[" ", "EMAIL", "5H / RESET", "7D / RESET", "SCOPED", "SCORE", "STATUS"]]
947
+ for r, s in zip(rows, scored):
948
+ st = r["status"] + (age(r["fetched"], now) if r["source"] == "cached" else "")
949
+ if s["score"] >= 0 and not s["guard"]:
950
+ st += " (guard)"
951
+ table.append(["*" if r["email"] == cur else " ", r["email"], cell(r["five"], r["five_ep"], now),
952
+ cell(r["seven"], r["seven_ep"], now), scoped_cell(r["scoped"], now), fmt_score(s["score"]), st])
953
+ print_table(table, indent=" ")
954
+
955
+
956
+ def auto_cycle() -> bool:
957
+ auto_sync_current()
958
+ discover_accounts()
959
+ if not ACCOUNTS:
960
+ auto_log("등록된 계정이 없습니다 (claude-switch --add).")
961
+ return False
962
+ rows = build_all_rows()
963
+ cur = active_account()
964
+ scored = score_rows(rows)
965
+ auto_print_table(rows, scored, cur)
966
+ if not any(s["score"] >= 0 for s in scored):
967
+ auto_log("측정 가능한 계정 없음 (usage API 실패 또는 rate limit).")
968
+ return False
969
+ action, best, reason = auto_decide(scored, cur)
970
+ if action != "switch":
971
+ auto_log(f"유지: {cur or '(없음)'} — {reason}")
972
+ return True
973
+ if AUTO["dry"]:
974
+ auto_log(f"[dry-run] 전환 대상: {cur} → {best} ({reason})")
975
+ return True
976
+ running = claude_running()
977
+ if running and not AUTO["hot"]:
978
+ auto_log(f"보류: claude 실행 중이라 전환하지 않음 (--no-hot). 대상: {best}")
979
+ return True
980
+ if do_switch(best):
981
+ tail = f" — claude 실행 중이라 최대 {SWAP_APPLY_S}s 내 다음 요청부터 적용" if running else ""
982
+ auto_log(f"전환: {cur} → {best} ({reason}){tail}")
983
+ return True
984
+ auto_log(f"전환 실패: {cur} → {best}")
985
+ return False
986
+
987
+
988
+ AUTO_HELP = """claude-switch auto: 사용량 기반 자동 계정 전환
989
+
990
+ Usage:
991
+ claude-switch auto [옵션]
992
+
993
+ 옵션:
994
+ --once 1회만 실행하고 종료
995
+ --dry-run 전환하지 않고 선택 결과만 출력
996
+ --interval <분> 갱신 주기 (기본 {interval}, 1~1440)
997
+ --5h-guard <%> 5시간 잔여 용량 최소치 (기본 {guard5})
998
+ --7d-guard <%> 7일 잔여 용량 최소치 (기본 {guard7})
999
+ --margin <%> 현재 계정 대비 최소 개선폭 (기본 {margin})
1000
+ --fallback <email|prefix> guard 통과 계정이 없을 때 폴백 대상
1001
+ --no-hot claude 실행 중이면 전환 보류 (기본: 실행 중에도 전환)
1002
+ -h, --help 이 도움말
1003
+
1004
+ 선택 규칙:
1005
+ score = (5H 잔여%) × (7D 잔여%)
1006
+ 1) status가 OK가 아닌 계정 제외
1007
+ 2) guard(5H/7D 잔여 용량) 미달 계정 제외
1008
+ 3) score 최대 계정 선택 (동점: min(5H,7D) → 현재 계정 유지 순)
1009
+ 4) 현재 계정보다 margin% 이상 나을 때만 전환
1010
+ 5) guard 통과 계정이 없으면 --fallback, 그것도 없으면 잔여 용량 최다 계정
1011
+
1012
+ hot-swap:
1013
+ 실행 중인 claude 는 자격증명을 다시 읽으므로 (macOS Keychain 은 {apply}s 캐시) 재시작 없이 다음 요청부터 새 계정이 적용됩니다.
1014
+ 전환 시 Claude Code 와 같은 쓰기 락(<config>/.storage-write.lock)을 잡고 write 후 read-back 검증을 합니다.
1015
+ 주의: 실행 중인 세션의 UI(계정 표시)는 시작 시점 값이라 갱신되지 않을 수 있습니다."""
1016
+
1017
+
1018
+ def cmd_auto(args: list) -> int:
1019
+ ints = {"--interval": ("interval", 1, 1440), "--5h-guard": ("guard5", 0, 100), "--five-hour-guard": ("guard5", 0, 100),
1020
+ "--7d-guard": ("guard7", 0, 100), "--weekly-guard": ("guard7", 0, 100),
1021
+ "--margin": ("margin", 0, 1000), "--switch-margin": ("margin", 0, 1000)}
1022
+ i = 0
1023
+ while i < len(args):
1024
+ a = args[i]
1025
+ if a == "--once":
1026
+ AUTO["once"] = True
1027
+ elif a == "--dry-run":
1028
+ AUTO["dry"] = True
1029
+ elif a == "--no-hot":
1030
+ AUTO["hot"] = False
1031
+ elif a == "--hot":
1032
+ AUTO["hot"] = True
1033
+ elif a in ("-h", "--help"):
1034
+ print(AUTO_HELP.format(apply=SWAP_APPLY_S, **AUTO))
1035
+ return 0
1036
+ elif a in ints or a == "--fallback":
1037
+ v = args[i + 1] if i + 1 < len(args) else ""
1038
+ if not v or v.startswith("-"):
1039
+ eprint(f"Error: {a} 옵션에 값이 필요합니다 (claude-switch auto --help)")
1040
+ return 1
1041
+ if a == "--fallback":
1042
+ AUTO["fallback"] = v
1043
+ else:
1044
+ key, lo, hi = ints[a]
1045
+ if not v.isdigit() or not lo <= int(v) <= hi:
1046
+ eprint(f"Error: {a} 값이 올바르지 않습니다: '{v}' (허용: {lo}~{hi} 정수)")
1047
+ return 1
1048
+ AUTO[key] = int(v)
1049
+ i += 1
1050
+ else:
1051
+ eprint(f"Error: 알 수 없는 옵션 '{a}' (claude-switch auto --help)")
1052
+ return 1
1053
+ i += 1
1054
+ mode = "hot-swap on" if AUTO["hot"] else "hot-swap off"
1055
+ if AUTO["dry"]:
1056
+ mode += ", dry-run"
1057
+ auto_log(f"auto 시작 — {AUTO['interval']}분 주기, guard 5H≥{AUTO['guard5']}% / 7D≥{AUTO['guard7']}%, "
1058
+ f"margin {AUTO['margin']}%, {mode}")
1059
+ fail_streak = 0
1060
+ try:
1061
+ while True:
1062
+ fail_streak = 0 if auto_cycle() else fail_streak + 1
1063
+ if AUTO["once"]:
1064
+ break
1065
+ wait = AUTO["interval"] * 60
1066
+ # 조회가 연달아 실패하면(대개 usage API rate limit) 주기를 늘려 스스로 압력을 낮춘다
1067
+ if fail_streak:
1068
+ wait *= min(fail_streak + 1, 5)
1069
+ auto_log(f"연속 실패 {fail_streak}회 → {wait}s 후 재시도")
1070
+ time.sleep(wait)
1071
+ except KeyboardInterrupt:
1072
+ print()
1073
+ auto_log("중지됨.")
1074
+ return 0
1075
+
1076
+
1077
+ # ─── TUI ──────────────────────────────────────────────────────
1078
+
1079
+ def cmd_tui(args: list) -> int:
1080
+ py = HERE / "claude-switch-tui.py"
1081
+ if not py.is_file():
1082
+ eprint(f"Error: TUI 스크립트를 찾을 수 없습니다: {py}")
1083
+ return 1
1084
+ env = dict(os.environ, CLAUDE_SWITCH_ENGINE=str(Path(__file__).resolve()))
1085
+ uv = shutil.which("uv")
1086
+ if uv:
1087
+ # uv 가 의존성(textual)을 알아서 처리한다 (PEP 723 인라인 메타데이터).
1088
+ # uv 는 기본으로 자기 인증서 목록만 믿어 회사 TLS 검사 아래에선 pypi 를 못 받는다 → OS 인증서 저장소를 쓰게 한다
1089
+ env.setdefault("UV_SYSTEM_CERTS", "1")
1090
+ env.setdefault("UV_NATIVE_TLS", "1")
1091
+ return subprocess.call([uv, "run", "--quiet", "--script", str(py), *args], env=env)
1092
+ if subprocess.run([sys.executable, "-c", "import textual"], capture_output=True).returncode == 0:
1093
+ return subprocess.call([sys.executable, str(py), *args], env=env)
1094
+ eprint("Error: TUI 실행에 uv 또는 textual 이 필요합니다.\n uv 설치 (권장 — 의존성 자동 처리): "
1095
+ "https://docs.astral.sh/uv/ (macOS: brew install uv)\n 또는 pip install textual")
1096
+ return 1
1097
+
1098
+
1099
+ # ─── Main ─────────────────────────────────────────────────────
1100
+
1101
+ HELP = """claude-switch: 단일 config + 이메일 기반 다중 계정 런처 (macOS · Linux · Windows)
1102
+
1103
+ Usage:
1104
+ claude-switch 인터랙티브 picker (스왑만, fzf 가 없으면 번호로 고른다)
1105
+ claude-switch <email> 해당 이메일로 스왑 (claude 실행 안 함)
1106
+ claude-switch <prefix> prefix 매칭 (유일할 때만, 예: 'whqu')
1107
+ claude-switch --all, -a 모든 계정 상태 출력
1108
+ claude-switch --all --json 상태 + auto 판정을 JSON으로 출력 (외부 도구용)
1109
+ claude-switch --all --fresh usage 캐시({ttl}s) 무시하고 즉시 재조회 (--json 과 조합 가능)
1110
+ claude-switch auto [opts] 사용량 기반 자동 전환 (기본 {interval}분 주기, auto --help)
1111
+ claude-switch tui 라이브 TUI (사용량 모니터 + 전환, uv 또는 textual 필요)
1112
+ claude-switch --add [email] 새 계정 추가 (claude auth login을 시크릿 창으로 실행)
1113
+ claude-switch --remove <q> 계정 백업 제거
1114
+ claude-switch --sync 활성 자격증명을 계정 백업에 옮기기만 한다 (thuthi-accounts Stop 훅이 턴마다 부른다)
1115
+ claude-switch -h 이 도움말
1116
+
1117
+ 스왑 후 claude 실행: 스왑 완료되면 'claude'를 실행하세요. 실행 중인 claude 도 다음 요청부터 새 계정을 쓴다.
1118
+
1119
+ Accounts (현재 활성: {current}):
1120
+ {accounts}
1121
+
1122
+ 동작 방식:
1123
+ - config dir = {config} 하나 (모든 state 공유)
1124
+ - 스왑 = 활성 자격증명({store})의 claudeAiOauth 교체 + .claude.json 의 oauthAccount 패치
1125
+ - 매 실행마다 현재 상태 auto-sync → /login으로 새 계정 추가 시 자동 등록
1126
+ - 활성 토큰의 소유 계정은 백업 대조 → 캐시 → /api/oauth/profile 순으로 확정
1127
+
1128
+ State:
1129
+ {state}/"""
1130
+
1131
+
1132
+ def main(argv: list) -> int:
1133
+ global USAGE_TTL
1134
+ try:
1135
+ sys.stdout.reconfigure(encoding="utf-8") # Windows 콘솔에서도 한글 · 기호가 깨지지 않게
1136
+ sys.stderr.reconfigure(encoding="utf-8")
1137
+ except (AttributeError, ValueError):
1138
+ pass
1139
+ if argv[:1] == ["--sync-hook"]:
1140
+ # thuthi-accounts Stop 훅: 턴마다 sync 를 떼어 내 돌리고 바로 끝난다 (Claude 가 기다리지 않게)
1141
+ sys.stdin.read()
1142
+ try:
1143
+ import install # 낡은 launcher 를 지금 판으로 (플러그인 이름이 바뀐 뒤 등)
1144
+ install.refresh_launcher()
1145
+ except Exception: # noqa: BLE001 훅은 어떤 경우에도 턴을 막지 않는다
1146
+ pass
1147
+ kw = dict(stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True)
1148
+ if sys.platform == "win32":
1149
+ kw["creationflags"] = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
1150
+ else:
1151
+ kw["start_new_session"] = True
1152
+ try:
1153
+ subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "--sync"], **kw)
1154
+ except OSError:
1155
+ pass
1156
+ return 0
1157
+ if argv[:1] in (["-h"], ["--help"]):
1158
+ discover_accounts()
1159
+ print(HELP.format(ttl=USAGE_TTL, interval=AUTO["interval"], current=active_account(),
1160
+ accounts="\n".join(f" {a}" for a in ACCOUNTS) or " (없음)", config=cs.config_dir(),
1161
+ store=cs.active_store().label, state=STATE))
1162
+ return 0
1163
+ # 모든 명령 실행 전에 현재 상태 sync (신규 계정 자동 등록 포함)
1164
+ auto_sync_current()
1165
+ if argv[:1] == ["--sync"]:
1166
+ # sync 만 (thuthi-accounts Stop 훅이 --sync-hook 으로 턴마다 떼어 내 부른다). Claude Code 가 토큰을 갱신하면 refresh token 이 바뀌는데,
1167
+ # 그 뒤 /login 등으로 활성 자격증명이 덮이기 전에 백업에 옮겨 두지 않으면 그 계정은 재로그인해야 한다
1168
+ return 0
1169
+ discover_accounts()
1170
+ if not argv:
1171
+ return cmd_picker()
1172
+ a = argv[0]
1173
+ if a in ("--all", "-a", "--json", "--fresh"):
1174
+ want_json = False
1175
+ for x in argv:
1176
+ if x in ("--all", "-a"):
1177
+ continue
1178
+ if x == "--json":
1179
+ want_json = True
1180
+ elif x == "--fresh":
1181
+ USAGE_TTL = 0 # 캐시 무시 → 백오프/dead 아닌 계정은 usage API 즉시 조회
1182
+ else:
1183
+ eprint(f"Error: 알 수 없는 옵션 '{x}' (--all [--json] [--fresh])")
1184
+ return 1
1185
+ if want_json:
1186
+ print(json.dumps(all_json(), ensure_ascii=False, indent=2))
1187
+ return 0
1188
+ return cmd_all()
1189
+ if a == "--add":
1190
+ return cmd_add(argv[1] if len(argv) > 1 else "")
1191
+ if a == "--remove":
1192
+ if len(argv) < 2:
1193
+ eprint("Usage: claude-switch --remove <email|prefix>")
1194
+ return 1
1195
+ return cmd_remove(argv[1])
1196
+ if a in ("tui", "--tui"):
1197
+ return cmd_tui(argv[1:])
1198
+ if a in ("auto", "--auto"):
1199
+ return cmd_auto(argv[1:])
1200
+ return cmd_switch(a)
1201
+
1202
+
1203
+ if __name__ == "__main__":
1204
+ sys.exit(main(sys.argv[1:]))