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,491 @@
1
+ #!/usr/bin/env python3
2
+ """claude-switch · statusline · 설치를 가짜 Anthropic API 와 임시 HOME 으로 끝까지 돌려 본다 (macOS · Linux · Windows).
3
+
4
+ python3 tests/selftest.py exit 0 = 통과
5
+
6
+ 진짜 자격증명은 건드리지 않는다:
7
+ - HOME · USERPROFILE · 상태 폴더는 임시 폴더다 (Linux · Windows 의 .credentials.json 도 그 안)
8
+ - macOS 는 임시 keychain 파일(CLAUDE_SWITCH_KEYCHAIN)과 시험용 서비스 이름(CLAUDE_SWITCH_KC_SERVICE)을 쓴다
9
+ - Windows 자격 증명 관리자 시험도 시험용 서비스 이름만 쓰고 끝나면 지운다
10
+ - API 는 127.0.0.1 의 가짜 서버다 (CLAUDE_SWITCH_API_BASE · CLAUDE_SWITCH_CONSOLE_BASE)
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ import shutil
17
+ import subprocess
18
+ import sys
19
+ import tempfile
20
+ import threading
21
+ import time
22
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
23
+ from pathlib import Path
24
+
25
+ HERE = Path(__file__).resolve().parent
26
+ TOOL = HERE.parent # tools/claude-switch
27
+ PLUGIN = TOOL.parents[1] # plugins/thuthi-accounts
28
+ REPO = PLUGIN.parents[1]
29
+ ENGINE = TOOL / "claude_switch.py"
30
+ STATUSLINE = PLUGIN / "tools" / "statusline" / "statusline.py"
31
+ WIN, MAC = sys.platform == "win32", sys.platform == "darwin"
32
+ SERVICE = f"claude-switch-selftest-{os.getpid()}"
33
+ FAILS: list = []
34
+
35
+
36
+ def check(cond: bool, what: str, detail: str = "") -> None:
37
+ print((" ok " if cond else " FAIL ") + what + ("" if cond else f"\n {detail}"), flush=True)
38
+ if not cond:
39
+ FAILS.append(what)
40
+
41
+
42
+ # ─── 가짜 Anthropic API ───────────────────────────────────────
43
+
44
+ class Api:
45
+ owners = {} # access token → email
46
+ usage = {} # access token → (five, seven) 또는 "429"
47
+ refresh = {} # refresh token → (새 access, 새 refresh) 또는 "dead"
48
+ calls = []
49
+
50
+
51
+ class Handler(BaseHTTPRequestHandler):
52
+ def log_message(self, *a):
53
+ pass
54
+
55
+ def _send(self, code: int, body: dict) -> None:
56
+ data = json.dumps(body).encode()
57
+ self.send_response(code)
58
+ self.send_header("Content-Type", "application/json")
59
+ self.send_header("Content-Length", str(len(data)))
60
+ self.end_headers()
61
+ self.wfile.write(data)
62
+
63
+ def _token(self) -> str:
64
+ return (self.headers.get("Authorization") or "").replace("Bearer ", "")
65
+
66
+ def do_GET(self):
67
+ tok = self._token()
68
+ Api.calls.append((self.path, tok))
69
+ if self.path == "/api/oauth/profile":
70
+ if tok in Api.owners:
71
+ return self._send(200, {"account": {"email": Api.owners[tok]}})
72
+ return self._send(401, {"error": {"type": "authentication_error", "message": "invalid"}})
73
+ if self.path == "/api/oauth/usage":
74
+ u = Api.usage.get(tok)
75
+ if u is None:
76
+ return self._send(401, {"error": {"type": "authentication_error", "message": "OAuth token invalid"}})
77
+ if u == "429":
78
+ return self._send(429, {"error": {"type": "rate_limit_error", "message": "Rate limited"}})
79
+ reset5 = time.strftime("%Y-%m-%dT%H:%M:%S.123456+00:00", time.gmtime(time.time() + 3600))
80
+ reset7 = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() + 86400 * 3))
81
+ return self._send(200, {"five_hour": {"utilization": u[0], "resets_at": reset5},
82
+ "seven_day": {"utilization": u[1], "resets_at": reset7},
83
+ "limits": [{"scope": {"model": {"display_name": "Fable"}}, "group": "weekly",
84
+ "percent": 7, "resets_at": reset7}]})
85
+ self._send(404, {"error": "not found"})
86
+
87
+ def do_POST(self):
88
+ n = int(self.headers.get("Content-Length") or 0)
89
+ body = json.loads(self.rfile.read(n) or b"{}")
90
+ Api.calls.append((self.path, body.get("refresh_token")))
91
+ if self.path == "/v1/oauth/token":
92
+ r = Api.refresh.get(body.get("refresh_token"))
93
+ if r is None or r == "dead":
94
+ return self._send(400, {"error": "invalid_grant", "error_description": "refresh token revoked"})
95
+ return self._send(200, {"access_token": r[0], "refresh_token": r[1], "expires_in": 28800,
96
+ "scope": "user:inference user:profile"})
97
+ self._send(404, {"error": "not found"})
98
+
99
+
100
+ # ─── 시험 환경 ────────────────────────────────────────────────
101
+
102
+ def oauth(at: str, rt: str, exp_ms: int) -> dict:
103
+ return {"claudeAiOauth": {"accessToken": at, "refreshToken": rt, "expiresAt": exp_ms,
104
+ "scopes": ["user:inference"], "subscriptionType": "max"}}
105
+
106
+
107
+ class Env:
108
+ def __init__(self, port: int, extra: dict = None):
109
+ self.root = Path(tempfile.mkdtemp(prefix="cs-selftest-"))
110
+ self.home = self.root / "home"
111
+ (self.home / ".claude").mkdir(parents=True)
112
+ self.env = dict(os.environ)
113
+ for k in ("CLAUDE_CONFIG_DIR", "CLAUDE_SWITCH_STATE_DIR", "CLAUDE_SWITCH_STORE", "XDG_CACHE_HOME",
114
+ "CLAUDE_CODE_FORCE_WINDOWS_CREDMAN"):
115
+ self.env.pop(k, None)
116
+ self.env.update(HOME=str(self.home), USERPROFILE=str(self.home), PYTHONIOENCODING="utf-8",
117
+ CLAUDE_SWITCH_API_BASE=f"http://127.0.0.1:{port}",
118
+ CLAUDE_SWITCH_CONSOLE_BASE=f"http://127.0.0.1:{port}",
119
+ CLAUDE_SWITCH_KC_SERVICE=SERVICE, **(extra or {}))
120
+ self.keychain = ""
121
+ if MAC: # 임시 keychain 파일. 로그인 keychain 은 건드리지 않는다
122
+ self.keychain = str(self.root / "selftest.keychain-db")
123
+ subprocess.run(["security", "create-keychain", "-p", "selftest", self.keychain], check=True)
124
+ subprocess.run(["security", "unlock-keychain", "-p", "selftest", self.keychain], check=True)
125
+ subprocess.run(["security", "set-keychain-settings", self.keychain], check=True) # 자동 잠금 끄기
126
+ self.env["CLAUDE_SWITCH_KEYCHAIN"] = self.keychain
127
+ for k in ("CLAUDE_CODE_FORCE_WINDOWS_CREDMAN",):
128
+ os.environ.pop(k, None)
129
+ os.environ.update({k: v for k, v in self.env.items()
130
+ if k.startswith(("CLAUDE_SWITCH", "HOME", "USERPROFILE", "CLAUDE_CODE_FORCE"))})
131
+
132
+ def close(self):
133
+ if self.keychain:
134
+ subprocess.run(["security", "delete-keychain", self.keychain], capture_output=True)
135
+ shutil.rmtree(self.root, ignore_errors=True)
136
+
137
+ @property
138
+ def state(self) -> Path:
139
+ return self.home / ".local" / "share" / "claude-switch"
140
+
141
+ def run(self, *args, stdin: str = "", script: Path = ENGINE, extra: dict = None):
142
+ env = dict(self.env, **(extra or {}))
143
+ r = subprocess.run([sys.executable, str(script), *args], input=stdin, capture_output=True, text=True,
144
+ env=env, timeout=60, encoding="utf-8")
145
+ return r.returncode, r.stdout, r.stderr
146
+
147
+ def login_as(self, blob: dict, email: str) -> None:
148
+ """claude 에서 /login 한 것처럼 활성 자격증명과 .claude.json 을 바꾼다."""
149
+ import credstore as cs
150
+ cs.active_store().set(blob)
151
+ cj = self.home / ".claude.json"
152
+ data = json.loads(cj.read_text()) if cj.exists() else {"numStartups": 3}
153
+ data["oauthAccount"] = {"emailAddress": email, "organizationName": f"org of {email}"}
154
+ cj.write_text(json.dumps(data))
155
+
156
+ def active(self) -> dict:
157
+ import credstore as cs
158
+ return cs.active_store().get() or {}
159
+
160
+
161
+ # ─── 시험 ─────────────────────────────────────────────────────
162
+
163
+ def test_engine(e: Env) -> None:
164
+ sys.path.insert(0, str(TOOL))
165
+ sys.path.insert(0, str(PLUGIN / "lib"))
166
+ import credstore as cs
167
+ far = int(time.time() * 1000) + 8 * 3600 * 1000
168
+ Api.owners.update({"tA": "a@x.com", "tB": "b@x.com", "tB2": "b@x.com", "tC": "c@x.com"})
169
+ Api.usage.update({"tA": (10.0, 20.0), "tB": (30.0, 10.0), "tB2": (31.0, 11.0)})
170
+
171
+ print(f"[엔진] 저장소: {cs.active_store().label}")
172
+ # 1) 첫 계정: 활성 자격증명만 있으면 profile API 로 이메일을 찾아 자동 등록한다
173
+ blobA = oauth("tA", "rA", far)
174
+ blobA["mcpOAuth"] = {"server|1": {"accessToken": "mcp-secret"}} # 계정과 상관없는 키는 바꾸지 않아야 한다
175
+ e.login_as(blobA, "a@x.com")
176
+ code, out, err = e.run("--all", "--json")
177
+ j = json.loads(out) if code == 0 else {}
178
+ check(code == 0 and j.get("current") == "a@x.com", "첫 계정 자동 등록", err or out)
179
+ a = (j.get("accounts") or [{}])[0]
180
+ check(a.get("five_hour", {}).get("utilization") == 10.0 and a.get("source") == "live", "usage API 조회", out)
181
+ check(a.get("scoped") and a["scoped"][0]["label"] == "Fable", "scoped 한도", out)
182
+ check(abs(a.get("five_hour", {}).get("resets_at", 0) - (time.time() + 3600)) < 5, "소수초 · 오프셋 시각 파싱", out)
183
+ check((e.state / "backups" / "a@x.com" / "oauth-account.json").is_file(), "oauthAccount 백업")
184
+ check(oauth_of(cs.backup_store("a@x.com").get()).get("accessToken") == "tA", "자격증명 백업")
185
+ if not WIN and not MAC:
186
+ for f in (e.home / ".claude" / ".credentials.json", e.state / "backups" / "a@x.com" / "credentials.json"):
187
+ check(f.is_file() and (f.stat().st_mode & 0o777) == 0o600, f"{f.name} 권한 0600", oct(f.stat().st_mode))
188
+
189
+ # 2) 두 번째 계정: /login 으로 바꾸면 다음 실행에 자동 등록된다
190
+ e.login_as(oauth("tB", "rB", far), "b@x.com")
191
+ code, out, err = e.run("--all")
192
+ check(code == 0 and "b@x.com" in out and "a@x.com" in out, "두 번째 계정 자동 등록", err or out)
193
+ check((e.state / "current").read_text().strip() == "b@x.com", "current = b")
194
+
195
+ # 3) 캐시: 5분 안에는 API 를 다시 부르지 않는다
196
+ n = len([c for c in Api.calls if c[0] == "/api/oauth/usage"])
197
+ e.run("--all")
198
+ check(len([c for c in Api.calls if c[0] == "/api/oauth/usage"]) == n, "usage 캐시 (API 재호출 없음)")
199
+ code, out, _ = e.run("--all", "--json", "--fresh")
200
+ check(len([c for c in Api.calls if c[0] == "/api/oauth/usage"]) > n, "--fresh 는 바로 조회")
201
+
202
+ # 4) 전환: claudeAiOauth 만 바뀌고 다른 키 · .claude.json · switched-at 이 맞는다
203
+ act = e.active()
204
+ act["mcpOAuth"] = {"server|1": {"accessToken": "mcp-secret"}}
205
+ cs.active_store().set(act)
206
+ code, out, err = e.run("a@x")
207
+ act = e.active()
208
+ check(code == 0 and "Switched: b@x.com → a@x.com" in out, "prefix 로 전환", err or out)
209
+ check(oauth_of(act).get("accessToken") == "tA", "활성 자격증명이 a")
210
+ check(act.get("mcpOAuth", {}).get("server|1", {}).get("accessToken") == "mcp-secret", "다른 키(mcpOAuth) 보존")
211
+ cj = json.loads((e.home / ".claude.json").read_text())
212
+ check(cj["oauthAccount"]["emailAddress"] == "a@x.com" and cj.get("numStartups") == 3, ".claude.json oauthAccount 만 패치")
213
+ check((e.state / "switched-at").is_file(), "switched-at 기록")
214
+ code, out, _ = e.run("a@x.com")
215
+ check("이미 활성 계정" in out, "같은 계정이면 그대로")
216
+ code, out, err = e.run("zzz")
217
+ check(code == 1 and "계정 없음" in err, "없는 계정은 오류")
218
+
219
+ # 5) refresh: 만료된 백업 토큰은 refresh 해서 저장하고 조회한다
220
+ cs.backup_store("b@x.com").set(oauth("tB", "rB", int(time.time() * 1000) - 1000))
221
+ Api.refresh["rB"] = ("tB2", "rB2")
222
+ code, out, err = e.run("--all", "--json", "--fresh")
223
+ b = next((x for x in json.loads(out)["accounts"] if x["email"] == "b@x.com"), {})
224
+ o = oauth_of(cs.backup_store("b@x.com").get())
225
+ check(o.get("accessToken") == "tB2" and o.get("refreshToken") == "rB2" and o.get("expiresAt", 0) > time.time() * 1000,
226
+ "만료 토큰 refresh 후 백업에 저장", json.dumps(o))
227
+ check(o.get("subscriptionType") == "max" and o.get("scopes") == ["user:inference", "user:profile"], "refresh 때 다른 필드 보존 · scope 반영")
228
+ check(b.get("five_hour", {}).get("utilization") == 31.0, "refresh 한 토큰으로 조회", out)
229
+
230
+ # 6) refresh token 폐기 → dead (재로그인 필요), 이후 네트워크를 타지 않는다
231
+ e.login_as(oauth("tC", "rC", int(time.time() * 1000) - 1000), "c@x.com")
232
+ Api.owners["tC"] = "c@x.com"
233
+ e.run("--all", "--json", "--fresh")
234
+ check((e.state / "dead" / "c@x.com").is_file(), "폐기된 refresh token → dead 표시")
235
+ n = len(Api.calls)
236
+ code, out, err = e.run("--all", "--json", "--fresh")
237
+ c = next((x for x in json.loads(out)["accounts"] if x["email"] == "c@x.com"), {}) if code == 0 else {}
238
+ check(c.get("source") == "dead" and "재로그인" in (c.get("status") or ""), "이후 재로그인 필요로 표시", out[:400] + err)
239
+ check(not [x for x in Api.calls[n:] if x[1] in ("tC", "rC")], "dead 계정은 네트워크를 타지 않음")
240
+ e.run("a@x.com")
241
+
242
+ # 7) 백오프: usage 가 실패하면 그 계정은 일정 시간 건너뛴다
243
+ Api.usage["tA"] = "429"
244
+ code, out, _ = e.run("--all", "--json", "--fresh")
245
+ a = next(x for x in json.loads(out)["accounts"] if x["email"] == "a@x.com")
246
+ check(a["status"].startswith("Rate limited") and (e.state / "backoff" / "a@x.com").is_file(), "실패 → 백오프 기록", out[:300])
247
+ code, out, _ = e.run("--all", "--json", "--fresh")
248
+ a = next(x for x in json.loads(out)["accounts"] if x["email"] == "a@x.com")
249
+ check(a["status"].startswith("backoff"), "백오프 중엔 건너뜀")
250
+ (e.state / "backoff" / "a@x.com").unlink()
251
+ (e.state / "usage-cache" / "a@x.com").unlink(missing_ok=True)
252
+ Api.usage["tA"] = (95.0, 40.0)
253
+
254
+ # 8) auto: a 가 한도 근처면 b 로 (dry-run 은 바꾸지 않는다)
255
+ code, out, err = e.run("auto", "--once", "--dry-run")
256
+ check("[dry-run] 전환 대상: a@x.com → b@x.com" in out, "auto --dry-run 판정", out + err)
257
+ check(oauth_of(e.active()).get("accessToken") == "tA", "dry-run 은 그대로")
258
+ code, out, err = e.run("auto", "--once")
259
+ check("전환: a@x.com → b@x.com" in out and oauth_of(e.active()).get("accessToken") == "tB2", "auto 전환", out + err)
260
+ code, out, _ = e.run("auto", "--interval", "0")
261
+ check(code == 1, "auto 옵션 검사")
262
+
263
+ # 9) statusline: 세션 값 되쓰기 + 후보 계정
264
+ Api.usage["tA"] = (5.0, 5.0)
265
+ e.run("--all", "--fresh")
266
+ now = int(time.time())
267
+ # 전환 직후 60초 안에 처음 본 값은 되쓰지 않는다
268
+ sw = e.state / "switched-at"
269
+ sw.write_text(str(now))
270
+ inp = {"session_id": "s1", "model": {"display_name": "Opus"},
271
+ "rate_limits": {"five_hour": {"used_percentage": 88, "resets_at": now + 3600},
272
+ "seven_day": {"used_percentage": 40, "resets_at": now + 86400}}}
273
+ code, out, err = e.run(stdin=json.dumps(inp), script=STATUSLINE)
274
+ import usage_store as us
275
+ check(us.read("b@x.com").five != "88", "전환 직후에는 되쓰지 않음", us.read("b@x.com").line())
276
+ sw.write_text(str(now - 3600))
277
+ time.sleep(1.1) # 캐시와 같은 초면 "더 최신" 이 아니라 되쓰지 않는다
278
+ inp["session_id"] = "s2"
279
+ code, out, err = e.run(stdin=json.dumps(inp), script=STATUSLINE)
280
+ plain = strip_ansi(out)
281
+ check(code == 0 and us.read("b@x.com").five == "88", "세션 값을 공용 캐시에 되씀", us.read("b@x.com").line() + err)
282
+ check(us.read("b@x.com").scoped.startswith("Fable"), "되쓸 때 scoped 보존")
283
+ check("5h 88%" in plain and "→a 5h 5% 7d 5%" in plain, "후보 계정 표시", plain)
284
+ code, out, _ = e.run(stdin='{"session_id":"s3","model":{"display_name":"Opus"}}', script=STATUSLINE)
285
+ check(code == 0 and "Opus" in strip_ansi(out), "rate_limits 없는 입력", out)
286
+
287
+ # 10) remove
288
+ code, out, err = e.run("--remove", "c@x.com", stdin="y\n")
289
+ check(code == 0 and not (e.state / "backups" / "c@x.com").exists() and cs.backup_store("c@x.com").get() is None,
290
+ "계정 제거", out + err)
291
+ code, out, err = e.run("--remove", "b@x.com", stdin="y\n")
292
+ check(code == 1, "활성 계정은 제거 안 됨")
293
+
294
+
295
+ def test_install(e: Env) -> None:
296
+ print("[설치]")
297
+ plugins = e.home / ".claude" / "plugins"
298
+ plugins.mkdir(parents=True, exist_ok=True)
299
+ (plugins / "known_marketplaces.json").write_text(json.dumps({"thuthi-plugin": {
300
+ "source": {"source": "directory", "path": str(REPO)}, "installLocation": str(REPO)}}))
301
+ (e.home / ".claude" / "settings.json").write_text(json.dumps({"model": "opus", "statusLine": {
302
+ "type": "command", "command": "old", "refreshInterval": 30, "padding": 1}}))
303
+ bin_dir = e.home / ".local" / "bin"
304
+ bin_dir.mkdir(parents=True)
305
+ (bin_dir / "claude-switch").write_text("old copy")
306
+ inst = TOOL / "install.py"
307
+ code, out, err = e.run("shims", script=inst)
308
+ check(code == 0 and (e.state / "launch.py").is_file(), "launcher 생성", out + err)
309
+ check(any((e.state / "replaced").rglob("claude-switch")), "예전 복사본은 옮겨 둔다")
310
+ # 0.11 까지의 launcher (플러그인 이름 thuthi) 는 Stop 훅이 지금 판으로 다시 쓴다. 우리 것이 아닌 파일은 건드리지 않는다
311
+ fresh = (e.state / "launch.py").read_bytes().decode("utf-8")
312
+ (e.state / "launch.py").write_text(fresh.replace('"thuthi-accounts"', '"thuthi"').replace("thuthi-accounts@", "thuthi@"),
313
+ encoding="utf-8")
314
+ code, out, err = e.run("--sync-hook", stdin="{}")
315
+ check(code == 0 and (e.state / "launch.py").read_bytes().decode("utf-8") == fresh, "Stop 훅이 낡은 launcher 를 고친다",
316
+ out + err)
317
+ (e.state / "launch.py").write_text("someone else's file\n", encoding="utf-8")
318
+ e.run("--sync-hook", stdin="{}")
319
+ check((e.state / "launch.py").read_text(encoding="utf-8") == "someone else's file\n", "남의 launcher 는 그대로 둔다")
320
+ (e.state / "launch.py").write_bytes(fresh.encode("utf-8")) # write_text 는 Windows 에서 \r\n 으로 바꿔 "낡았다" 가 된다
321
+ # 0.11 launcher 는 플러그인 thuthi 의 tools/ 를 찾는다. 거기 둔 다리가 thuthi-accounts 를 실행하고 launcher 를 새 판으로 바꾼다
322
+ old = fresh.replace('"thuthi-accounts"', '"thuthi"').replace("thuthi-accounts@", "thuthi@")
323
+ (e.state / "launch.py").write_bytes(old.encode("utf-8"))
324
+ code, out, err = e.run("statusline", stdin='{"session_id":"old","model":{"display_name":"Opus"}}', script=e.state / "launch.py")
325
+ check(code == 0 and "Opus" in strip_ansi(out), "0.11 launcher → 다리 → statusline", out + err)
326
+ check((e.state / "launch.py").read_bytes().decode("utf-8") == fresh, "다리가 launcher 를 새 판으로 바꾼다")
327
+ (e.state / "launch.py").write_bytes(old.encode("utf-8"))
328
+ code, out, err = e.run("claude-switch", "--all", script=e.state / "launch.py")
329
+ check(code == 0 and "a@x.com" in out, "0.11 launcher → 다리 → claude-switch", out + err)
330
+ (e.state / "launch.py").write_bytes(fresh.encode("utf-8"))
331
+ code, out, err = e.run("statusline", script=inst)
332
+ s = json.loads((e.home / ".claude" / "settings.json").read_text())
333
+ check(code == 0 and s["statusLine"]["refreshInterval"] == 30 and s["statusLine"]["padding"] == 1 and s["model"] == "opus",
334
+ "statusLine 교체 (다른 키 보존)", json.dumps(s))
335
+ check(any((e.home / ".claude").glob("settings.json.bak-thuthi-*")), "settings.json 백업")
336
+ code, out, err = e.run("check", script=inst, extra={"PATH": str(bin_dir) + os.pathsep + e.env.get("PATH", "")})
337
+ check("✗" not in out, "설치 점검이 모두 통과", out + err)
338
+
339
+ # shim 으로 엔진 실행
340
+ env = dict(e.env, PATH=str(bin_dir) + os.pathsep + e.env.get("PATH", ""))
341
+ if WIN:
342
+ r = subprocess.run(["cmd", "/c", str(bin_dir / "claude-switch.cmd"), "--all"], capture_output=True, text=True,
343
+ env=env, encoding="utf-8", timeout=60)
344
+ check(r.returncode == 0 and "b@x.com" in r.stdout, "claude-switch.cmd (cmd)", r.stdout + r.stderr)
345
+ r = subprocess.run(["powershell", "-NoProfile", "-Command", "claude-switch --all"], capture_output=True,
346
+ text=True, env=env, encoding="utf-8", timeout=60)
347
+ check(r.returncode == 0 and "b@x.com" in r.stdout, "claude-switch (PowerShell)", r.stdout + r.stderr)
348
+ bash = git_bash() if WIN else "/bin/sh"
349
+ if bash:
350
+ r = subprocess.run([bash, "-c", "claude-switch --all"], capture_output=True, text=True, env=env,
351
+ encoding="utf-8", timeout=60)
352
+ check(r.returncode == 0 and "b@x.com" in r.stdout, f"claude-switch ({os.path.basename(bash)})", r.stdout + r.stderr)
353
+
354
+ # statusLine 명령을 Claude Code 처럼 셸로 돌린다 (stdin JSON)
355
+ cmd = s["statusLine"]["command"]
356
+ inp = '{"session_id":"inst","model":{"display_name":"Opus"}}'
357
+ shells = [["powershell", "-NoProfile", "-Command", cmd]] if WIN else []
358
+ if bash:
359
+ shells.append([bash, "-c", cmd])
360
+ for sh in shells:
361
+ r = subprocess.run(sh, input=inp, capture_output=True, text=True, env=env, encoding="utf-8", timeout=60)
362
+ check(r.returncode == 0 and "Opus" in strip_ansi(r.stdout), f"statusLine 명령 ({os.path.basename(sh[0])})",
363
+ f"cmd={cmd!r}\n{r.stdout}{r.stderr}")
364
+
365
+
366
+ def git_bash() -> str:
367
+ """Windows 의 Git Bash (System32 의 bash.exe 는 WSL 이라 쓰지 않는다)."""
368
+ for c in (Path(os.environ.get("ProgramFiles", r"C:\Program Files")) / "Git" / "bin" / "bash.exe",
369
+ Path(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")) / "Git" / "bin" / "bash.exe"):
370
+ if c.is_file():
371
+ return str(c)
372
+ found = shutil.which("bash")
373
+ return found if found and "system32" not in found.lower() else ""
374
+
375
+
376
+ def test_engine_credman(port: int) -> None:
377
+ """Windows 자격 증명 관리자 모드 (CLAUDE_CODE_FORCE_WINDOWS_CREDMAN=1) 로 등록 · 전환."""
378
+ print("[엔진 · 자격 증명 관리자 모드]")
379
+ e = Env(port, {"CLAUDE_CODE_FORCE_WINDOWS_CREDMAN": "1"})
380
+ import importlib
381
+ import credstore as cs
382
+ importlib.reload(cs)
383
+ try:
384
+ st = cs.active_store()
385
+ check("자격 증명 관리자" in st.label, "활성 저장소 = 자격 증명 관리자", st.label)
386
+ far = int(time.time() * 1000) + 8 * 3600 * 1000
387
+ big = oauth("tA", "rA", far)
388
+ big["mcpOAuth"] = {"s": "z" * 3000} # 조각 여러 개
389
+ e.login_as(big, "a@x.com")
390
+ code, out, err = e.run("--all", "--json")
391
+ check(code == 0 and json.loads(out).get("current") == "a@x.com", "등록", out + err)
392
+ cm = cs.CredmanStore(SERVICE, cs.os_user())
393
+ cm.set(dict(oauth("tB", "rB", far), mcpOAuth={"s": "z" * 3000}))
394
+ (e.home / ".claude.json").write_text(json.dumps({"oauthAccount": {"emailAddress": "b@x.com"}}))
395
+ code, out, err = e.run("--all")
396
+ code, out, err = e.run("a@x.com")
397
+ got = cm.get() or {}
398
+ check(code == 0 and oauth_of(got).get("accessToken") == "tA" and len(got.get("mcpOAuth", {}).get("s", "")) == 3000,
399
+ "자격 증명 관리자에 전환 (조각 · 다른 키 보존)", out + err)
400
+ check(not (e.home / ".claude" / ".credentials.json").exists(), "파일에는 쓰지 않음")
401
+ cm.delete()
402
+ finally:
403
+ e.close()
404
+ os.environ.pop("CLAUDE_CODE_FORCE_WINDOWS_CREDMAN", None)
405
+
406
+
407
+ def test_credman() -> None:
408
+ """Windows 자격 증명 관리자: Claude Code(Bun.secrets) 형식 그대로 읽고 쓰는지. 시험용 서비스 이름만 쓴다."""
409
+ print("[자격 증명 관리자]")
410
+ import credstore as cs
411
+ st = cs.CredmanStore(SERVICE + "-cm", "selftest")
412
+ try:
413
+ small = {"claudeAiOauth": {"accessToken": "a" * 100}}
414
+ check(st.set(small) and st.get() == small, "짧은 값 쓰기 · 읽기")
415
+ big = {"claudeAiOauth": {"accessToken": "b" * 3000}, "mcpOAuth": {"x": "y" * 2500}}
416
+ check(st.set(big) and st.get() == big, "2400자 넘는 값은 조각으로")
417
+ check(st.set(small) and st.get() == small, "조각 수가 줄면 남은 조각 정리")
418
+ left = st.cm.targets(f"{SERVICE}-cm/*")
419
+ check(sorted(left) == sorted([f"{SERVICE}-cm/selftest#0", f"{SERVICE}-cm/selftest#m"]), "남는 항목은 #0 · #m 뿐", str(left))
420
+ bun = shutil.which("bun")
421
+ if bun:
422
+ # Bun.secrets 로 쓴 값을 우리가 읽고, 우리가 쓴 값을 Bun.secrets 로 읽는다 (Claude Code 가 쓰는 API)
423
+ js = Path(tempfile.mkdtemp()) / "t.js"
424
+ js.write_text(
425
+ "const s = Bun.secrets; const svc = process.argv[2];\n"
426
+ "if (process.argv[3] === 'write') { await s.set({service: svc, name: 'bunuser#m', value: JSON.stringify({n:1,l:"
427
+ "process.argv[4].length})}); await s.set({service: svc, name: 'bunuser#0', value: process.argv[4]}); }\n"
428
+ "else { console.log(await s.get({service: svc, name: 'selftest#m'})); console.log(await s.get({service: svc, name: 'selftest#0'})); }\n")
429
+ payload = json.dumps({"claudeAiOauth": {"accessToken": "from-bun"}}, separators=(",", ":"))
430
+ r = subprocess.run([bun, str(js), SERVICE + "-cm", "write", payload], capture_output=True, text=True)
431
+ got = cs.CredmanStore(SERVICE + "-cm", "bunuser").get()
432
+ check(r.returncode == 0 and got == json.loads(payload), "Bun.secrets 가 쓴 값을 읽음", r.stderr + str(got)
433
+ + str(st.cm.targets(f"{SERVICE}-cm*")))
434
+ r = subprocess.run([bun, str(js), SERVICE + "-cm", "read"], capture_output=True, text=True)
435
+ lines = r.stdout.strip().splitlines()
436
+ check(len(lines) == 2 and json.loads(lines[0]).get("n") == 1 and json.loads(lines[1]) == small,
437
+ "우리가 쓴 값을 Bun.secrets 가 읽음", r.stdout + r.stderr)
438
+ cs.CredmanStore(SERVICE + "-cm", "bunuser").delete()
439
+ else:
440
+ print(" skip Bun.secrets 호환 (bun 없음)")
441
+ finally:
442
+ st.delete()
443
+ check(not st.cm.targets(f"{SERVICE}-cm*"), "시험 항목을 다 지움")
444
+
445
+
446
+ def test_keychain(e: Env) -> None:
447
+ print("[macOS Keychain]")
448
+ import credstore as cs
449
+ st = cs.KeychainStore(SERVICE + "-kc")
450
+ small = {"claudeAiOauth": {"accessToken": "k" * 50}}
451
+ check(st.set(small) and st.get() == small, "stdin(-i) 로 쓰기 · 읽기")
452
+ big = {"claudeAiOauth": {"accessToken": "k" * 2500}}
453
+ check(st.set(big) and st.get() == big, "긴 값 (인자 경로)")
454
+ check(st.delete() and st.get() is None, "지우기")
455
+
456
+
457
+ def oauth_of(blob) -> dict:
458
+ return (blob or {}).get("claudeAiOauth") or {}
459
+
460
+
461
+ def strip_ansi(s: str) -> str:
462
+ import re
463
+ return re.sub(r"\x1b\[[0-9;]*m", "", s)
464
+
465
+
466
+ def main() -> int:
467
+ try:
468
+ sys.stdout.reconfigure(encoding="utf-8")
469
+ except (AttributeError, ValueError):
470
+ pass
471
+ srv = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
472
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
473
+ e = Env(srv.server_address[1])
474
+ print(f"platform={sys.platform} python={sys.version.split()[0]} tmp={e.root}")
475
+ try:
476
+ test_engine(e)
477
+ test_install(e)
478
+ if MAC:
479
+ test_keychain(e)
480
+ if WIN:
481
+ test_credman()
482
+ test_engine_credman(srv.server_address[1])
483
+ finally:
484
+ srv.shutdown()
485
+ e.close()
486
+ print(f"\n{'통과' if not FAILS else f'실패 {len(FAILS)}건: ' + ', '.join(FAILS)}")
487
+ return 1 if FAILS else 0
488
+
489
+
490
+ if __name__ == "__main__":
491
+ sys.exit(main())