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,212 @@
1
+ #!/usr/bin/env python3
2
+ """Claude Code status line (macOS · Linux · Windows, python3 3.9 표준 라이브러리만)
3
+ 5h 사용량 ↻남은시간 │ 7d 사용량 ↻남은시간 │ [scoped 한도 …] │ ctx 사용량 │ 모델(effort) │ 계정 [→후보 계정] │ 사용량 갱신시각
4
+
5
+ thuthi-accounts 플러그인의 tools/statusline/ 에 있다. settings.json 의 statusLine 은 thuthi:setup 이 만든 shim 을 가리키고,
6
+ shim 이 지금 판의 이 파일을 실행한다.
7
+
8
+ 사용량 출처 두 곳을 합친다:
9
+ stdin — Claude Code 가 마지막 API 응답에서 받은 rate_limits. 프롬프트를 안 보내면 갱신되지 않고,
10
+ hot-swap 직후엔 이전 계정 값이 남아 있다.
11
+ cache — claude-switch 와 같이 쓰는 usage-cache/<email> (lib/usage_store.py). 유휴 중에도 흐르고
12
+ 계정별 파일이라 현재 계정 값이 보장된다. scoped 한도(Fable 주간 등)도 여기서만 나온다.
13
+ 규칙: stdin 값은 "처음 관측된 시점의 계정 == 현재 계정"일 때만 후보로 삼고,
14
+ 후보 중 더 최근 것(stdin 관측 시각 vs cache 조회 시각)을 쓴다. 후보가 하나뿐이면 그것을 쓴다.
15
+ 되쓰기: 그 stdin 값이 캐시보다 최신이면 캐시에 써서 claude-switch(TUI · auto)도 API 조회 없이 같은 값을 본다.
16
+ 계정 전환 직후 60초 안에 처음 본 값은 이전 계정 토큰의 응답일 수 있어 쓰지 않는다.
17
+ 후보 계정: 현재 계정의 5h · 7d 중 하나라도 80% 이상이면 캐시에서 가장 여유 있는 다른 계정을 붙인다
18
+ (점수 = 5h 잔여 × 7d 잔여, claude-switch auto 와 같은 식). 캐시만 읽어 API 호출은 늘지 않는다.
19
+ 재로그인 필요 · 조회 실패 중 · 6시간 넘게 안 갱신된 계정은 뺀다.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import os
25
+ import sys
26
+ import time
27
+ from datetime import datetime
28
+ from pathlib import Path
29
+
30
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "lib"))
31
+ import usage_store as us # noqa: E402
32
+
33
+ R, B = "\033[0m", "\033[1m"
34
+
35
+
36
+ def c(n: int) -> str:
37
+ return f"\033[38;5;{n}m"
38
+
39
+
40
+ OK, WARN, BAD, NA = c(39), c(220), c(196), c(240) # 사용량 임계색: 파랑/노랑/빨강, 값없음 회색
41
+ SEPC, MODEL, EFF, ACCT, CAND, TIME = c(99), c(213), c(177), c(120), c(87), c(245)
42
+ SEP = f"{SEPC} │ {R}"
43
+
44
+
45
+ def num(v):
46
+ try:
47
+ return float(v)
48
+ except (TypeError, ValueError):
49
+ return None
50
+
51
+
52
+ def claude_json() -> dict:
53
+ env = os.environ.get("CLAUDE_CONFIG_DIR")
54
+ p = Path(env) / ".claude.json" if env else Path.home() / ".claude.json"
55
+ try:
56
+ return json.loads(p.read_text(encoding="utf-8"))
57
+ except (OSError, ValueError):
58
+ return {}
59
+
60
+
61
+ def left(ep: int, now: int) -> str:
62
+ """epoch → 남은 시간 " ↻3d4h" / " ↻2h13m" / " ↻45m" """
63
+ if ep <= 0:
64
+ return ""
65
+ s = max(ep - now, 0)
66
+ d, h, m = s // 86400, s % 86400 // 3600, s % 3600 // 60
67
+ if d:
68
+ return f" ↻{d}d{h}h"
69
+ if h:
70
+ return f" ↻{h}h{m}m"
71
+ return f" ↻{m}m"
72
+
73
+
74
+ def kfmt(n: int) -> str:
75
+ return f"{(n + 500000) // 1000000}M" if n >= 1000000 else f"{(n + 500) // 1000}K"
76
+
77
+
78
+ def seg(label: str, val, reset: int = 0, tok: int = 0, mx=None, now: int = 0) -> str:
79
+ """라벨 · 값 · 남은시간 전부 사용량 임계색 한 가지로. 토큰수가 있으면 "ctx 75K / 200K(38%)", 없으면 "5h 24% ↻2h13m" """
80
+ if val is None:
81
+ return f"{NA}{label} –{R}"
82
+ p = int(round(val))
83
+ col = BAD if p >= 80 else WARN if p >= 50 else OK
84
+ if tok > 0:
85
+ total = f" / {kfmt(int(mx))}" if mx else ""
86
+ return f"{col}{label} {B}{kfmt(tok)}{R}{col}{total}({p}%){R}"
87
+ return f"{col}{label} {B}{p}%{R}{col}{left(reset, now)}{R}"
88
+
89
+
90
+ def main() -> int:
91
+ try:
92
+ sys.stdout.reconfigure(encoding="utf-8")
93
+ inp = json.loads(sys.stdin.read() or "{}")
94
+ except (ValueError, AttributeError):
95
+ inp = {}
96
+ now = int(time.time())
97
+ sid = str(inp.get("session_id") or "default")
98
+ model = (inp.get("model") or {}).get("display_name") or "?"
99
+ effort = (inp.get("effort") or {}).get("level") or ""
100
+ cw = inp.get("context_window") or {}
101
+ ctx = num(cw.get("used_percentage"))
102
+ ctx_max = cw.get("context_window_size")
103
+ cu = cw.get("current_usage") or {}
104
+ ctx_tok = sum(int(cu.get(k) or 0) for k in ("input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens"))
105
+ rl = inp.get("rate_limits") or {}
106
+ h5, h5r = num((rl.get("five_hour") or {}).get("used_percentage")), us.to_int((rl.get("five_hour") or {}).get("resets_at"))
107
+ d7, d7r = num((rl.get("seven_day") or {}).get("used_percentage")), us.to_int((rl.get("seven_day") or {}).get("resets_at"))
108
+
109
+ email = str((claude_json().get("oauthAccount") or {}).get("emailAddress") or "")
110
+ acct = email.split("@")[0]
111
+
112
+ # --- stdin rate_limits 의 관측 시각 · 소유 계정 (세션별 상태 파일) ---
113
+ # 값이 바뀐 시점(= 새 API 응답)을 기록해 두면 캐시와 신선도를 비교할 수 있고,
114
+ # 그때의 계정을 함께 적어 두면 hot-swap 뒤 남은 이전 계정 값을 걸러낼 수 있다.
115
+ stdin_seen, stdin_owner = 0, ""
116
+ if h5 is not None or d7 is not None:
117
+ sdir = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache") / "claude-statusline"
118
+ sfile = sdir / sid
119
+ sig = f"{rl.get('five_hour', {}).get('used_percentage')}|{h5r}|{rl.get('seven_day', {}).get('used_percentage')}|{d7r}"
120
+ prev = us.read_text(sfile).rstrip("\n").split("\t")
121
+ if len(prev) == 3 and prev[0] == sig and prev[1]:
122
+ stdin_seen, stdin_owner = us.to_int(prev[1]), prev[2]
123
+ else:
124
+ stdin_seen, stdin_owner = now, email
125
+ try:
126
+ us.write_atomic(sfile, f"{sig}\t{now}\t{email}\n")
127
+ for f in sdir.iterdir(): # 끝난 세션의 상태 파일 정리 (값이 바뀔 때만 실행)
128
+ if now - f.stat().st_mtime > 7 * 86400:
129
+ f.unlink()
130
+ except OSError:
131
+ pass
132
+ if stdin_owner != email:
133
+ h5 = d7 = None
134
+ h5r = d7r = stdin_seen = 0
135
+
136
+ # --- 공용 캐시 ---
137
+ c5 = c7 = None
138
+ c5r = c7r = cfetched = 0
139
+ cscoped = ""
140
+ if email:
141
+ u = us.read(email)
142
+ cfetched, cscoped = u.fetched, u.scoped
143
+ # stdin 값이 캐시보다 최신이면 되쓴다 (scoped 는 stdin 에 없으니 캐시 것을 그대로 둔다)
144
+ if h5 is not None and d7 is not None and stdin_seen > cfetched and stdin_seen >= us.switched_at() + 60:
145
+ us.write(email, us.Usage(f"{h5:g}", h5r, f"{d7:g}", d7r, stdin_seen, cscoped))
146
+ c5, c5r, c7, c7r = num(u.five), u.five_ep, num(u.seven), u.seven_ep
147
+ if 0 < c5r <= now: # 리셋 시각이 지난 캐시 값은 버린다 (엔진이 다음 조회에서 새로 채움)
148
+ c5 = None
149
+ if 0 < c7r <= now:
150
+ c7 = None
151
+
152
+ def pick(sv, sr, cv, cr):
153
+ """창별로 더 최근 출처 → (값, 리셋, 그 출처의 시각)"""
154
+ if sv is not None and (cv is None or stdin_seen >= cfetched):
155
+ return sv, sr, stdin_seen
156
+ if cv is not None:
157
+ return cv, cr, cfetched
158
+ return None, 0, 0
159
+
160
+ h5, h5r, t5 = pick(h5, h5r, c5, c5r)
161
+ d7, d7r, t7 = pick(d7, d7r, c7, c7r)
162
+ updated = max(t5, t7)
163
+
164
+ # scoped 한도(label:group:pct:epoch,…) → 각각 seg 로. weekly 외 그룹은 "라벨/그룹"
165
+ scoped_segs = ""
166
+ for item in filter(None, cscoped.split(",")):
167
+ f = (item.split(":") + ["", "", "", ""])[:4]
168
+ sp = num(f[2])
169
+ se = us.to_int(f[3])
170
+ if sp is None or 0 < se <= now:
171
+ continue
172
+ label = f[0] if not f[1] or f[1] == "weekly" else f"{f[0]}/{f[1]}"
173
+ scoped_segs += seg(label, sp, se, now=now) + SEP
174
+
175
+ # 현재 계정이 한도에 가까우면 가장 여유 있는 다른 계정 (캐시만 읽는다)
176
+ cand = ""
177
+ p5, p7 = int(round(h5)) if h5 is not None else 0, int(round(d7)) if d7 is not None else 0
178
+ if email and (p5 >= 80 or p7 >= 80):
179
+ best, best_score, b5, b7 = "", (100 - p5) * (100 - p7), 0, 0
180
+ for a in us.accounts():
181
+ if a == email or us.dead_reason(a) or us.in_backoff(a):
182
+ continue
183
+ o = us.read(a)
184
+ o5, o7 = num(o.five), num(o.seven)
185
+ # 6시간 넘게 안 갱신된 계정은 뺀다 (TUI · auto 가 돌면 살아 있는 계정은 5분마다 갱신된다)
186
+ if o5 is None or o7 is None or now - o.fetched > 21600:
187
+ continue
188
+ o5 = 0 if 0 < o.five_ep <= now else int(round(o5)) # 리셋이 지났으면 0
189
+ o7 = 0 if 0 < o.seven_ep <= now else int(round(o7))
190
+ s = (100 - o5) * (100 - o7)
191
+ if s > best_score:
192
+ best, best_score, b5, b7 = a, s, o5, o7
193
+ if best:
194
+ cand = f" {CAND}→{best.split('@')[0]} 5h {b5}% 7d {b7}%{R}"
195
+
196
+ model_seg = f"{MODEL}{B}{model}{R}" + (f"{EFF}({effort}){R}" if effort else "")
197
+ # 사용량 마지막 갱신 시각 "13:42" + 1분 이상 지났으면 "(3m 전)"
198
+ time_seg = f"{TIME}–{R}"
199
+ if updated > 0:
200
+ ago_m = (now - updated) // 60
201
+ ago = f" ({ago_m // 60}h 전)" if ago_m >= 60 else f" ({ago_m}m 전)" if ago_m >= 1 else ""
202
+ time_seg = f"{TIME}{datetime.fromtimestamp(updated).strftime('%H:%M')}{ago}{R}"
203
+
204
+ sys.stdout.write(
205
+ seg("5h", h5, h5r, now=now) + SEP + seg("7d", d7, d7r, now=now) + SEP + scoped_segs
206
+ + seg("ctx", ctx, 0, ctx_tok, ctx_max, now) + SEP + model_seg + SEP
207
+ + f"{ACCT}{acct}{R}{cand}" + SEP + time_seg + "\n")
208
+ return 0
209
+
210
+
211
+ if __name__ == "__main__":
212
+ sys.exit(main())
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "thuthi-agenda-picker",
3
+ "version": "0.12.4",
4
+ "description": "agenda-picker 스킬: 고를 안건을 바닥 페이지 + 반반 보기(지금 · 안) HTML 로 띄우고 고른 결과를 세션으로 돌려받는다. 선택지는 이것으로 띄우라는 상시 지시 포함",
5
+ "author": {
6
+ "name": "thuthi"
7
+ },
8
+ "dependencies": ["thuthi", "thuthi-browser"]
9
+ }
@@ -0,0 +1,3 @@
1
+ # thuthi-agenda-picker 상시 지시
2
+
3
+ - 사용자에게 고를 선택지(2개 이상)를 내놓을 때는 AskUserQuestion 대신 `thuthi-agenda-picker:agenda-picker` 스킬로 띄운다. 사용자가 부르지 않아도, 대화가 압축된 뒤에도, 앞서 이미 썼어도 그렇게 한다. AskUserQuestion 은 예/아니오 확인 · 안이 하나뿐인 확인에만 쓴다.
@@ -0,0 +1,15 @@
1
+ {
2
+ "hooks": {
3
+ "SessionStart": [
4
+ {
5
+ "hooks": [
6
+ {
7
+ "type": "command",
8
+ "command": "cat \"${CLAUDE_PLUGIN_ROOT}/context.md\"",
9
+ "timeout": 5
10
+ }
11
+ ]
12
+ }
13
+ ]
14
+ }
15
+ }
@@ -0,0 +1,397 @@
1
+ """thuthi 스킬 스크립트가 parallel-browser 로 브라우저를 다루게 하는 얇은 다리.
2
+
3
+ from pbpage import Browser
4
+ with Browser("agenda-selftest") as b: # 세션 하나 (탭 묶음). 끝나면 닫는다
5
+ pg = b.new_page(viewport=(1360, 900)) # 첫 탭을 쓰고, 다음부터는 새 탭
6
+ pg.goto("http://127.0.0.1:8000/")
7
+ pg.click("#send"); pg.screenshot("/tmp/a.png")
8
+
9
+ parallel-browser 는 사용자 Chrome · Edge 의 에이전트 전용 창에서 돌고 포커스를 가져가지 않는다. `parallel-browser nodejs`
10
+ 프로세스 하나를 띄워 두고 JSON 한 줄씩 명령을 보낸다 (세션 메서드 이름을 그대로 부른다: "goto", "mouse.move", "cdp" …).
11
+ 작업이 끝나면 세션을 닫는다 (사용자 요청: 각 작업 뒤 자기가 띄운 탭은 끈다).
12
+ 세션 주인은 이 파이썬 프로세스다 (PB_OWNER_PID). 예외로 죽어 close 를 못 불러도 데몬이 몇 초 안에 탭을 닫는다.
13
+ Page 는 Playwright 동기 API 의 일부와 같은 이름 · 모양이라 Playwright 로 쓰던 스크립트를 조금만 고쳐 옮길 수 있다.
14
+ python3 3.9 표준 라이브러리만 쓴다.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import os
20
+ import queue
21
+ import re
22
+ import shutil
23
+ import subprocess
24
+ import sys
25
+ import threading
26
+ import time
27
+ from pathlib import Path
28
+
29
+ MARK = "@@PB "
30
+
31
+ # parallel-browser nodejs 안에서 도는 쪽. 한 줄에 명령 하나를 받아 차례로 실행하고 결과를 MARK 를 붙여 돌려준다.
32
+ SERVER_JS = r"""
33
+ const cfg = JSON.parse(process.env.PBPAGE_CFG || '{}');
34
+ const s = await session(cfg.label || 'thuthi', cfg.options || {});
35
+ const send = (o) => process.stdout.write('@@PB ' + JSON.stringify(o) + '\n');
36
+ s.onDialog(async (d) => ({ accept: cfg.acceptDialogs !== false }));
37
+ send({ id: 0, ok: true, result: { handle: s.handle, tabId: s.tabId } });
38
+ let chain = Promise.resolve(), closing = false;
39
+ const run = async (m) => {
40
+ try {
41
+ if (m.path === '__close') { closing = true; await s.close(); return send({ id: m.id, ok: true, result: null }); }
42
+ const parts = m.path.split('.');
43
+ let obj = s;
44
+ for (const p of parts.slice(0, -1)) obj = obj[p];
45
+ const fn = obj[parts[parts.length - 1]];
46
+ if (typeof fn !== 'function') throw new Error('no such method: ' + m.path);
47
+ const r = await fn.apply(obj, m.args || []);
48
+ send({ id: m.id, ok: true, result: r === undefined ? null : r });
49
+ } catch (e) {
50
+ send({ id: m.id, ok: false, error: String((e && e.stack) || e) });
51
+ }
52
+ };
53
+ await new Promise((resolve) => {
54
+ let buf = '';
55
+ process.stdin.setEncoding('utf8');
56
+ process.stdin.on('data', (chunk) => {
57
+ buf += chunk;
58
+ let i;
59
+ while ((i = buf.indexOf('\n')) >= 0) {
60
+ const line = buf.slice(0, i); buf = buf.slice(i + 1);
61
+ if (line.trim()) { const m = JSON.parse(line); chain = chain.then(() => run(m)); }
62
+ }
63
+ });
64
+ process.stdin.on('end', resolve);
65
+ });
66
+ await chain;
67
+ if (!closing) { try { await s.close(); } catch (e) {} }
68
+ """
69
+
70
+ # 페이지 JS 오류를 모아 두는 스크립트 (Playwright 의 pageerror 대신). 새 문서마다 먼저 돈다.
71
+ ERRORS_JS = """(() => { if (window.__pbErrors) return; window.__pbErrors = [];
72
+ addEventListener('error', e => window.__pbErrors.push(String(e.message || e)));
73
+ addEventListener('unhandledrejection', e => window.__pbErrors.push('unhandled: ' + String(e.reason))); })();"""
74
+
75
+ FN_RE = re.compile(r"^\s*(async\s+)?(function\b|\([^()]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)")
76
+
77
+
78
+ class PBError(RuntimeError):
79
+ pass
80
+
81
+
82
+ def _pb_js():
83
+ """parallel-browser CLI 의 js (bin/parallel-browser.js). npm link 가 건 곳 → 마켓플레이스 레포 → 이 레포 순."""
84
+ cands = []
85
+ cmd = shutil.which("parallel-browser")
86
+ if cmd:
87
+ cands.append(Path(cmd).parent / "node_modules" / "parallel-browser" / "bin" / "parallel-browser.js")
88
+ try:
89
+ km = Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude") / "plugins" / "known_marketplaces.json"
90
+ loc = (json.loads(km.read_text(encoding="utf-8")).get("thuthi-plugin") or {}).get("installLocation")
91
+ if loc:
92
+ cands.append(Path(loc) / "bin" / "parallel-browser.js")
93
+ except (OSError, ValueError):
94
+ pass
95
+ cands.append(Path(__file__).resolve().parents[3] / "bin" / "parallel-browser.js")
96
+ return next((str(c) for c in cands if c.is_file()), None)
97
+
98
+
99
+ def pb_argv() -> list:
100
+ """parallel-browser 를 부르는 명령 앞부분. Windows 는 npm 이 만든 parallel-browser.cmd 라 이름만으로는 실행되지 않고
101
+ (WinError 2), .cmd 를 거치면 여러 줄 -e 인자가 깨진다 (Windows 실측). 그래서 node 로 js 를 직접 부른다."""
102
+ if sys.platform == "win32":
103
+ node, js = shutil.which("node"), _pb_js()
104
+ if node and js:
105
+ return [node, js]
106
+ return [shutil.which("parallel-browser") or "parallel-browser"]
107
+ return ["parallel-browser"]
108
+
109
+
110
+ def utf8_stdio() -> None:
111
+ """Windows 콘솔(cp949)에서 ✓ · 한글을 찍다 UnicodeEncodeError 로 죽지 않게 stdout · stderr 를 UTF-8 로."""
112
+ for f in (sys.stdout, sys.stderr):
113
+ try:
114
+ f.reconfigure(encoding="utf-8", errors="replace")
115
+ except (AttributeError, ValueError):
116
+ pass
117
+
118
+
119
+ class Browser:
120
+ """parallel-browser 세션 하나. 탭(Page) 여러 개를 가질 수 있다."""
121
+
122
+ def __init__(self, label: str = "thuthi", *, accept_dialogs: bool = True,
123
+ budget: int = 4, timeout: float = 60):
124
+ cfg = {"label": label, "acceptDialogs": accept_dialogs, "options": {"budget": budget}}
125
+ # 세션 주인 = 이 파이썬. 이게 끝나면 데몬이 세션을 닫는다
126
+ env = dict(os.environ, PBPAGE_CFG=json.dumps(cfg), PB_OWNER_PID=str(os.getpid()))
127
+ self.proc = subprocess.Popen([*pb_argv(), "nodejs", "-e", SERVER_JS], stdin=subprocess.PIPE,
128
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8",
129
+ errors="replace", bufsize=1, env=env)
130
+ self._q: dict[int, queue.Queue] = {}
131
+ self._lock = threading.Lock()
132
+ self._next = 1
133
+ self._stderr: list[str] = []
134
+ self._ready: queue.Queue = queue.Queue()
135
+ self._q[0] = self._ready
136
+ threading.Thread(target=self._read, daemon=True).start()
137
+ threading.Thread(target=lambda: self._stderr.extend(self.proc.stderr), daemon=True).start()
138
+ try:
139
+ hello = self._ready.get(timeout=timeout)
140
+ except queue.Empty:
141
+ self.proc.kill()
142
+ raise PBError("parallel-browser 세션을 열지 못했다: " + "".join(self._stderr)[-500:])
143
+ if not hello.get("ok"):
144
+ raise PBError(hello.get("error", "세션 열기 실패"))
145
+ self.handle = hello["result"]["handle"]
146
+ self._first_tab = hello["result"]["tabId"]
147
+ self._cur_tab = self._first_tab
148
+ self.pages: list[Page] = []
149
+ self.closed = False
150
+
151
+ # -- 통신
152
+ def _read(self):
153
+ for line in self.proc.stdout:
154
+ if not line.startswith(MARK):
155
+ continue
156
+ msg = json.loads(line[len(MARK):])
157
+ q = self._q.get(msg.get("id"))
158
+ if q:
159
+ q.put(msg)
160
+ for q in list(self._q.values()): # 프로세스가 끝났다
161
+ q.put({"ok": False, "error": "parallel-browser 프로세스가 끝났다: " + "".join(self._stderr)[-500:]})
162
+
163
+ def call(self, path: str, *args, timeout: float = 60):
164
+ if self.closed:
165
+ raise PBError("세션이 닫혔다")
166
+ with self._lock:
167
+ mid = self._next
168
+ self._next += 1
169
+ q = self._q[mid] = queue.Queue()
170
+ self.proc.stdin.write(json.dumps({"id": mid, "path": path, "args": list(args)}) + "\n")
171
+ self.proc.stdin.flush()
172
+ try:
173
+ msg = q.get(timeout=timeout)
174
+ except queue.Empty:
175
+ raise PBError(f"{path}: {timeout}초 안에 답이 없다")
176
+ finally:
177
+ self._q.pop(mid, None)
178
+ if not msg.get("ok"):
179
+ raise PBError(f"{path}: {msg.get('error')}")
180
+ return msg.get("result")
181
+
182
+ def _use(self, tab):
183
+ if tab != self._cur_tab:
184
+ self.call("use", tab)
185
+ self._cur_tab = tab
186
+
187
+ # -- 탭
188
+ def new_page(self, url: str = "", *, viewport=None, dpr: float = 1, color_scheme: str | None = "light",
189
+ collect_errors: bool = True) -> "Page":
190
+ if not self.pages:
191
+ tab = self._first_tab
192
+ else:
193
+ tab = self.call("newTab", "about:blank")
194
+ tab = tab.get("tabId", tab) if isinstance(tab, dict) else tab
195
+ pg = Page(self, tab)
196
+ self.pages.append(pg)
197
+ if viewport:
198
+ pg.set_viewport(viewport[0], viewport[1], dpr)
199
+ if color_scheme:
200
+ pg.cdp("Emulation.setEmulatedMedia", {"features": [{"name": "prefers-color-scheme", "value": color_scheme}]})
201
+ if collect_errors:
202
+ pg.cdp("Page.addScriptToEvaluateOnNewDocument", {"source": ERRORS_JS})
203
+ if url:
204
+ pg.goto(url)
205
+ return pg
206
+
207
+ def close(self):
208
+ if self.closed:
209
+ return
210
+ try:
211
+ self.call("__close", timeout=20)
212
+ except PBError:
213
+ pass
214
+ self.closed = True
215
+ try:
216
+ self.proc.stdin.close()
217
+ self.proc.wait(timeout=20)
218
+ except (OSError, subprocess.TimeoutExpired):
219
+ self.proc.kill()
220
+
221
+ def __enter__(self):
222
+ return self
223
+
224
+ def __exit__(self, *exc):
225
+ self.close()
226
+
227
+
228
+ class _Mouse:
229
+ def __init__(self, pg: "Page"):
230
+ self.pg = pg
231
+ self._down = False
232
+
233
+ def move(self, x, y, steps: int = 1):
234
+ self.pg._call("mouse.move", x, y, {"steps": steps, "button": "left" if self._down else "none"})
235
+
236
+ def down(self):
237
+ self._down = True
238
+ self.pg._call("mouse.down")
239
+
240
+ def up(self):
241
+ self._down = False
242
+ self.pg._call("mouse.up")
243
+
244
+ def click(self, x, y):
245
+ self.pg._call("mouse.click", x, y)
246
+
247
+ def wheel(self, dx, dy):
248
+ self.pg._call("mouse.wheel", dx, dy)
249
+
250
+
251
+ class _Keyboard:
252
+ def __init__(self, pg: "Page"):
253
+ self.pg = pg
254
+
255
+ def press(self, key: str):
256
+ self.pg._call("press", key)
257
+
258
+ def type(self, text: str, delay: float = 0):
259
+ self.pg._call("type", text, {"delay": delay})
260
+
261
+
262
+ class Locator:
263
+ """CSS 선택자 하나. count · first · click · inner_text 만 쓴다."""
264
+
265
+ def __init__(self, pg: "Page", sel: str, nth: int | None = None):
266
+ self.pg, self.sel, self.nth = pg, sel, nth
267
+
268
+ def count(self) -> int:
269
+ return self.pg.evaluate(f"document.querySelectorAll({json.dumps(self.sel)}).length")
270
+
271
+ @property
272
+ def first(self) -> "Locator":
273
+ return Locator(self.pg, self.sel, 0)
274
+
275
+ def _target(self) -> str:
276
+ return f"css={self.sel}" + (f" >> nth={self.nth}" if self.nth is not None else "")
277
+
278
+ def click(self):
279
+ self.pg._call("click", self._target())
280
+
281
+ def inner_text(self) -> str:
282
+ return self.pg._el(self.sel, "e.innerText", self.nth or 0)
283
+
284
+ def is_visible(self) -> bool:
285
+ return self.pg._visible(self.sel)
286
+
287
+ def focus(self):
288
+ self.pg._el(self.sel, "(e.focus(), null)", self.nth or 0)
289
+
290
+ def scroll_into_view_if_needed(self):
291
+ self.pg._el(self.sel, "(e.scrollIntoView({block: 'center'}), null)", self.nth or 0)
292
+
293
+
294
+ class Page:
295
+ """탭 하나. Playwright Page 와 같은 이름의 메서드 일부."""
296
+
297
+ def __init__(self, browser: Browser, tab):
298
+ self.b, self.tab = browser, tab
299
+ self.mouse = _Mouse(self)
300
+ self.keyboard = _Keyboard(self)
301
+ self.viewport_size = None
302
+
303
+ def _call(self, path, *args, timeout: float = 60):
304
+ self.b._use(self.tab)
305
+ return self.b.call(path, *args, timeout=timeout)
306
+
307
+ def cdp(self, method: str, params: dict | None = None):
308
+ return self._call("cdp", method, params or {})
309
+
310
+ def set_viewport(self, width: int, height: int, dpr: float = 1):
311
+ self.cdp("Emulation.setDeviceMetricsOverride", {"width": width, "height": height, "deviceScaleFactor": dpr, "mobile": False})
312
+ self.viewport_size = {"width": width, "height": height}
313
+
314
+ # -- 이동
315
+ def goto(self, url: str, wait_until: str = "load", timeout: float = 30):
316
+ # # 뒤만 바뀌면 문서를 다시 읽지 않아 load 가 오지 않는다. Playwright 처럼 같은 문서 안 이동으로 처리한다.
317
+ cur = self.url() or ""
318
+ if "#" in url and cur.split("#")[0] == url.split("#")[0]:
319
+ self.evaluate(f"location.href = {json.dumps(url)}")
320
+ return
321
+ self._call("goto", url, {"waitUntil": wait_until, "timeout": int(timeout * 1000)}, timeout=timeout + 10)
322
+
323
+ def reload(self):
324
+ self._call("reload")
325
+
326
+ def url(self) -> str:
327
+ return self._call("url")
328
+
329
+ def close(self):
330
+ self._call("closeTab", self.tab)
331
+ self.b.pages.remove(self)
332
+ self.b._cur_tab = None
333
+
334
+ # -- 읽기
335
+ def evaluate(self, expr: str, arg=None):
336
+ if FN_RE.match(expr):
337
+ expr = f"({expr})({json.dumps(arg)})"
338
+ return self._call("evaluate", expr)
339
+
340
+ def _el(self, sel: str, body: str, nth: int = 0, timeout: float = 5):
341
+ """선택자가 나올 때까지 기다렸다가 e 로 body 를 계산한다 (Playwright 의 자동 대기 대신)."""
342
+ js = f"""(async () => {{ const end = Date.now() + {int(timeout * 1000)};
343
+ for (;;) {{ const e = document.querySelectorAll({json.dumps(sel)})[{nth}];
344
+ if (e) return {body};
345
+ if (Date.now() > end) throw new Error('없다: ' + {json.dumps(sel)});
346
+ await new Promise(r => setTimeout(r, 50)); }} }})()"""
347
+ return self._call("evaluate", js)
348
+
349
+ def inner_text(self, sel: str) -> str:
350
+ return self._el(sel, "e.innerText")
351
+
352
+ def get_attribute(self, sel: str, name: str):
353
+ return self._el(sel, f"e.getAttribute({json.dumps(name)})")
354
+
355
+ def _visible(self, sel: str) -> bool:
356
+ return self.evaluate(f"""(e => !!e && e.checkVisibility() && e.getClientRects().length > 0)
357
+ (document.querySelector({json.dumps(sel)}))""")
358
+
359
+ def is_visible(self, sel: str) -> bool:
360
+ return self._visible(sel)
361
+
362
+ def locator(self, sel: str) -> Locator:
363
+ return Locator(self, sel)
364
+
365
+ def errors(self) -> list:
366
+ return self.evaluate("window.__pbErrors || []") or []
367
+
368
+ # -- 조작
369
+ def click(self, sel: str):
370
+ self._call("click", f"css={sel}")
371
+
372
+ def fill(self, sel: str, text: str):
373
+ self._call("fill", f"css={sel}", text)
374
+
375
+ def hide_overlay(self, hide: bool = True):
376
+ """parallel-browser 가 페이지에 띄우는 상태 표시 (파란 테두리 · 라벨 · [내가 하기]) 를 숨기거나 되살린다.
377
+
378
+ 스크린샷 · 녹화에 찍히지 않게 하려는 것이다. 사용자가 그 탭을 넘겨받는 버튼도 같이 숨으므로 찍는 동안만 숨긴다.
379
+ """
380
+ self.evaluate(f"""(() => {{ let st = document.getElementById('__pbpage_hide__');
381
+ if ({'true' if hide else 'false'}) {{ if (!st) {{ st = document.createElement('style'); st.id = '__pbpage_hide__';
382
+ st.textContent = '#__parallel_browser_overlay__, [data-parallel-browser] {{ display: none !important; }}';
383
+ document.documentElement.appendChild(st); }} }}
384
+ else if (st) st.remove(); }})()""")
385
+
386
+ def screenshot(self, path: str, full_page: bool = False, clean: bool = True):
387
+ """clean=True 면 상태 표시를 숨긴 채 찍고 되살린다."""
388
+ if clean:
389
+ self.hide_overlay(True)
390
+ try:
391
+ self._call("screenshot", str(path), {"fullPage": full_page}, timeout=40)
392
+ finally:
393
+ if clean:
394
+ self.hide_overlay(False)
395
+
396
+ def wait_for_timeout(self, ms: float):
397
+ time.sleep(ms / 1000)
@@ -0,0 +1,18 @@
1
+ """thuthi-agenda-picker 점검 (thuthi:setup 의 doctor.py 가 부른다). 스크린샷 · 검사는 thuthi-browser 줄이 본다."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import shutil
6
+ import sys
7
+
8
+ G = "agenda-picker"
9
+
10
+
11
+ def check(d) -> list:
12
+ py = sys.version_info[:2] >= (3, 9)
13
+ in_orca = bool(shutil.which("orca")) and os.environ.get("TERM_PROGRAM") == "Orca"
14
+ return [
15
+ (G, d.OK if py else d.BAD, "python3 (표준 라이브러리만)", ""),
16
+ (G, d.OK if in_orca else d.OPT, "Orca",
17
+ "Orca 안이면 보내기가 입력창으로 바로 들어온다" if in_orca else "Orca 밖이면 wait 로 받는다 (그대로 쓸 수 있다)"),
18
+ ]