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,188 @@
1
+ #!/usr/bin/env python3
2
+ """setup doctor 와 플러그인 나눔을 레포에서 바로 돌려 본다 (macOS · Linux · Windows, python3 3.9 표준 라이브러리만).
3
+
4
+ python3 plugins/thuthi/skills/setup/scripts/selftest.py exit 0 = 통과
5
+
6
+ - 켜진 플러그인 찾기: 가짜 `claude plugin list --json` · installed_plugins.json + settings.json · 기록 없음 (레포 전부)
7
+ - 켜진 플러그인만 점검하고 꺼진 것은 건너뛴다고 찍는다
8
+ - 공용 파일 복사본이 원본과 같고 (scripts/sync_shared.py), plugins/ 에 심링크가 없다 (Windows 기본 git 은 심링크를 텍스트로 받는다)
9
+ - 플러그인마다: setup_check.py 를 부를 수 있다, lib/ 의 공용 파일을 import 한다, SessionStart 훅이 가리키는
10
+ context.md 가 있다, notify 가드 matcher 가 MCP 도구 이름과 같다, dependencies 가 마켓플레이스에 있다
11
+ - 옮긴 스킬을 옛 이름(thuthi:<스킬>)으로 부르는 곳이 남지 않았다
12
+ 진짜 설정은 건드리지 않는다 (CLAUDE_CONFIG_DIR 를 임시 폴더로 바꾼다).
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import os
18
+ import re
19
+ import subprocess
20
+ import sys
21
+ import tempfile
22
+ from pathlib import Path
23
+
24
+ HERE = Path(__file__).resolve().parent
25
+ DOCTOR = HERE / "doctor.py"
26
+ PLUGINS = HERE.parents[3] # <repo>/plugins
27
+ REPO = PLUGINS.parent
28
+ MARKET = "thuthi-plugin"
29
+ WIN = sys.platform == "win32"
30
+ FAILS: list = []
31
+
32
+
33
+ def check(cond: bool, what: str, detail: str = "") -> None:
34
+ print((" ok " if cond else " FAIL ") + what + ("" if cond else f"\n {detail}"), flush=True)
35
+ if not cond:
36
+ FAILS.append(what)
37
+
38
+
39
+ def load(p: Path) -> dict:
40
+ return json.loads(p.read_text(encoding="utf-8"))
41
+
42
+
43
+ def import_doctor(cfg: Path):
44
+ os.environ["CLAUDE_CONFIG_DIR"] = str(cfg)
45
+ import importlib.util
46
+ spec = importlib.util.spec_from_file_location(f"doctor_{cfg.name}", DOCTOR)
47
+ mod = importlib.util.module_from_spec(spec)
48
+ spec.loader.exec_module(mod)
49
+ return mod
50
+
51
+
52
+ def test_layout() -> None:
53
+ print("[나눔]")
54
+ market = load(REPO / ".claude-plugin" / "marketplace.json")
55
+ names = [p["name"] for p in market["plugins"]]
56
+ dirs = sorted(d.parent.parent.name for d in PLUGINS.glob("*/.claude-plugin/plugin.json"))
57
+ check(sorted(names) == dirs, "marketplace.json 의 플러그인 = plugins/ 의 폴더", f"{names} / {dirs}")
58
+ for name in names:
59
+ root = PLUGINS / name
60
+ man = load(root / ".claude-plugin" / "plugin.json")
61
+ check(man.get("name") == name, f"{name}: plugin.json 이름")
62
+ deps = man.get("dependencies") or []
63
+ check(all(d in names for d in deps), f"{name}: dependencies 가 이 마켓플레이스에 있다", str(deps))
64
+ if name != "thuthi":
65
+ check("thuthi" in deps, f"{name}: 바탕 플러그인 thuthi 에 의존 (setup 이 같이 켜진다)", str(deps))
66
+ check((root / "setup_check.py").is_file(), f"{name}: setup_check.py")
67
+ hooks = root / "hooks" / "hooks.json"
68
+ if hooks.is_file():
69
+ text = hooks.read_text(encoding="utf-8")
70
+ if "context.md" in text:
71
+ ctx = root / "context.md"
72
+ check(ctx.is_file() and ctx.read_text(encoding="utf-8").strip(), f"{name}: SessionStart 가 넣는 context.md")
73
+ mcp = root / ".mcp.json"
74
+ if mcp.is_file():
75
+ servers = list(load(mcp).get("mcpServers") or {})
76
+ want = {f"mcp__plugin_{name}_{s}__notify" for s in servers}
77
+ matchers = {m.get("matcher") for ms in (load(hooks).get("hooks") or {}).get("PreToolUse", []) for m in [ms]}
78
+ check(bool(want & matchers), f"{name}: 가드 matcher = MCP 도구 이름 (mcp__plugin_<플러그인>_<서버>__notify)",
79
+ f"want {want} got {matchers}")
80
+
81
+
82
+ def test_shared() -> None:
83
+ print("[공용 파일 복사본]")
84
+ sys.path.insert(0, str(REPO / "scripts"))
85
+ import sync_shared
86
+ diffs = [f"{dst.relative_to(REPO)}: {why}" for src, dst in sync_shared.pairs() for why in [sync_shared.differs(src, dst)] if why]
87
+ check(not diffs, "복사본이 원본과 같다 (다르면 python3 scripts/sync_shared.py)", "\n ".join(diffs))
88
+ links = [str(p.relative_to(REPO)) for p in PLUGINS.rglob("*") if p.is_symlink()]
89
+ check(not links, "plugins/ 에 심링크가 없다", ", ".join(links))
90
+ for name, mod in (("thuthi-agenda-picker", "pbpage"), ("thuthi-demo-video", "pbpage"), ("thuthi-arch-diagram", "pbpage"),
91
+ ("thuthi-notify", "tls")):
92
+ lib = PLUGINS / name / "lib"
93
+ code = f"import sys; sys.path.insert(0, {str(lib)!r}); import {mod}; print({mod}.__file__)"
94
+ r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, encoding="utf-8", errors="replace")
95
+ check(r.returncode == 0, f"{name}: lib/{mod}.py 를 import 한다", r.stderr[-400:])
96
+ rules = PLUGINS / "thuthi-agenda-picker" / "skills" / "agenda-picker" / "references" / "design-rules.md"
97
+ check(rules.is_file() and "## 10" in rules.read_text(encoding="utf-8"),
98
+ "agenda-picker: references/design-rules.md (arch-diagram 문서, SKILL.md 가 §10 을 가리킨다)")
99
+
100
+
101
+ def test_old_names() -> None:
102
+ print("[옛 스킬 이름]")
103
+ old = re.compile(r"(?<![\w/-])thuthi:(agenda-picker|arch-diagram|claude-switch|demo-video|orca-new-work|parallel-browser)\b")
104
+ hits = []
105
+ for f in PLUGINS.rglob("*"):
106
+ if f.is_file() and not f.is_symlink() and f.suffix in (".md", ".py", ".json", ".ts", ".js", ".html", ".cmd", ""):
107
+ try:
108
+ text = f.read_text(encoding="utf-8")
109
+ except (UnicodeDecodeError, OSError):
110
+ continue
111
+ hits += [f"{f.relative_to(REPO)}: {m.group(0)}" for m in old.finditer(text)]
112
+ check(not hits, "plugins/ 에 thuthi:<옮긴 스킬> 이 남지 않았다", "\n ".join(hits[:10]))
113
+
114
+
115
+ def test_discovery(tmp: Path) -> None:
116
+ print("[켜진 플러그인 찾기]")
117
+ # 1) 기록 없음 → 레포의 플러그인 전부
118
+ d = import_doctor(tmp / "empty")
119
+ d._from_cli = lambda: None
120
+ on, off, missing, how, errors = d.plugins()
121
+ check(set(on) >= {"thuthi-browser", "thuthi-notify"} and not off, "기록이 없으면 레포의 플러그인 전부", f"{how} {on} {off}")
122
+
123
+ # 2) installed_plugins.json + settings.json (claude 명령이 없을 때)
124
+ cfg = tmp / "files"
125
+ (cfg / "plugins").mkdir(parents=True)
126
+ (cfg / "plugins" / "installed_plugins.json").write_text(json.dumps({"version": 2, "plugins": {
127
+ f"thuthi@{MARKET}": [{"installPath": str(PLUGINS / "thuthi")}],
128
+ f"thuthi-orca@{MARKET}": [{"installPath": str(tmp / "old-cache")}], # setup_check.py 가 없는 예전 캐시
129
+ f"thuthi-notify@{MARKET}": [{"installPath": str(PLUGINS / "thuthi-notify")}],
130
+ "other@elsewhere": [{"installPath": "/nowhere"}]}}))
131
+ (cfg / "settings.json").write_text(json.dumps({"enabledPlugins": {f"thuthi-notify@{MARKET}": False}}))
132
+ d = import_doctor(cfg)
133
+ d._from_cli = lambda: None
134
+ on, off, missing, how, errors = d.plugins()
135
+ check(set(on) == {"thuthi", "thuthi-orca"} and off == ["thuthi-notify"], "설치 기록 + settings 의 끄기", f"{on} {off}")
136
+ check(on.get("thuthi-orca") == PLUGINS / "thuthi-orca", "기록된 폴더에 setup_check.py 가 없으면 원본 폴더", str(on))
137
+ check("thuthi-browser" in missing and "thuthi-orca" not in missing and "thuthi-notify" not in missing,
138
+ "마켓플레이스에 있지만 안 깐 플러그인", str(missing))
139
+ on, off, *_ = d.plugins(include_off=True)
140
+ check({"thuthi-notify", "thuthi-browser"} <= set(on), "--all 은 꺼진 것 · 설치 안 한 것까지", str(on))
141
+
142
+ # 3) 가짜 claude 명령: thuthi-orca 만 켜짐 → 그 줄만 찍고 나머지는 건너뛴다고 알린다
143
+ if WIN:
144
+ print(" -- 가짜 claude 명령 시험은 Windows 에서 건너뛴다 (.cmd 감싸기)")
145
+ return
146
+ bin_dir = tmp / "bin"
147
+ bin_dir.mkdir()
148
+ rows = [{"id": f"thuthi@{MARKET}", "enabled": True, "installPath": str(PLUGINS / "thuthi")},
149
+ {"id": f"thuthi-orca@{MARKET}", "enabled": True, "readFromFolder": str(PLUGINS / "thuthi-orca")},
150
+ {"id": f"thuthi-browser@{MARKET}", "enabled": False, "installPath": str(PLUGINS / "thuthi-browser")},
151
+ {"id": f"thuthi-notify@{MARKET}", "enabled": True, "readFromFolder": str(PLUGINS / "thuthi-notify"),
152
+ "errors": ['Dependency "thuthi@thuthi-plugin" is disabled — enable it or remove the dependency']},
153
+ {"id": "thuthi-orca@other-market", "enabled": True, "installPath": "/nowhere"}]
154
+ fake = bin_dir / "claude"
155
+ fake.write_text(f"#!/bin/sh\ncat <<'JSON'\n{json.dumps(rows)}\nJSON\n")
156
+ fake.chmod(0o755)
157
+ env = dict(os.environ, CLAUDE_CONFIG_DIR=str(tmp / "cli"), PATH=str(bin_dir) + os.pathsep + os.environ.get("PATH", ""),
158
+ PYTHONIOENCODING="utf-8")
159
+ r = subprocess.run([sys.executable, str(DOCTOR)], capture_output=True, text=True, encoding="utf-8", env=env, timeout=120)
160
+ out = r.stdout
161
+ check("orca CLI" in out and "parallel-browser" not in out.split("점검한 플러그인")[0],
162
+ "켜진 플러그인(thuthi-orca · thuthi-notify)만 점검한다", out[-800:] + r.stderr[-400:])
163
+ check("점검한 플러그인 (claude plugin list): thuthi, thuthi-notify, thuthi-orca" in out and "건너뜀: thuthi-browser" in out
164
+ and "claude plugin enable" in out, "꺼진 플러그인은 건너뛴다고 찍는다 (켜기는 enable)", out[-400:])
165
+ check("✗ 불러오기 실패" in out and "is disabled" in out and r.returncode == 1, "불러오지 못한 플러그인 (의존성 꺼짐) 은 ✗",
166
+ out[-600:])
167
+ check("설치 안 됨: thuthi-accounts" in out and "claude plugin install" in out, "안 깐 thuthi 플러그인을 알린다", out[-400:])
168
+ r = subprocess.run([sys.executable, str(DOCTOR), "fix", "nothing"], capture_output=True, text=True, encoding="utf-8",
169
+ env=env, timeout=60)
170
+ check(r.returncode == 2 and "모르는 항목" in r.stderr, "fix: 모르는 항목은 exit 2", r.stdout + r.stderr)
171
+
172
+
173
+ def main() -> int:
174
+ try:
175
+ sys.stdout.reconfigure(encoding="utf-8")
176
+ except (AttributeError, ValueError):
177
+ pass
178
+ test_layout()
179
+ test_shared()
180
+ test_old_names()
181
+ with tempfile.TemporaryDirectory() as t:
182
+ test_discovery(Path(t))
183
+ print("\n" + ("통과" if not FAILS else f"실패 {len(FAILS)}건: " + ", ".join(FAILS)))
184
+ return 1 if FAILS else 0
185
+
186
+
187
+ if __name__ == "__main__":
188
+ sys.exit(main())
@@ -0,0 +1,8 @@
1
+ # 0.11 launcher 다리: 진짜 코드는 thuthi-accounts 플러그인의 tools/claude-switch/claude_switch.py 에 있다 (../legacy_launcher.py)
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
6
+ import legacy_launcher # noqa: E402
7
+
8
+ legacy_launcher.forward("tools/claude-switch/claude_switch.py")
@@ -0,0 +1,65 @@
1
+ """0.11 launcher 다리. 0.11 까지 thuthi:setup 이 깐 ~/.local/share/claude-switch/launch.py 는 플러그인 thuthi 의
2
+ tools/statusline/statusline.py · tools/claude-switch/claude_switch.py 를 찾는다. 0.12.0 에서 그 코드가 thuthi-accounts
3
+ 플러그인으로 옮겨 가, 업데이트만 한 PC 는 statusline 에 "thuthi 플러그인을 못 찾았다" 가 떴다 (2026-10-23 Windows).
4
+ 그래서 그 자리에 다리를 두어 thuthi-accounts 의 같은 파일을 실행하고, launcher 를 새 판으로 바꿔 쓴다
5
+ (그다음부터는 launcher 가 thuthi-accounts 를 바로 찾는다). python3 3.9 표준 라이브러리만.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import runpy
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ MARKET, PLUGIN = "thuthi-plugin", "thuthi-accounts"
16
+
17
+
18
+ def _load(p: Path) -> dict:
19
+ try:
20
+ return json.loads(p.read_text(encoding="utf-8"))
21
+ except (OSError, ValueError):
22
+ return {}
23
+
24
+
25
+ def roots() -> list:
26
+ """새 launcher 와 같은 순서: 로컬 경로 마켓플레이스 원본 → 설치 기록 → 마켓플레이스 레포."""
27
+ cfg = Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude") / "plugins"
28
+ km = _load(cfg / "known_marketplaces.json").get(MARKET) or {}
29
+ loc = km.get("installLocation")
30
+ out = []
31
+ if loc and (km.get("source") or {}).get("source") == "directory":
32
+ out.append(Path(loc) / "plugins" / PLUGIN)
33
+ for e in _load(cfg / "installed_plugins.json").get("plugins", {}).get(f"{PLUGIN}@{MARKET}") or []:
34
+ if isinstance(e, dict) and e.get("installPath"):
35
+ out.append(Path(e["installPath"]))
36
+ if loc:
37
+ out.append(Path(loc) / "plugins" / PLUGIN)
38
+ out.append(Path(__file__).resolve().parents[2] / PLUGIN) # 레포에서 바로 돌릴 때 (옆 폴더)
39
+ return out
40
+
41
+
42
+ def forward(rel: str) -> None:
43
+ for root in roots():
44
+ f = root / rel
45
+ if not f.is_file():
46
+ continue
47
+ try: # launcher 를 새 판으로 (우리 것이고 낡았을 때만 쓴다)
48
+ sys.path.insert(0, str(root / "tools" / "claude-switch"))
49
+ import install
50
+ install.refresh_launcher()
51
+ except Exception: # noqa: BLE001 statusline 은 어떤 경우에도 찍는다
52
+ pass
53
+ sys.argv[0] = str(f)
54
+ sys.path.insert(0, str(f.parent))
55
+ runpy.run_path(str(f), run_name="__main__")
56
+ return
57
+ try:
58
+ sys.stdout.reconfigure(encoding="utf-8") # Windows 는 cp949 로 찍혀 statusline 에서 글자가 깨졌다
59
+ except (AttributeError, ValueError):
60
+ pass
61
+ msg = f"thuthi-accounts 플러그인이 없다: claude plugin install {PLUGIN}@{MARKET}"
62
+ if rel.endswith("statusline.py"):
63
+ print(msg)
64
+ return
65
+ sys.exit(msg)
@@ -0,0 +1,8 @@
1
+ # 0.11 launcher 다리: 진짜 코드는 thuthi-accounts 플러그인의 tools/statusline/statusline.py 에 있다 (../legacy_launcher.py)
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
6
+ import legacy_launcher # noqa: E402
7
+
8
+ legacy_launcher.forward("tools/statusline/statusline.py")
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "thuthi-accounts",
3
+ "version": "0.12.3",
4
+ "description": "계정: claude-switch 스킬 + statusline. Claude 구독 계정 여러 개의 사용량을 보고 다른 계정으로 바꾼다 (macOS · Linux · Windows). 턴마다 자격증명 백업을 맞추는 Stop 훅 포함",
5
+ "author": {
6
+ "name": "thuthi"
7
+ },
8
+ "dependencies": ["thuthi"]
9
+ }
@@ -0,0 +1,5 @@
1
+ #!/bin/sh
2
+ # Claude 세션 Bash 용 (플러그인 bin/ 은 세션 Bash 의 PATH 에 붙는다). 터미널용은 thuthi:setup 이 만든 ~/.local/bin/claude-switch
3
+ here=$(cd "$(dirname "$0")" && pwd)
4
+ py=$(command -v python3 || command -v python)
5
+ exec "$py" "$here/../tools/claude-switch/claude_switch.py" "$@"
@@ -0,0 +1,4 @@
1
+ @echo off
2
+ REM claude-switch for Claude session shells on Windows (plugin bin/). The terminal command is made by thuthi:setup.
3
+ where py >nul 2>nul
4
+ if %errorlevel%==0 (py -3 "%~dp0..\tools\claude-switch\claude_switch.py" %*) else (python "%~dp0..\tools\claude-switch\claude_switch.py" %*)
@@ -0,0 +1,15 @@
1
+ {
2
+ "hooks": {
3
+ "Stop": [
4
+ {
5
+ "hooks": [
6
+ {
7
+ "type": "command",
8
+ "command": "P=$(command -v python3 || command -v python); \"$P\" \"${CLAUDE_PLUGIN_ROOT}/tools/claude-switch/claude_switch.py\" --sync-hook",
9
+ "timeout": 10
10
+ }
11
+ ]
12
+ }
13
+ ]
14
+ }
15
+ }
@@ -0,0 +1,68 @@
1
+ """HTTPS 용 SSL context (python3 3.9 표준 라이브러리만). 회사 TLS 검사 아래에서도 붙게 CA 를 더 싣는다.
2
+
3
+ - 기본 CA (Windows 는 여기서 시스템 인증서 저장소를 싣는다)
4
+ - SSL_CERT_FILE · REQUESTS_CA_BUNDLE · NODE_EXTRA_CA_CERTS 파일 (Claude Code 도 NODE_EXTRA_CA_CERTS 를 쓴다)
5
+ - macOS: 키체인(시스템 · 로그인) 인증서 모음. python 의 OpenSSL 은 키체인을 보지 않는다 (하루 캐시)
6
+ - Python 3.13 부터 기본인 X.509 엄격 검사는 끈다. 회사 CA(Authority Key Identifier 없음 등)를 거부하기 때문이다.
7
+ curl · Node 처럼 체인 · 호스트 이름 검증만 한다 (Docker debian python 3.13 실측)
8
+ claude-switch 엔진과 알림 훅이 같이 쓴다.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import ssl
14
+ import subprocess
15
+ import sys
16
+ import time
17
+ from pathlib import Path
18
+ from typing import Optional
19
+
20
+ _SSL = None
21
+
22
+
23
+ def _cache_dir() -> Path:
24
+ env = os.environ.get("CLAUDE_SWITCH_STATE_DIR")
25
+ return Path(env) if env else Path.home() / ".local" / "share" / "claude-switch"
26
+
27
+
28
+ def _macos_ca_bundle() -> Optional[str]:
29
+ path = _cache_dir() / "ca-macos.pem"
30
+ try:
31
+ if path.exists() and time.time() - path.stat().st_mtime < 86400 and path.stat().st_size > 0:
32
+ return str(path)
33
+ pems = []
34
+ for args in (["security", "find-certificate", "-a", "-p"],
35
+ ["security", "find-certificate", "-a", "-p", "/Library/Keychains/System.keychain"],
36
+ ["security", "find-certificate", "-a", "-p", "/System/Library/Keychains/SystemRootCertificates.keychain"]):
37
+ r = subprocess.run(args, capture_output=True, text=True, timeout=20)
38
+ if r.returncode == 0:
39
+ pems.append(r.stdout)
40
+ text = "".join(pems)
41
+ if "BEGIN CERTIFICATE" not in text:
42
+ return None
43
+ path.parent.mkdir(parents=True, exist_ok=True)
44
+ tmp = path.with_name(path.name + f".{os.getpid()}")
45
+ tmp.write_text(text)
46
+ os.replace(tmp, path)
47
+ return str(path)
48
+ except (OSError, subprocess.TimeoutExpired):
49
+ return None
50
+
51
+
52
+ def ssl_context() -> ssl.SSLContext:
53
+ global _SSL
54
+ if _SSL is not None:
55
+ return _SSL
56
+ ctx = ssl.create_default_context()
57
+ ctx.verify_flags &= ~getattr(ssl, "VERIFY_X509_STRICT", 0)
58
+ extra = [os.environ.get(k) for k in ("SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "NODE_EXTRA_CA_CERTS")]
59
+ if sys.platform == "darwin":
60
+ extra.append(_macos_ca_bundle())
61
+ for f in extra:
62
+ if f and os.path.isfile(f):
63
+ try:
64
+ ctx.load_verify_locations(cafile=f)
65
+ except (ssl.SSLError, OSError):
66
+ pass
67
+ _SSL = ctx
68
+ return ctx
@@ -0,0 +1,150 @@
1
+ """claude-switch 엔진과 statusline 이 같이 쓰는 계정별 사용량 저장소 (python3 3.9 표준 라이브러리만).
2
+
3
+ 파일 하나 = 계정 하나: <state>/usage-cache/<slug(email)>
4
+ five|five_ep|seven|seven_ep|fetched|scoped
5
+ five/seven 사용률 % (usage API utilization = statusline stdin used_percentage, 같은 단위)
6
+ *_ep 리셋 epoch (0 = 모름)
7
+ fetched 이 값이 관측된 epoch. 엔진은 이것으로 5분 TTL 을 잰다
8
+ scoped label:group:pct:epoch,… (모델별 한도. usage API 만 준다)
9
+ 쓰는 쪽은 둘이다: 엔진(usage API 조회), statusline(세션이 받은 rate_limits 가 더 최신일 때).
10
+ 상태 폴더는 OS 와 상관없이 ~/.local/share/claude-switch 다 (CLAUDE_SWITCH_STATE_DIR 로 바꿀 수 있다).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import tempfile
16
+ import time
17
+ from pathlib import Path
18
+ from typing import NamedTuple, Optional
19
+
20
+
21
+ def state_dir() -> Path:
22
+ env = os.environ.get("CLAUDE_SWITCH_STATE_DIR")
23
+ return Path(env) if env else Path.home() / ".local" / "share" / "claude-switch"
24
+
25
+
26
+ def usage_dir() -> Path:
27
+ return state_dir() / "usage-cache"
28
+
29
+
30
+ def backup_dir() -> Path:
31
+ return state_dir() / "backups"
32
+
33
+
34
+ def dead_dir() -> Path:
35
+ return state_dir() / "dead"
36
+
37
+
38
+ def backoff_dir() -> Path:
39
+ return state_dir() / "backoff"
40
+
41
+
42
+ def switched_at_file() -> Path:
43
+ # 마지막 계정 전환 epoch. 전환 직후엔 실행 중인 claude 가 이전 계정 토큰으로 응답을 받을 수 있어
44
+ # statusline 이 그 값을 새 계정 것으로 쓰지 않게 막는 데 쓴다.
45
+ return state_dir() / "switched-at"
46
+
47
+
48
+ def slug(email: str) -> str:
49
+ return email.replace("/", "_").replace(" ", "_")
50
+
51
+
52
+ def write_atomic(path: Path, text: str, mode: Optional[int] = None) -> None:
53
+ """임시 파일에 쓰고 바꿔 끼운다. 여러 세션 · 엔진이 같이 써도 읽는 쪽이 반쯤 쓴 내용을 보지 않는다."""
54
+ path.parent.mkdir(parents=True, exist_ok=True)
55
+ fd, tmp = tempfile.mkstemp(prefix=path.name + ".", dir=str(path.parent))
56
+ try:
57
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as f:
58
+ f.write(text)
59
+ if mode is not None:
60
+ os.chmod(tmp, mode)
61
+ os.replace(tmp, path)
62
+ except BaseException:
63
+ try:
64
+ os.unlink(tmp)
65
+ except OSError:
66
+ pass
67
+ raise
68
+
69
+
70
+ def read_text(path: Path) -> str:
71
+ try:
72
+ return path.read_text(encoding="utf-8")
73
+ except (OSError, UnicodeDecodeError):
74
+ return ""
75
+
76
+
77
+ def to_int(v, default: int = 0) -> int:
78
+ try:
79
+ return int(float(v))
80
+ except (TypeError, ValueError):
81
+ return default
82
+
83
+
84
+ class Usage(NamedTuple):
85
+ five: str = "" # 사용률 문자열 그대로 ("29.0", "" = 모름, "-" · "?" = 조회 실패)
86
+ five_ep: int = 0
87
+ seven: str = ""
88
+ seven_ep: int = 0
89
+ fetched: int = 0
90
+ scoped: str = ""
91
+
92
+ def line(self) -> str:
93
+ return f"{self.five}|{self.five_ep}|{self.seven}|{self.seven_ep}|{self.fetched}|{self.scoped}\n"
94
+
95
+
96
+ def read(email: str) -> Usage:
97
+ raw = read_text(usage_dir() / slug(email)).strip()
98
+ if not raw:
99
+ return Usage()
100
+ p = (raw.split("|") + [""] * 6)[:6]
101
+ return Usage(p[0], to_int(p[1]), p[2], to_int(p[3]), to_int(p[4]), p[5])
102
+
103
+
104
+ def write(email: str, u: Usage) -> None:
105
+ try:
106
+ write_atomic(usage_dir() / slug(email), u.line())
107
+ except OSError:
108
+ pass
109
+
110
+
111
+ def delete(email: str) -> None:
112
+ for d in (usage_dir(), backoff_dir(), dead_dir()):
113
+ try:
114
+ (d / slug(email)).unlink()
115
+ except OSError:
116
+ pass
117
+
118
+
119
+ def switched_at() -> int:
120
+ return to_int(read_text(switched_at_file()).strip())
121
+
122
+
123
+ def mark_switched() -> None:
124
+ try:
125
+ write_atomic(switched_at_file(), f"{int(time.time())}\n")
126
+ except OSError:
127
+ pass
128
+
129
+
130
+ def accounts() -> list:
131
+ """등록된 계정 (oauthAccount 백업이 있는 이메일), 이름순."""
132
+ d = backup_dir()
133
+ try:
134
+ return sorted(p.name for p in d.iterdir() if (p / "oauth-account.json").is_file())
135
+ except OSError:
136
+ return []
137
+
138
+
139
+ def dead_reason(email: str) -> str:
140
+ # 첫 줄이 사유, 둘째 줄은 claude_switch.dead_mark 가 남긴 refresh token 지문 (rt:…)
141
+ return (read_text(dead_dir() / slug(email)).strip().splitlines() or [""])[0].strip()
142
+
143
+
144
+ def backoff_until(email: str) -> int:
145
+ parts = read_text(backoff_dir() / slug(email)).split()
146
+ return to_int(parts[0]) if parts else 0
147
+
148
+
149
+ def in_backoff(email: str) -> bool:
150
+ return backoff_until(email) > time.time()
@@ -0,0 +1,21 @@
1
+ """thuthi-accounts 점검 · 고치기 (thuthi:setup 의 doctor.py 가 부른다). 설치 코드는 tools/claude-switch/install.py 에 있다."""
2
+ from __future__ import annotations
3
+
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ sys.path.insert(0, str(Path(__file__).resolve().parent / "tools" / "claude-switch"))
8
+ import install as cs_install # noqa: E402 (claude-switch · statusline 설치 · 점검)
9
+
10
+
11
+ def check(d) -> list:
12
+ # claude-switch (계정 전환 · 사용량) + statusline: macOS · Linux · Windows
13
+ return [("claude-switch", mark, item, note) for mark, item, note in cs_install.status()]
14
+
15
+
16
+ def fix(what: str, d):
17
+ if what == "claude-switch":
18
+ return cs_install.install_shims()
19
+ if what == "statusline":
20
+ return cs_install.install_statusline()
21
+ return None
@@ -0,0 +1,48 @@
1
+ ---
2
+ name: claude-switch
3
+ description: >-
4
+ Claude Code 구독 계정 여러 개의 사용량(5h · 7d · 모델별 한도)을 보고, 다른 계정으로 바꾼다 (claude-switch 엔진, macOS · Linux · Windows).
5
+ 실행 중인 claude 세션도 다음 요청부터 새 계정으로 넘어간다 (macOS 는 최대 30초). "계정 사용량", "한도 얼마 남았어", "다른 계정으로 바꿔",
6
+ "ag12 로 전환", "claude-switch", "여유 있는 계정으로", "statusline 의 →계정 표시가 뭐야" 같은 요청에 진입한다.
7
+ 터미널 TUI(claude-switch tui) 띄우기와 계정 추가 안내도 여기서 한다.
8
+ ---
9
+
10
+ # thuthi-accounts:claude-switch: 계정 사용량 · 전환
11
+
12
+ 엔진은 `${CLAUDE_PLUGIN_ROOT}/tools/claude-switch/claude_switch.py` (python3 3.9 표준 라이브러리) 이고, 플러그인 `bin/` 덕에 이 세션 셸에서는 `claude-switch` 로 부른다 (Windows PowerShell 은 `claude-switch.cmd`). 모든 명령은 자격증명 저장소(macOS Keychain · `~/.claude/.credentials.json` · Windows 자격 증명 관리자)와 네트워크를 쓰므로 **`dangerouslyDisableSandbox: true`** 로 실행한다. 명령이 없거나 python 이 없다고 하면 `thuthi:setup` 으로 점검한다.
13
+
14
+ 자세한 동작 (선택 규칙 · hot-swap · 백오프 · 저장소 형식) 은 레포의 `docs/claude-switch.md` 에 있다.
15
+
16
+ ## 사용량 보기
17
+
18
+ ```bash
19
+ claude-switch --all --json # 캐시(5분) 를 쓴다. 대개 이것으로 충분하다
20
+ claude-switch --all --json --fresh # 사용자가 "지금 값" 을 원할 때만. 백오프 · 재로그인 필요 계정은 그래도 건너뛴다
21
+ ```
22
+
23
+ JSON 에서 읽을 것: `current` (지금 계정), `accounts[]` 의 `email` · `five_hour.utilization` / `resets_at` · `seven_day.*` · `scoped[]` (모델별 한도, 예: Fable 주간) · `status` (`OK` · `backoff Nm` · `재로그인 필요`) · `fetched_at`, `decision` (auto 가 고를 계정과 이유). 사용자에게는 계정마다 한 줄로 알린다: `ag11 (지금) 5h 29% ↻52m · 7d 49% ↻4d18h · Fable 0%`. 리셋까지 남은 시간은 `resets_at - 지금` 으로 센다. 이메일은 `@` 앞만 써도 된다.
24
+
25
+ ## 바꾸기
26
+
27
+ ```bash
28
+ claude-switch <email 또는 유일한 prefix> # 예: claude-switch buildcenter.ag12
29
+ ```
30
+
31
+ - 사용자가 계정을 정해 바꾸라고 했으면 바로 바꾼다. "여유 있는 계정으로" 면 `--all --json` 의 `decision.best` 를 쓰고, `decision.action` 이 `keep` 이면 이유(`reason`)를 알리고 바꾸지 않는다.
32
+ - 이 세션을 포함해 떠 있는 claude 는 다음 요청부터 새 계정으로 나간다 (macOS 는 Keychain 캐시 30초 뒤). 재시작할 필요가 없다.
33
+ - `재로그인 필요` 계정으로는 바꾸지 않는다. 그 계정은 사용자가 다시 로그인해야 한다 (아래 계정 추가와 같다).
34
+
35
+ ## TUI · auto (터미널)
36
+
37
+ TUI 는 대화형이라 이 세션 Bash 에서 띄우지 않는다. 사용자가 원하면:
38
+
39
+ - Orca 안이면 `orca terminal create --title "claude-switch" --command "claude-switch tui" --json` 로 새 탭에 띄운다 (샌드박스 밖).
40
+ - 아니면 터미널에서 `claude-switch tui` 를 치라고 알린다. TUI 는 30초마다 엔진을 조회하고 auto(기본 OFF, `a` 로 켬)를 켜면 잔여 용량이 가장 많은 계정으로 바꾼다. 키: `enter`/`s` 전환 · `a` auto 토글 · `r` 즉시 조회 · `q` 종료.
41
+
42
+ ## 계정 추가
43
+
44
+ `claude-switch --add [email]` 은 시크릿 브라우저 창에서 `claude auth login` 을 돌리는 대화형 명령이다. 사용자에게 `! claude-switch --add` 로 직접 실행하라고 알린다. claude 안에서 `/login` 으로 새 계정에 로그인해도 다음 claude-switch 실행 때 자동 등록된다.
45
+
46
+ ## statusline 과의 관계
47
+
48
+ statusline (`tools/statusline/statusline.py`) 은 엔진과 같은 `~/.local/share/claude-switch/usage-cache/` 를 읽고, 세션이 받은 최신 사용량을 거기 되쓴다. 현재 계정이 5h · 7d 중 하나라도 80% 이상이면 계정 이름 옆에 `→ag12 5h 3% 7d 10%` 처럼 가장 여유 있는 다른 계정이 붙는다. 사용자가 그 표시를 물으면 이 뜻을 알려 주고, 바꿀지 묻는다.