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,106 @@
1
+ # Install and connect
2
+
3
+ Read this only when the `parallel-browser` command is missing, or a script fails because the
4
+ browser is not connected. For normal work go back to `SKILL.md`.
5
+
6
+ parallel-browser has two halves: a **browser extension** the user installs once, and a **Node
7
+ runtime** that talks to it. macOS and Linux work today; Windows is untested.
8
+
9
+ ## 0. Installed as the `thuthi-browser` plugin
10
+
11
+ The plugin cache holds only `plugins/thuthi-browser`, so the runtime and the extension come from the
12
+ marketplace checkout instead (`~/.claude/plugins/marketplaces/thuthi-plugin`, or the local path
13
+ the marketplace was added from). Use the `thuthi:setup` skill: it finds that checkout, runs
14
+ `npm install` + `npm link` there (`doctor.py fix pb-runtime`), and prints the `extension/` path
15
+ to load. Updates then apply themselves: the daemon restarts when its code changes and reloads the
16
+ extension, both once nothing is using the browser (on Chrome this needs the reloader below).
17
+
18
+ ## 1. The command
19
+
20
+ From a checkout:
21
+
22
+ ```bash
23
+ cd /path/to/parallel-browser
24
+ npm install
25
+ node bin/parallel-browser.js status
26
+ ```
27
+
28
+ To get `parallel-browser` on the PATH, `npm link` in that directory, or add
29
+ `/path/to/parallel-browser/bin` to PATH.
30
+
31
+ ## 2. The extension (the user does this once)
32
+
33
+ On Chrome, load `extension-reloader/` the same way as well: it lets the bridge reload itself from
34
+ disk when it is updated (Chrome does not bring an extension back after `chrome.runtime.reload()`;
35
+ Edge does, so there it is optional).
36
+
37
+ 1. Open `edge://extensions` or `chrome://extensions`.
38
+ 2. Turn on **Developer mode**.
39
+ 3. **Load unpacked** and choose the `extension/` directory of this checkout.
40
+
41
+ The extension connects to `ws://127.0.0.1:9333/ext` by itself and reconnects every second when
42
+ the runtime is not up yet. Nothing is sent anywhere else.
43
+
44
+ Loading it unpacked makes the browser show a "disable developer mode extensions" warning on
45
+ every start. That is expected until the extension is published to a store.
46
+
47
+ ## 3. Check the connection
48
+
49
+ ```bash
50
+ parallel-browser status
51
+ ```
52
+
53
+ `"connected": true` with a browser user agent means everything is wired. Then:
54
+
55
+ ```bash
56
+ parallel-browser nodejs -e 'const s = await session("smoke"); await s.goto("https://example.com"); out(await s.title());'
57
+ ```
58
+
59
+ `Example Domain` means the environment is ready. Go back to `SKILL.md`.
60
+
61
+ ## How it fits together
62
+
63
+ ```
64
+ your script → parallel-browser CLI → daemon (tcp 9336) → ws 9333 → extension → Chrome/Edge
65
+ ```
66
+
67
+ The daemon starts on the first CLI call and stays up, so separate invocations share one browser
68
+ connection and recordings can span them. Session state lives in the extension, so it survives
69
+ the CLI exiting and the daemon restarting.
70
+
71
+ ## Troubleshooting
72
+
73
+ - **`browser not connected`** — the extension is not loaded, or the browser is closed. Ask the
74
+ user to check `edge://extensions` and that the browser is running. The extension retries on
75
+ its own; no restart of the daemon is needed.
76
+ - **`daemon did not start`** — a stale process may hold the port. `parallel-browser daemon stop`,
77
+ then retry. `PC_CTRL_PORT` and `PC_RELAY_PORT` override the ports.
78
+ - **`EADDRINUSE 9333`** — something else already owns the relay port, usually a daemon that is
79
+ still running. Use the CLI (which goes through the daemon) rather than opening a second relay.
80
+ - **Commands time out after ~30s** — the browser is reachable but the page is not responding,
81
+ often a navigation to a server that never answers. Check the URL from a terminal.
82
+ - **`blocked by guard: ...`** — deliberate. Commands that could close or crash the browser, wipe
83
+ cookies or storage, or navigate to `chrome://`, `file://` or `javascript:` are refused. Find
84
+ another way to do the task.
85
+ - **`tab budget (N) reached`** — the session already owns its maximum tabs. Reuse one with
86
+ `goto()`, close one with `closeTab()`, or create the session with a larger `budget`.
87
+ - **`no session pb-…` for a handle that worked before** — sessions close by themselves within
88
+ seconds of their owner process exiting (the agent that ran the script). Make a new one.
89
+ - **`warning: could not register the session owner`** — the daemon predates owners. It restarts
90
+ by itself once nobody is connected; `parallel-browser daemon stop` does it now.
91
+ - **A recording or screenshot comes out at the tab area, cropped** — the session's tab became the
92
+ agent window's front tab (someone clicked it while in that window). It goes back behind, with
93
+ the emulated size set again, as soon as they leave the window.
94
+ - **`note: the browser runs an older parallel-browser extension`** — the daemon could not reload it
95
+ (Chrome without `extension-reloader/`, or a bridge from before self-update). Reload
96
+ parallel-browser on the extensions page once.
97
+ - **Something broke and you need to know why** — the daemon logs what happened in
98
+ `~/.local/state/parallel-browser/events.log`, one JSON line per event (session and tab closes with
99
+ their reason, tabs the browser froze, discarded or swapped, failed commands and timeouts, worker
100
+ restarts, and for recordings `record.start` · `record.stop` with frame counts · `record.encoded` ·
101
+ `record.failed` · `record.abandoned`). Look at the lines around the time it broke.
102
+ - **`stopRecording` returned `encoding: true`** — the video is still being copied into place (a
103
+ very slow disk). Not an error: `await s.waitForRecording(outMp4)` waits for it.
104
+ - **The session is paused** — the user pressed "내가 하기" on the page overlay (or paused from the
105
+ dashboard), or the agent handed over with `handOff`. Working in the page never pauses a session
106
+ by itself. Stop acting and report; resume only when they ask.
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "thuthi-demo-video",
3
+ "version": "0.14.2",
4
+ "description": "demo-video 스킬: 웹 앱 동작을 자막 · 화살표 · 빨리 감기가 들어간 시연 영상(mp4)으로 만든다",
5
+ "author": {
6
+ "name": "thuthi"
7
+ },
8
+ "dependencies": ["thuthi", "thuthi-browser"]
9
+ }
@@ -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,14 @@
1
+ """thuthi-demo-video 점검 (thuthi:setup 의 doctor.py 가 부른다). 자기 doctor (demo_video.py doctor) 를 그대로 쓴다."""
2
+ from __future__ import annotations
3
+
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ DV = Path(__file__).resolve().parent / "skills" / "demo-video" / "scripts" / "demo_video.py"
8
+
9
+
10
+ def check(d) -> list:
11
+ code, out = d.run([sys.executable, str(DV), "doctor"], timeout=120)
12
+ miss = [ln.split()[0] for ln in out.splitlines() if "없음" in ln]
13
+ return [("demo-video", d.OK if code == 0 else d.BAD, "녹화 · 렌더 도구 (demo_video.py doctor)",
14
+ "" if code == 0 else f"없음: {', '.join(miss) or '?'} → python3 {DV} doctor (ffmpeg 는 brew install ffmpeg)")]