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,115 @@
1
+ #!/usr/bin/env python3
2
+ """실제 브라우저로 팝업 상호작용을 실측한다: hover 확대 · 클릭으로 팝업 열림 · 배경 스크롤 잠금 · ESC 닫기 ·
3
+ 페이지 폭보다 넓어 제 폭으로 그려진 그림(svg 에 style 폭이 붙은 것)의 좌우 스크롤.
4
+
5
+ python3 interact_test.py out.html
6
+
7
+ 브라우저는 parallel-browser (사용자 Chrome · Edge 의 에이전트 창, 포커스를 가져가지 않는다) 로 몰고, 화면은 1700×1000 으로
8
+ 고정한다. 확장은 file:// 을 못 열 수 있어 파일이 든 폴더를 127.0.0.1 임시 서버로 연다. 끝나면 띄운 탭 · 세션을 닫는다.
9
+ exit 0 = 전부 통과, 1 = 실패 있음.
10
+ """
11
+ import functools
12
+ import json
13
+ import os
14
+ import sys
15
+ import threading
16
+ from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
17
+ from pathlib import Path
18
+ from urllib.parse import quote
19
+
20
+ sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "lib"))
21
+ from pbpage import Browser # noqa: E402
22
+
23
+
24
+ class Quiet(SimpleHTTPRequestHandler):
25
+ def log_message(self, *a):
26
+ pass
27
+
28
+
29
+ def serve(folder):
30
+ srv = ThreadingHTTPServer(("127.0.0.1", 0), functools.partial(Quiet, directory=str(folder)))
31
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
32
+ return srv
33
+
34
+
35
+ def main(path):
36
+ for _f in (sys.stdout, sys.stderr): # Windows 콘솔(cp949)에서 ✓ · 한글을 찍다 죽지 않게
37
+ try:
38
+ _f.reconfigure(encoding="utf-8", errors="replace")
39
+ except (AttributeError, ValueError):
40
+ pass
41
+ path = Path(path).resolve()
42
+ srv = serve(path.parent)
43
+ url = f"http://127.0.0.1:{srv.server_address[1]}/{quote(path.name)}"
44
+ fails, n, wide = [], 0, []
45
+ link = lambda i: f"document.querySelectorAll('a.node-link')[{i}]"
46
+ try:
47
+ with Browser("arch-diagram interact_test") as b:
48
+ pg = b.new_page(viewport=(1700, 1000))
49
+ pg.goto(url)
50
+ n = pg.locator("a.node-link").count()
51
+ if n == 0:
52
+ fails.append('a.node-link 가 없다 (팝업 링크 노드 없음)')
53
+ for i in range(n):
54
+ # 노드가 접힌 곳 아래에 있으면 hover 좌표가 화면 밖으로 나간다. hover 전에 반드시 화면 안으로 올린다.
55
+ href, box = pg.evaluate(f"""(e => {{ e.scrollIntoView({{block: 'center'}});
56
+ const r = e.getBoundingClientRect(); return [e.getAttribute('href'), [r.x, r.y, r.width, r.height]]; }})({link(i)})""")
57
+ pg.wait_for_timeout(100)
58
+ cx, cy = box[0] + box[2] / 2, box[1] + box[3] / 2
59
+ pg.mouse.move(cx, cy)
60
+ pg.wait_for_timeout(250)
61
+ hov, tf = pg.evaluate(f"(e => [e.matches(':hover'), getComputedStyle(e).transform])({link(i)})")
62
+ if not hov or tf == 'none':
63
+ fails.append(f'{href}: hover 확대 안 됨 (hover={hov}, transform={tf})')
64
+ pg.mouse.click(cx, cy)
65
+ pg.wait_for_timeout(250)
66
+ st = pg.evaluate("(() => { const m=document.querySelector('.modal:target'); return m ? [m.id, getComputedStyle(m).display, getComputedStyle(document.body).overflow] : null })()")
67
+ if not st or st[1] != 'block':
68
+ fails.append(f'{href}: 클릭해도 팝업이 안 열림 ({st})')
69
+ elif '#' + st[0] != href:
70
+ fails.append(f'{href}: 다른 팝업이 열림 ({st[0]})')
71
+ elif st[2] != 'hidden':
72
+ fails.append(f'{href}: 팝업 열림 중 배경 스크롤 잠금 안 됨 (overflow={st[2]})')
73
+ pg.keyboard.press('Escape')
74
+ pg.wait_for_timeout(250)
75
+ if pg.evaluate("!!document.querySelector('.modal:target')"):
76
+ fails.append(f'{href}: ESC 로 안 닫힘')
77
+ # 넓은 그림(svg() 가 style 폭을 붙인 것: 타일 스타일 1600 · 옛 스타일 1280 초과) 은 줄지 않고 제 폭으로 그려져 .diagram-container 가 좌우로 스크롤돼야 한다.
78
+ # 팝업 안 그림은 그 팝업을 연 상태에서만 크기가 잡히므로 hash 로 열고 잰다.
79
+ wide = pg.evaluate("""[...document.querySelectorAll('svg')].map((s, i) => {
80
+ const vb = (s.getAttribute('viewBox') || '').split(/\\s+/).map(Number);
81
+ const m = s.closest('.modal');
82
+ return {i, w: vb[2] || 0, modal: m ? m.id : '', fixed: /px/.test(s.style.width || '')};
83
+ }).filter(x => x.fixed)""")
84
+ for x in wide:
85
+ target = ('#' + x['modal']) if x['modal'] else '#overview'
86
+ pg.evaluate(f"location.hash = {json.dumps(target)}")
87
+ pg.wait_for_timeout(250)
88
+ r = pg.evaluate(f"""(() => {{
89
+ const s = document.querySelectorAll('svg')[{x['i']}], c = s.closest('.diagram-container');
90
+ if (!c) return {{err: 'diagram-container 없음'}};
91
+ const before = c.scrollLeft; c.scrollLeft = 100000; const after = c.scrollLeft; c.scrollLeft = before;
92
+ return {{client: c.clientWidth, scroll: c.scrollWidth, after, svgw: s.getBoundingClientRect().width}};
93
+ }})()""")
94
+ label = f"svg#{x['i']}" + (f" (#{x['modal']})" if x['modal'] else '')
95
+ if r.get('err'):
96
+ fails.append(f'{label}: {r["err"]}')
97
+ elif r['svgw'] < x['w'] - 1:
98
+ fails.append(f"{label}: 폭 {x['w']} 그림이 {r['svgw']:.0f}px 로 줄어 그려짐 (svg() 가 제 폭 style 을 붙였는지 확인)")
99
+ elif not (r['scroll'] > r['client'] and r['after'] > 0):
100
+ fails.append(f'{label}: 좌우 스크롤 안 됨 ({r})')
101
+ if wide:
102
+ pg.evaluate("location.hash = '#overview'")
103
+ errs = pg.errors()
104
+ if errs:
105
+ fails.append('JS 오류: ' + '; '.join(errs))
106
+ finally:
107
+ srv.shutdown()
108
+ for f in fails:
109
+ print('FAIL', f)
110
+ print(('FAIL' if fails else 'OK'), path, f'(링크 노드 {n}개, 넓은 그림 {len(wide)}장)')
111
+ return 1 if fails else 0
112
+
113
+
114
+ if __name__ == '__main__':
115
+ sys.exit(main(sys.argv[1]))
@@ -0,0 +1,113 @@
1
+ #!/usr/bin/env python3
2
+ """HTML 을 정해진 크기로 스크린샷 찍고 (선택) 세로로 나눠 눈으로 확인할 PNG 를 만든다.
3
+
4
+ python3 render.py out.html # /tmp/nd-full.png (1700 x 4000)
5
+ python3 render.py out.html --height 1200 # 위쪽만
6
+ python3 render.py out.html --fragment popup-b # 팝업 열린 상태
7
+ python3 render.py out.html --bands 3 # /tmp/nd-full-band0..2.png 로 3등분
8
+ python3 render.py out.html --svg 2 # 문서 순서 3번째 svg 한 장만 제 폭 그대로 (넓은 그림 전체 확인용)
9
+
10
+ 브라우저는 parallel-browser (사용자 Chrome · Edge 의 에이전트 창, 포커스를 가져가지 않는다) 로 몬다. 화면 크기를
11
+ --width × --height 로 고정하고 상태 표시를 숨긴 채 찍은 뒤 탭 · 세션을 닫는다. 확장은 file:// 을 막으므로 파일이 든
12
+ 폴더를 127.0.0.1 임시 서버로 연다. OS 마다 다른 브라우저 경로나 이미지 도구(sips 등)에 기대지 않는다.
13
+ 넓은 그림(페이지 폭 1600 · 옛 스타일 1280 보다 넓은 것)은 팝업 안에서 좌우로 스크롤되므로 --fragment 캡처에는 앞부분만 찍힌다. 전체는 --svg N 으로 본다.
14
+ """
15
+ import argparse
16
+ import base64
17
+ import functools
18
+ import os
19
+ import re
20
+ import sys
21
+ import tempfile
22
+ import threading
23
+ from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
24
+ from pathlib import Path
25
+ from urllib.parse import quote
26
+
27
+ sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "lib"))
28
+ from pbpage import Browser # noqa: E402
29
+
30
+
31
+ class Quiet(SimpleHTTPRequestHandler):
32
+ def log_message(self, *a):
33
+ pass
34
+
35
+
36
+ def serve(folder):
37
+ srv = ThreadingHTTPServer(("127.0.0.1", 0), functools.partial(Quiet, directory=str(folder)))
38
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
39
+ return srv
40
+
41
+
42
+ def capture(pg, out, clip=None):
43
+ """지금 화면(또는 clip 영역)을 PNG 로. 상태 표시는 찍는 동안만 숨긴다."""
44
+ pg.hide_overlay(True)
45
+ try:
46
+ params = {"format": "png"}
47
+ if clip:
48
+ params["clip"] = dict(clip, scale=1)
49
+ data = pg.cdp("Page.captureScreenshot", params)["data"]
50
+ finally:
51
+ pg.hide_overlay(False)
52
+ Path(out).write_bytes(base64.b64decode(data))
53
+
54
+
55
+ def main():
56
+ for _f in (sys.stdout, sys.stderr): # Windows 콘솔(cp949)에서 ✓ · 한글을 찍다 죽지 않게
57
+ try:
58
+ _f.reconfigure(encoding="utf-8", errors="replace")
59
+ except (AttributeError, ValueError):
60
+ pass
61
+ ap = argparse.ArgumentParser()
62
+ ap.add_argument('html')
63
+ ap.add_argument('--width', type=int, default=1700) # 타일 스타일 페이지 폭 1600 + 여백
64
+ ap.add_argument('--height', type=int, default=4000)
65
+ ap.add_argument('--fragment', default='')
66
+ ap.add_argument('--out', default='/tmp/nd-full.png')
67
+ ap.add_argument('--bands', type=int, default=0)
68
+ ap.add_argument('--svg', type=int, default=None, help='문서 순서 N 번째(0부터) svg 한 장만 제 폭으로 찍는다')
69
+ a = ap.parse_args()
70
+ src = Path(a.html).resolve()
71
+ tmp = None
72
+ if a.svg is not None:
73
+ # svg 한 장을 원래 페이지 스타일과 함께 떼어 내 viewBox 크기대로 찍는다 (width/height 인자는 무시).
74
+ html = src.read_text(encoding='utf-8')
75
+ svgs = re.findall(r'<svg viewBox="0 0 (\d+) (\d+)".*?</svg>', html, re.S)
76
+ blocks = re.findall(r'<svg viewBox="0 0 \d+ \d+".*?</svg>', html, re.S)
77
+ if a.svg >= len(blocks):
78
+ sys.exit(f'svg 는 {len(blocks)}장뿐 (0 ~ {len(blocks) - 1})')
79
+ w, h = (int(v) for v in svgs[a.svg])
80
+ head = html[:html.index('</head>')] if '</head>' in html else '<html><head><meta charset="UTF-8">'
81
+ tmp = Path(tempfile.mkdtemp(prefix='nd-svg-'))
82
+ src = tmp / f'svg{a.svg}.html'
83
+ src.write_text(head + '</head><body style="padding:20px;min-height:0">' + blocks[a.svg] + '</body></html>', encoding='utf-8')
84
+ a.width, a.height = w + 60, h + 60
85
+ srv = serve(src.parent)
86
+ url = f"http://127.0.0.1:{srv.server_address[1]}/{quote(src.name)}" + ('#' + a.fragment if a.fragment else '')
87
+ out = str(Path(a.out).expanduser())
88
+ try:
89
+ with Browser("arch-diagram render") as b:
90
+ pg = b.new_page(viewport=(a.width, a.height))
91
+ pg.goto(url)
92
+ pg.cdp("Emulation.setScrollbarsHidden", {"hidden": True})
93
+ pg.evaluate("document.fonts.ready.then(() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r))))")
94
+ capture(pg, out)
95
+ print(out)
96
+ if a.bands:
97
+ h = a.height // a.bands
98
+ for i in range(a.bands):
99
+ band = out.replace('.png', f'-band{i}.png')
100
+ capture(pg, band, {"x": 0, "y": i * h, "width": a.width, "height": h})
101
+ print(band)
102
+ finally:
103
+ srv.shutdown()
104
+ if tmp:
105
+ for f in tmp.iterdir():
106
+ f.unlink()
107
+ tmp.rmdir()
108
+ if not os.path.exists(out):
109
+ sys.exit('스크린샷 실패')
110
+
111
+
112
+ if __name__ == '__main__':
113
+ main()
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "thuthi-browser",
3
+ "version": "0.22.0",
4
+ "description": "parallel-browser 스킬: 사용자 Chrome · Edge 안의 에이전트 전용 창에서 웹을 다룬다 (스크린샷 · 조작 · 검사 · 녹화). 스킬 스크립트용 Python 다리 lib/pbpage.py 포함",
5
+ "author": {
6
+ "name": "thuthi"
7
+ },
8
+ "dependencies": ["thuthi"]
9
+ }
@@ -0,0 +1,3 @@
1
+ # thuthi-browser 상시 지시
2
+
3
+ - 브라우저가 필요한 작업(스크린샷 · 웹 조작 · 검사 · 녹화)은 `thuthi-browser:parallel-browser` 로 한다. Playwright 나 다른 브라우저 실행 파일을 직접 띄우지 않는다. 작업이 끝나면 자기가 띄운 탭 · 세션은 닫는다 (`s.close()`). 사용자에게 보여 주려고 남길 때는 닫지 않고 두면 된다 (이 세션이 살아 있는 동안 남고, 끝나면 몇 초 안에 저절로 닫힌다).
@@ -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)