cdpm-mcp 0.1.5 → 0.1.6

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.
package/README.md CHANGED
@@ -1,197 +1,199 @@
1
- # CDPM — CDP Manager
2
-
3
- [한국어 README](README.ko.md)
4
-
5
- > **Asked to install this? (for Claude / AI agents)** Do these steps in order.
6
- > 1. Check that Node.js 22+ and Google Chrome are installed. If not, tell the user and stop.
7
- > 2. Run `npm install -g cdpm-mcp@latest` (also when already installed: this updates it).
8
- > 3. Run `cdpm install` (if `cdpm` isn't found: `node "$(npm root -g)/cdpm-mcp/dist/cli.js" install`). It registers CDPM with Claude Code and sets up the status line, rules, subagent and permissions; an older git-clone registration is switched to the new location.
9
- > 4. Do not launch any Chrome slot, ask questions, or explain internals. On success reply with exactly one line in the user's language, e.g. "CDPM <version> installed. Restart Claude Code to use it." (version: `cdpm --version`). If a step failed, say only which step and why.
10
-
11
- An MCP server that runs **Chrome slots 1–30** over the Chrome DevTools Protocol, so several Claude sessions and subagents can share and drive the same browsers just by number: *"turn on slot 3"*, *"check slot 3"*.
12
-
13
- - **Pure CDP.** No Playwright, no Puppeteer, no stealth patches. A normal Chrome with a debugging port, driven with real input events.
14
- - **Numbered slots.** Slot *N* uses CDP port `14049 + N` (slot 1 = 14050 … slot 30 = 14079) and its own profile folder. The range avoids the common default 9222; set `CDPM_PORT_BASE` to move it if something else uses those ports. Ports outside that range are not managed.
15
- - **Starts only when asked.** No tool ever starts a closed slot except `browser_launch`. Without a number, the lowest free slot is used.
16
- - **Slots outlive their caller.** Closing CDPM, Claude Code or VS Code (even when it kills its whole process tree) does not close slot Chrome. Slots end only with `browser_close` / `cdpm close` or when you close that Chrome yourself.
17
- - **One taskbar button per slot**, with a browser-window icon in the slot color and the slot number, pre-corrected so the taskbar shows it pixel-sharp (drawn with the system font via GDI+, so no font files ship in the repo). The window title shows "3번" via Chrome's own window-name feature (pages can't see it).
18
- - **Built for many agents.** Every tool takes `slot` explicitly, records who opened each tab and who touched it last, warns (without blocking) when you act on a tab someone else just used, and serializes concurrent commands on the same tab.
19
- - **Agents can talk** with `slot_send` / `slot_inbox`; unread messages are also delivered at the top of every result.
20
- - **Status line.** `cdpm statusline` prints live slots as slot-colored numbers; each slot shows the title of the tab last acted on (no agent names; only blank/new tabs left shows just the number): `CDPM 1 NAVER 2 Daum`. It fits the terminal width (from ccstatusline): titles shrink first, then only numbers, then `+N` for the rest. A paused slot (`slot_pause` / `cdpm pause`) shows its number in dim gray instead of its slot color. A dim `CDPM -` when none are running. Ending a slot's Chrome yourself (closing its last window on Windows, Cmd+Q on macOS) removes it right away, and titles are read live.
21
- - **English for the AI.** Server instructions, tool descriptions and tool results are in English to save tokens; Claude is told to answer in the user's language. CLI output is in Korean.
22
- - **Leaves the user's PC alone.** No window, viewport or zoom changes, and actions that would pop up OS windows are refused (see below).
23
-
24
- > Works on Windows 11 and macOS. Per-slot icons: taskbar on Windows, Dock on macOS (see "macOS" below).
25
- > Linux is experimental: the code paths exist (Chrome lookup, data folder) but it has not been tested on a Linux machine, and there are no per-slot icons.
26
-
27
- ## Requirements
28
-
29
- - Node.js 22+
30
- - Google Chrome (found automatically. Windows: registry `App Paths`, then standard install folders. macOS: `/Applications`, `~/Applications`, then Spotlight. Linux: `/usr/bin/google-chrome`, `google-chrome-stable`, `/opt/google/chrome/chrome`)
31
-
32
- ## Install
33
-
34
- ```sh
35
- npm install -g cdpm-mcp
36
- cdpm install
37
- ```
38
-
39
- `cdpm install` registers CDPM with Claude Code and sets up the status line, the parallel-work rule, the `cdpm-browser` subagent and the permission allow list in one go. Restart Claude Code afterwards.
40
-
41
- ### Other MCP clients (Cursor, Claude Desktop, ...)
42
-
43
- `cdpm install` only registers with Claude Code. For other clients add it to their `mcpServers` config (paths from `npm root -g`):
44
-
45
- ```json
46
- {
47
- "mcpServers": {
48
- "cdpm": {
49
- "command": "C:\\Program Files\\nodejs\\node.exe",
50
- "args": ["C:\\Users\\<you>\\AppData\\Roaming\\npm\\node_modules\\cdpm-mcp\\dist\\cli.js"]
51
- }
52
- }
53
- }
54
- ```
55
-
56
- On macOS: `"command": "/opt/homebrew/opt/node/bin/node"`, `"args": ["/opt/homebrew/lib/node_modules/cdpm-mcp/dist/cli.js"]`.
57
-
58
- - The tools are the same for every client.
59
- - CDPM picks its instructions from the connecting client's name: only `claude-code` gets the Claude Code specific guidance (spawning subagents with the Agent tool, `cdpm-browser`). Other clients get a generic rule: give each slot its own subagent if the client has them, otherwise use a different `agent` name per slot.
60
- - The automatic setup (status line, `CLAUDE.md` rule, `cdpm-browser`, permissions) changes `~/.claude`, so it only runs when Claude Code connects. Starting CDPM from another client never touches Claude Code's settings.
61
-
62
- ### From a clone (development)
63
-
64
- ```sh
65
- git clone https://github.com/IGELHARINE/CDPM.git
66
- cd CDPM
67
- npm install
68
- node dist/cli.js install
69
- ```
70
-
71
- ### Update
72
-
73
- ```sh
74
- npm install -g cdpm-mcp@latest
75
- ```
76
-
77
- Then restart Claude Code. From a clone: `git fetch origin && git reset --hard origin/main` and `npm install`. The MCP registration and status line setting stay as they are. Check the version with `node dist/cli.js --version`; changes are listed in [CHANGELOG.md](CHANGELOG.md).
78
-
79
- Or just ask Claude: "update CDPM".
80
-
81
- ### What happens automatically
82
-
83
- The first time the MCP server starts, CDPM sets these up once, with no extra steps (original files backed up as `.before-cdpm`):
84
- - the slot display in Claude Code's status line (redrawn every 3 s)
85
- - a rule in the user's `CLAUDE.md`: when several slots get different jobs, use one subagent per slot in parallel and let each write its own part of the output (Claude follows user instructions more reliably than MCP guidance)
86
- - a CDPM-only subagent `cdpm-browser` in `~/.claude/agents/`: only CDPM tools plus file writing, no `CLAUDE.md`, so it starts faster (measured on a 3-slot parallel job: median 28.7 s -> 20.6 s, about 37% less usage); same model and effort as the main agent. It uses whatever name CDPM is registered under.
87
- - CDPM tools (`mcp__cdpm`) in Claude Code's permission allow list (`permissions.allow` in `settings.json`), so auto mode's classifier doesn't block typing and filling mid-task. Claude then performs CDPM input and clicks (sending mail, posting) without asking each time.
88
- - subagents run at most 20 at once, so beyond 20 slots Claude is told to launch them in batches (raise with `CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS`).
89
-
90
- Undo with `cdpm unsetup`; skip it entirely with `CDPM_NO_AUTO_SETUP=1`. When an update changes the automatic setup it runs once more, item by item: items still present are refreshed, items you removed (including with `cdpm unsetup`) are not brought back. `cdpm setup` re-adds everything.
91
-
92
- ### Status line only
93
-
94
- `cdpm install` (and the first server start) already turns it on. To redo only the status line: `cdpm statusline-setup`. With no status line it adds one to Claude's settings; with ccstatusline it adds a widget; with any other status line it changes nothing and prints the command to append. The original file is backed up as `.before-cdpm`.
95
-
96
- ## How it behaves
97
-
98
- Each result starts with a header: the slot's tabs (`>` = acted on now, `·앞` = the tab in front in its window), warnings, and new messages (marked as read there).
99
-
100
- **Tab rules:** one tab → that tab; the agent's last-used (or newly opened) tab → that tab; first use → view tools take the front tab, action tools require `tab`. Tab numbers follow first-seen order; IDs like `t7` never change while the tab lives.
101
-
102
- **Sharing one slot:** several agents (even in different Claude sessions) can work in one slot at the same time, each in its own tab. Commands queue per tab, so agent A can type in tab 1 while agent B clicks in tab 2; only commands on the same tab wait for each other, across Claude sessions too (a per-tab lock file), so two sessions typing into one tab never interleave; a lock held by a dead process is released at once, and one held over 2 minutes is reported instead of waited on. Starting and closing a slot also take a per-slot lock, so two sessions starting the same slot at once launch Chrome only once (the other attaches). One slot is one Chrome profile, so a site logged in in one tab is logged in in a new tab too (except sites that authenticate per tab). `browser_tab_new` opens in the background, so neither the user's view nor another agent's tab changes, and the opener keeps using its own tab. Every session gets its own name (`claude-a3f1`, subagents use theirs); headers show who opened and last used each tab, and acting on a tab someone else just used is reported, not blocked. One agent drives one slot: acting on a second slot within a minute is refused with advice to start a subagent for it (`multiSlot: true` for comparisons); reading other slots is always allowed. Refer to slots by number ("slot 3"); a name like "browser B" makes Claude guess.
103
-
104
- **Background tabs** can be read, driven and captured without switching tabs: while acting on a hidden tab, CDPM briefly enables `Emulation.setFocusEmulationEnabled` so Chrome paints it, then turns it off. The user's view does not change, but during that moment the page sees the tab as focused (`document.hasFocus()` etc.), so a site could notice.
105
-
106
- **Long pages:** `browser_snapshot` returns page 1 (~12k chars) with "1/8 · next: page=2". Later pages carry their ancestor context; refs stay the same across pages. `find` matches lines ignoring whitespace and shows ancestors plus the next two lines; `ref` shows one subtree. `browser_text` is shorter for reading content. The same element keeps the same ref until navigation, and new refs are unique per agent across tabs, so a ref from another tab or an old page is always rejected.
107
-
108
- ## Tools
109
-
110
- All tools take `slot` (1–30) and `agent` (display name). Action tools also take `tab`, `summary` and `read`: `read: "text" | "snapshot" | "changes"` attaches the page after the action to the same result (no separate read call). `changes` shows only lines added or removed since the agent's previous snapshot of that page — the shortest way to see what a click did.
111
-
112
- | Tool | What it does |
113
- |---|---|
114
- | `browser_status` | Live slots, tabs, openers, last actions, summaries, dialogs |
115
- | `browser_launch` | Start a slot — only when the user asks; no `slot` = lowest free; `slots` (list) or `count` start several at once, lowest first; `url` / `urls` open a start page right away. Window or headless is the user's choice: if they didn't say, Claude asks first (without `headless`, a closed slot is not started). `headless: true` adds only `--headless`. `proxy` / `proxies` (only when the user asks for a proxy): `host:port`, `http://user:pass@host:port`, `socks5://...`, `host:port:user:pass`. Without it, no proxy flag is added at all. Proxies with a username and password go through a small per-slot local relay that adds the credentials and exits with that Chrome |
116
- | `browser_close` | Close gracefully (profile kept) |
117
- | `browser_tabs` / `browser_tab_new` / `browser_tab_close` / `browser_tab_select` | List / open in background (returns ID) / close / bring to front (only when the user wants) |
118
- | `browser_snapshot` | Accessibility text with refs; `page`, `find`, `ref` |
119
- | `browser_text` | Readable text (main/article first, or one `ref`), paginated |
120
- | `browser_screenshot` | Visible area as PNG, background tabs included; no full-page capture |
121
- | `browser_navigate` / `browser_back` | Waits for load; slow servers are reported as "still loading", not as errors |
122
- | `browser_click` | Real mouse click; reports covering elements, new tabs, form-validation failures |
123
- | `browser_type` | Real key events per character (`clear`, `submit`, `fast`); verifies the value and does not press Enter for `submit` if the value differs (the site rejected or reformatted the input); date/time inputs are set after format validation |
124
- | `browser_fill` | Fill several inputs on one page in order, then optionally `submit` ("Enter" or a button ref); stops at the first failure, page change, dialog or a field whose value differs from what was typed (nothing is submitted then) |
125
- | `browser_dialog` | Accept or dismiss an open alert/confirm/prompt/beforeunload (`text` for prompt). Claude decides from the message |
126
- | `browser_forward` / `browser_reload` | Forward / reload (Chrome's own reload, `ignore_cache`) |
127
- | `browser_hover` | Real mouse over an element (hover-only menus) |
128
- | `browser_drag` | Real mouse drag: drag-and-drop, sliders, reordering. Drop on `to` (ref), `to_text` (text) or `dx`/`dy`. HTML5 drags are handled without an OS drag; `draggable` elements get refs |
129
- | `browser_download_wait` | Wait for a download to finish and return the saved file path (Chrome's download folder setting is kept) |
130
- | `browser_pdf` | Save the page as PDF (default: Downloads folder, named after the title) |
131
- | `browser_upload` | Upload files: into a file input by ref, or after clicking an "attach" button (CDPM intercepts the OS file dialog so it never appears) without a ref |
132
- | `browser_select` | `<select>`: focus + keys (arrow keys on Windows, option prefix on macOS; trusted events, no popup) |
133
- | `browser_press_key` | `Enter`, `Tab`, `Control+A` (`Meta+A` on macOS), … (clipboard keys refused) |
134
- | `browser_scroll` | To a ref, or exactly `dy` pixels (reports position A → B) |
135
- | `browser_wait` | Text in body or title / `gone` (text disappears) / `url` change / `enabled` (a button or input stops being disabled) / `response` (a network response whose URL matches finishes; returns its body, e.g. the JSON behind an SPA list — responses that arrived while you clicked are caught too; nothing extra is sent) / `network_idle` / N seconds |
136
- | `browser_eval` | JavaScript in an isolated world (DOM visible, page globals not) |
137
- | `browser_network` / `browser_network_detail` | Requests (last 500, 30 min) / headers, post data, body |
138
- | `browser_block` | Block/unblock URL patterns on a tab, including its cross-site iframes (already open or created later, blocked before their first request); while the session lives; visible to other agents |
139
- | `slot_send` / `slot_inbox` | Message an agent (use the receiver's slot number, works across slots) / receive (`wait` returns within ~0.1 s of a message, up to 600 s). A message also interrupts `browser_wait` immediately |
140
- | `slot_pause` / `slot_resume` | Pause a slot when the user says so ("stop slot 3"): every action is refused at once, an action already running stops before its next key or mouse event, and waits return. Reading the screen still works. Resume wakes the agents with a message so they re-read the page and continue. Applies to every Claude session |
141
-
142
- Subagents share their parent's MCP process — give each one its own `agent` name. When several slots get different jobs ("open 3: Naver, Daum, Google News"), Claude runs them in parallel by default, one subagent per slot, not one after another.
143
-
144
- ## Status line
145
-
146
- `cdpm statusline` exits in ~0.1 s (local registry plus a quick tab check on each live slot port); setup makes Claude Code redraw it every 3 s. Turned on by `cdpm install`; redo with `cdpm statusline-setup`. To wire it by hand: for **ccstatusline**, add a *Custom Command* widget with `"C:\Program Files\nodejs\node.exe" "C:\path\to\CDPM\dist\cli.js" statusline` (preserve colors). Otherwise point `statusLine.command` at the same command.
147
-
148
- ## CLI
149
-
150
- ```
151
- cdpm run the MCP server (stdio)
152
- cdpm install register with Claude Code and run the automatic setup (once after installing)
153
- cdpm setup add the status line, CLAUDE.md rule, cdpm-browser subagent and permission allow list, including ones you removed (also done automatically on first server start)
154
- cdpm unsetup remove what CDPM added
155
- cdpm --version print the version
156
- cdpm launch [slot...] start slots (ascending order; no number = lowest free)
157
- cdpm launch --headless [slot...] start without a window
158
- cdpm close <slot...> | --all close gracefully
159
- cdpm pause <slot...> | --all pause: stop all agent actions on the slot immediately
160
- cdpm resume <slot...> | --all resume: wake the waiting agents
161
- cdpm purge <slot> delete a closed slot's profile
162
- cdpm status | statusline
163
- cdpm statusline-setup turn on the slot display in Claude Code's status line (backs up settings)
164
- ```
165
-
166
- Data lives in `%LOCALAPPDATA%\cdpm\` on Windows `~/Library/Application Support/cdpm/` on macOS and `~/.cdpm/` on Linux (`CDPM_HOME` overrides): `registry.json`, `messages\<slot>.jsonl` (last 500 lines once over 1000) and `messages\<slot>.cursors.json` (read position per agent, latest 200), `locks\` (per-tab and per-slot lock files so Claude sessions never drive one tab, or start/close one slot, at once; removed when the action ends, leftovers of dead processes cleaned every minute), `profiles\<slot>\`, `icons\`, `auto-setup.json` (which setup version ran and which items CDPM added, so removed items are not brought back), optional `config.json` (`chromePath`, `extraArgs`).
167
-
168
- ## macOS
169
-
170
- - Launching, driving, network tools, agent messaging and the status line work the same as on Windows.
171
- - Each slot's Dock icon is set to the same slot-colored numbered icon as on Windows, through Chrome's own CDP command `Browser.setDockTile` (no app copying or re-signing). It returns to the normal Chrome icon if Chrome restarts outside CDPM, and is set again the next time CDPM launches or attaches. This code runs only on macOS.
172
- - Following the Mac convention, closing a slot's window (red button, Cmd+W) keeps the slot; the status line keeps showing the last-used tab title. Quitting Chrome with Cmd+Q ends the slot and removes it. (On Windows, closing the last window ends the slot.)
173
- - Chrome on macOS doesn't run editing shortcuts from key events alone, so `Meta+A` (select all), `Meta+Z` (undo), `Meta+←/→`, `Option+←/→` and similar also send the matching Chrome editing command with the same key event — the same thing a person pressing the key gets.
174
- - Arrow keys on a `<select>` open the macOS popup menu, so `browser_select` types the start of the option text instead. If an earlier option shares that prefix, it sets the value directly and says so.
175
-
176
- ## What CDPM does not do / refuses
177
-
178
- - No user-agent or fingerprint changes, device emulation or Chrome patching, and no page script changes except the print guard below.
179
- - Things you click yourself open as usual. Only while an agent action runs, CDPM keeps OS windows from appearing:
180
- - File pickers are intercepted however the action opens them (click, Enter on a file input, form submit), with a hint to use `browser_upload`.
181
- - `window.print()` would open print preview and freeze the tab (it cannot be closed over CDP), so the page's `print` is disabled for the duration of the action only, reported, and restored right after. Use `browser_pdf` for a PDF.
182
- - Date, time and color inputs are not clicked (they open a picker); `browser_type` sets their value (`#ff0000` for colors).
183
- - Browser shortcuts such as `Ctrl+S`/`Ctrl+O`/`Ctrl+P` sent over CDP do not trigger Chrome's save/open/print windows.
184
- - Known limits: a button whose JavaScript navigates to an external-program scheme (`mailto:` etc.) is not caught in advance (links are); HTTP authentication prompts cannot be filled by an agent.
185
- - Launch flags are only `--remote-debugging-port`, `--user-data-dir`, `--no-first-run`, `--no-default-browser-check`, `--window-name` (plus `--headless` on request, and `--proxy-server` + `--force-webrtc-ip-handling-policy=disable_non_proxied_udp` only when the user asks for a proxy; headless Chrome still reports `HeadlessChrome`).
186
- - Never changes window size/position/state, viewport, or zoom; if a click makes the page fullscreen, it is exited immediately.
187
- - No `Runtime.enable`; helper scripts run in an isolated world.
188
- - Dialogs (alert/confirm/prompt/beforeunload) are reported, never handled automatically. Claude reads the message and handles it itself with `browser_dialog` (accept or dismiss); it asks the user only when the dialog would confirm something irreversible the user did not ask for (a payment, a deletion).
189
- - Refuses: `mailto:`/`tel:`/app-scheme links and addresses in click, navigate, launch start pages and new tabs (would launch other programs), clicking `<select>` (popup), `Ctrl+C/X/V`/`Shift+Insert` (user clipboard). Downloads triggered by navigation are reported with the file name.
190
-
191
- ## Verification
192
-
193
- 58 unit and 40 integration tests (`npm test`, `npm run test:integration`, real Chrome on test ports 29222+). Long-running checks (`npm run test:long`, ~20 min): 4,000 rounds on an SPA that replaces its DOM, with a new agent name every round, kept the CDPM server heap within a fixed band (26–39 MB, no upward trend) and the page at 1,421 DOM nodes / 0.8 MB JS heap; 3 sessions sharing one slot for 600 rounds each (1,800 tabs opened and closed, the slot restarted 3 times) stayed at ~20 MB heap per session with no lock files or tabs left behind. A 15-subagent, 30-slot concurrent run confirmed that all 30 windows' position/size/state and all 52 tabs' viewport (`innerWidth×innerHeight`) and zoom were unchanged.
194
-
195
- ## License
196
-
197
- MIT
1
+ # CDPM — CDP Manager
2
+
3
+ [한국어 README](README.ko.md)
4
+
5
+ > **Asked to install this? (for Claude / AI agents)** Do these steps in order.
6
+ > 1. Check that Node.js 22+ and Google Chrome are installed. If not, tell the user and stop.
7
+ > 2. Run `npm install -g cdpm-mcp@latest` (also when already installed: this updates it).
8
+ > 3. Run `cdpm install` (if `cdpm` isn't found: `node "$(npm root -g)/cdpm-mcp/dist/cli.js" install`). It registers CDPM with Claude Code and sets up the status line, rules, subagent and permissions; an older git-clone registration is switched to the new location.
9
+ > 4. Do not launch any Chrome slot, ask questions, or explain internals. On success reply with exactly one line in the user's language, e.g. "CDPM <version> installed. Restart Claude Code to use it." (version: `cdpm --version`). If a step failed, say only which step and why.
10
+
11
+ An MCP server that runs **Chrome slots 1–30** over the Chrome DevTools Protocol, so several Claude sessions and subagents can share and drive the same browsers just by number: *"turn on slot 3"*, *"check slot 3"*.
12
+
13
+ - **Pure CDP.** No Playwright, no Puppeteer, no stealth patches. A normal Chrome with a debugging port, driven with real input events.
14
+ - **Numbered slots.** Slot *N* uses CDP port `14049 + N` (slot 1 = 14050 … slot 30 = 14079) and its own profile folder. The range avoids the common default 9222; set `CDPM_PORT_BASE` to move it if something else uses those ports. Ports outside that range are not managed.
15
+ - **Starts only when asked.** No tool ever starts a closed slot except `browser_launch`. Without a number, the lowest free slot is used.
16
+ - **Slots outlive their caller.** Closing CDPM, Claude Code or VS Code (even when it kills its whole process tree) does not close slot Chrome. Slots end only with `browser_close` / `cdpm close` or when you close that Chrome yourself.
17
+ - **One taskbar button per slot**, with a browser-window icon in the slot color and the slot number, pre-corrected so the taskbar shows it pixel-sharp (drawn with the system font via GDI+, so no font files ship in the repo). The window title shows "3번" via Chrome's own window-name feature (pages can't see it).
18
+ - **Built for many agents.** Every tool takes `slot` explicitly, records who opened each tab and who touched it last, warns (without blocking) when you act on a tab someone else just used, and serializes concurrent commands on the same tab.
19
+ - **Agents can talk** with `slot_send` / `slot_inbox`; unread messages are also delivered at the top of every result.
20
+ - **Status line.** `cdpm statusline` prints live slots as slot-colored numbers; each slot shows the title of the tab last acted on (no agent names; only blank/new tabs left shows just the number): `CDPM 1 NAVER 2 Daum`. It fits the terminal width (from ccstatusline): titles shrink first, then only numbers, then `+N` for the rest. A paused slot (`slot_pause` / `cdpm pause`) shows its number in dim gray instead of its slot color. A dim `CDPM -` when none are running. Ending a slot's Chrome yourself (closing its last window on Windows, Cmd+Q on macOS) removes it right away, and titles are read live.
21
+ - **English for the AI.** Server instructions, tool descriptions and tool results are in English to save tokens; Claude is told to answer in the user's language. CLI output is in Korean.
22
+ - **Leaves the user's PC alone.** No window, viewport or zoom changes, and actions that would pop up OS windows are refused (see below).
23
+
24
+ > Works on Windows 11 and macOS. Per-slot icons: taskbar on Windows, Dock on macOS (see "macOS" below).
25
+ > Linux is experimental: the code paths exist (Chrome lookup, data folder) but it has not been tested on a Linux machine, and there are no per-slot icons.
26
+
27
+ ## Requirements
28
+
29
+ - Node.js 22+
30
+ - Google Chrome (found automatically. Windows: registry `App Paths`, then standard install folders. macOS: `/Applications`, `~/Applications`, then Spotlight. Linux: `/usr/bin/google-chrome`, `google-chrome-stable`, `/opt/google/chrome/chrome`)
31
+
32
+ ## Install
33
+
34
+ ```sh
35
+ npm install -g cdpm-mcp
36
+ cdpm install
37
+ ```
38
+
39
+ `cdpm install` registers CDPM with Claude Code and sets up the status line, the parallel-work rule, the `cdpm-browser` subagent and the permission allow list in one go. Restart Claude Code afterwards.
40
+
41
+ ### Other MCP clients (Cursor, Claude Desktop, ...)
42
+
43
+ `cdpm install` only registers with Claude Code. For other clients add it to their `mcpServers` config (paths from `npm root -g`):
44
+
45
+ ```json
46
+ {
47
+ "mcpServers": {
48
+ "cdpm": {
49
+ "command": "C:\\Program Files\\nodejs\\node.exe",
50
+ "args": ["C:\\Users\\<you>\\AppData\\Roaming\\npm\\node_modules\\cdpm-mcp\\dist\\cli.js"]
51
+ }
52
+ }
53
+ }
54
+ ```
55
+
56
+ On macOS: `"command": "/opt/homebrew/opt/node/bin/node"`, `"args": ["/opt/homebrew/lib/node_modules/cdpm-mcp/dist/cli.js"]`.
57
+
58
+ - The tools are the same for every client.
59
+ - CDPM picks its instructions from the connecting client's name: only `claude-code` gets the Claude Code specific guidance (spawning subagents with the Agent tool, `cdpm-browser`). Other clients get a generic rule: give each slot its own subagent if the client has them, otherwise use a different `agent` name per slot.
60
+ - The automatic setup (status line, `CLAUDE.md` rule, `cdpm-browser`, permissions) changes `~/.claude`, so it only runs when Claude Code connects. Starting CDPM from another client never touches Claude Code's settings.
61
+
62
+ ### From a clone (development)
63
+
64
+ ```sh
65
+ git clone https://github.com/IGELHARINE/CDPM.git
66
+ cd CDPM
67
+ npm install
68
+ node dist/cli.js install
69
+ ```
70
+
71
+ ### Update
72
+
73
+ ```sh
74
+ npm install -g cdpm-mcp@latest
75
+ ```
76
+
77
+ Then restart Claude Code. From a clone: `git fetch origin && git reset --hard origin/main` and `npm install`. The MCP registration and status line setting stay as they are. Check the version with `node dist/cli.js --version`; changes are listed in [CHANGELOG.md](CHANGELOG.md).
78
+
79
+ Or just ask Claude: "update CDPM".
80
+
81
+ ### What happens automatically
82
+
83
+ The first time the MCP server starts, CDPM sets these up once, with no extra steps (original files backed up as `.before-cdpm`):
84
+ - the slot display in Claude Code's status line (redrawn every 3 s)
85
+ - a rule in the user's `CLAUDE.md`: when several slots get different jobs, use one subagent per slot in parallel and let each write its own part of the output (Claude follows user instructions more reliably than MCP guidance)
86
+ - a CDPM-only subagent `cdpm-browser` in `~/.claude/agents/`: only CDPM tools plus file writing, no `CLAUDE.md`, so it starts faster (measured on a 3-slot parallel job: median 28.7 s -> 20.6 s, about 37% less usage); same model and effort as the main agent. It uses whatever name CDPM is registered under.
87
+ - CDPM tools (`mcp__cdpm`) in Claude Code's permission allow list (`permissions.allow` in `settings.json`), so auto mode's classifier doesn't block typing and filling mid-task. Claude then performs CDPM input and clicks (sending mail, posting) without asking each time.
88
+ - subagents run at most 20 at once, so beyond 20 slots Claude is told to launch them in batches (raise with `CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS`).
89
+
90
+ Undo with `cdpm unsetup`; skip it entirely with `CDPM_NO_AUTO_SETUP=1`. When an update changes the automatic setup it runs once more, item by item: items still present are refreshed, items you removed (including with `cdpm unsetup`) are not brought back. `cdpm setup` re-adds everything.
91
+
92
+ ### Status line only
93
+
94
+ `cdpm install` (and the first server start) already turns it on. To redo only the status line: `cdpm statusline-setup`. With no status line it adds one to Claude's settings; with ccstatusline it adds a widget; with any other status line it changes nothing and prints the command to append. The original file is backed up as `.before-cdpm`.
95
+
96
+ ## How it behaves
97
+
98
+ Each result starts with a header: the slot's tabs (`>` = acted on now, `·앞` = the tab in front in its window), warnings, and new messages (marked as read there).
99
+
100
+ **Tab rules:** one tab → that tab; the agent's last-used (or newly opened) tab → that tab; first use → view tools take the front tab, action tools require `tab`. Tab numbers follow first-seen order; IDs like `t7` never change while the tab lives.
101
+
102
+ **Sharing one slot:** several agents (even in different Claude sessions) can work in one slot at the same time, each in its own tab. Commands queue per tab, so agent A can type in tab 1 while agent B clicks in tab 2; only commands on the same tab wait for each other, across Claude sessions too (a per-tab lock file), so two sessions typing into one tab never interleave; a lock held by a dead process is released at once, and one held over 2 minutes is reported instead of waited on. Starting and closing a slot also take a per-slot lock, so two sessions starting the same slot at once launch Chrome only once (the other attaches). One slot is one Chrome profile, so a site logged in in one tab is logged in in a new tab too (except sites that authenticate per tab). `browser_tab_new` opens in the background, so neither the user's view nor another agent's tab changes, and the opener keeps using its own tab. Every session gets its own name (`claude-a3f1`, subagents use theirs); headers show who opened and last used each tab, and acting on a tab someone else just used is reported, not blocked. One agent drives one slot: acting on a second slot within a minute is refused with advice to start a subagent for it (`multiSlot: true` for comparisons); reading other slots is always allowed. Refer to slots by number ("slot 3"); a name like "browser B" makes Claude guess.
103
+
104
+ **Background tabs** can be read, driven and captured without switching tabs: while acting on a hidden tab, CDPM briefly enables `Emulation.setFocusEmulationEnabled` so Chrome paints it, then turns it off. The user's view does not change, but during that moment the page sees the tab as focused (`document.hasFocus()` etc.), so a site could notice.
105
+
106
+ **Long pages:** `browser_snapshot` returns page 1 (~12k chars) with "1/8 · next: page=2". Later pages carry their ancestor context; refs stay the same across pages. `find` matches lines ignoring whitespace and shows ancestors plus the next two lines; `ref` shows one subtree. `browser_text` is shorter for reading content. The same element keeps the same ref until navigation, and new refs are unique per agent across tabs, so a ref from another tab or an old page is always rejected.
107
+
108
+ ## Tools
109
+
110
+ All tools take `slot` (1–30) and `agent` (display name). Action tools also take `tab`, `summary` and `read`: `read: "text" | "snapshot" | "changes"` attaches the page after the action to the same result (no separate read call). `changes` shows only lines added or removed since the agent's previous snapshot of that page — the shortest way to see what a click did.
111
+
112
+ | Tool | What it does |
113
+ |---|---|
114
+ | `browser_status` | Live slots, tabs, openers, last actions, summaries, dialogs |
115
+ | `browser_launch` | Start a slot — only when the user asks; no `slot` = lowest free; `slots` (list) or `count` start several at once, lowest first; `url` / `urls` open a start page right away. Window or headless is the user's choice: if they didn't say, Claude asks first (without `headless`, a closed slot is not started). `headless: true` adds only `--headless`. `proxy` / `proxies` (only when the user asks for a proxy): `host:port`, `http://user:pass@host:port`, `socks5://...`, `host:port:user:pass`. Without it, no proxy flag is added at all. Proxies with a username and password go through a small per-slot local relay that adds the credentials and exits with that Chrome |
116
+ | `browser_close` | Close gracefully (profile kept) |
117
+ | `browser_tabs` / `browser_tab_new` / `browser_tab_close` / `browser_tab_select` | List / open in background (returns ID) / close / bring to front (only when the user wants) |
118
+ | `browser_snapshot` | Accessibility text with refs; `page`, `find`, `ref` |
119
+ | `browser_text` | Readable text (main/article first, or one `ref`), paginated |
120
+ | `browser_screenshot` | Visible area as PNG, background tabs included; no full-page capture |
121
+ | `browser_navigate` / `browser_back` | Waits for load; slow servers are reported as "still loading", not as errors |
122
+ | `browser_click` | Real mouse click; reports covering elements, new tabs, form-validation failures |
123
+ | `browser_type` | Real key events per character (`clear`, `submit`, `fast`); verifies the value and does not press Enter for `submit` if the value differs (the site rejected or reformatted the input); date/time inputs are set after format validation |
124
+ | `browser_fill` | Fill several inputs on one page in order, then optionally `submit` ("Enter" or a button ref); stops at the first failure, page change, dialog or a field whose value differs from what was typed (nothing is submitted then) |
125
+ | `browser_dialog` | Accept or dismiss an open alert/confirm/prompt/beforeunload (`text` for prompt). Claude decides from the message |
126
+ | `browser_permission` | List or answer Chrome permission bubbles ("site wants to access other apps and services on this device", notifications, location…) by exact button name. Windows, windowed slots |
127
+ | `browser_forward` / `browser_reload` | Forward / reload (Chrome's own reload, `ignore_cache`) |
128
+ | `browser_hover` | Real mouse over an element (hover-only menus) |
129
+ | `browser_drag` | Real mouse drag: drag-and-drop, sliders, reordering. Drop on `to` (ref), `to_text` (text) or `dx`/`dy`. HTML5 drags are handled without an OS drag; `draggable` elements get refs |
130
+ | `browser_download_wait` | Wait for a download to finish and return the saved file path (Chrome's download folder setting is kept) |
131
+ | `browser_pdf` | Save the page as PDF (default: Downloads folder, named after the title) |
132
+ | `browser_upload` | Upload files: into a file input by ref, or after clicking an "attach" button (CDPM intercepts the OS file dialog so it never appears) without a ref |
133
+ | `browser_select` | `<select>`: focus + keys (arrow keys on Windows, option prefix on macOS; trusted events, no popup) |
134
+ | `browser_press_key` | `Enter`, `Tab`, `Control+A` (`Meta+A` on macOS), … (clipboard keys refused) |
135
+ | `browser_scroll` | To a ref, or exactly `dy` pixels (reports position A → B) |
136
+ | `browser_wait` | Text in body or title / `gone` (text disappears) / `url` change / `enabled` (a button or input stops being disabled) / `response` (a network response whose URL matches finishes; returns its body, e.g. the JSON behind an SPA list — responses that arrived while you clicked are caught too; nothing extra is sent) / `network_idle` / N seconds |
137
+ | `browser_eval` | JavaScript in an isolated world (DOM visible, page globals not) |
138
+ | `browser_network` / `browser_network_detail` | Requests (last 500, 30 min) / headers, post data, body |
139
+ | `browser_block` | Block/unblock URL patterns on a tab, including its cross-site iframes (already open or created later, blocked before their first request); while the session lives; visible to other agents |
140
+ | `slot_send` / `slot_inbox` | Message an agent (use the receiver's slot number, works across slots) / receive (`wait` returns within ~0.1 s of a message, up to 600 s). A message also interrupts `browser_wait` immediately |
141
+ | `slot_pause` / `slot_resume` | Pause a slot when the user says so ("stop slot 3"): every action is refused at once, an action already running stops before its next key or mouse event, and waits return. Reading the screen still works. Resume wakes the agents with a message so they re-read the page and continue. Applies to every Claude session |
142
+
143
+ Subagents share their parent's MCP process — give each one its own `agent` name. When several slots get different jobs ("open 3: Naver, Daum, Google News"), Claude runs them in parallel by default, one subagent per slot, not one after another.
144
+
145
+ ## Status line
146
+
147
+ `cdpm statusline` exits in ~0.1 s (local registry plus a quick tab check on each live slot port); setup makes Claude Code redraw it every 3 s. Turned on by `cdpm install`; redo with `cdpm statusline-setup`. To wire it by hand: for **ccstatusline**, add a *Custom Command* widget with `"C:\Program Files\nodejs\node.exe" "C:\path\to\CDPM\dist\cli.js" statusline` (preserve colors). Otherwise point `statusLine.command` at the same command.
148
+
149
+ ## CLI
150
+
151
+ ```
152
+ cdpm run the MCP server (stdio)
153
+ cdpm install register with Claude Code and run the automatic setup (once after installing)
154
+ cdpm setup add the status line, CLAUDE.md rule, cdpm-browser subagent and permission allow list, including ones you removed (also done automatically on first server start)
155
+ cdpm unsetup remove what CDPM added
156
+ cdpm --version print the version
157
+ cdpm launch [slot...] start slots (ascending order; no number = lowest free)
158
+ cdpm launch --headless [slot...] start without a window
159
+ cdpm close <slot...> | --all close gracefully
160
+ cdpm pause <slot...> | --all pause: stop all agent actions on the slot immediately
161
+ cdpm resume <slot...> | --all resume: wake the waiting agents
162
+ cdpm purge <slot> delete a closed slot's profile
163
+ cdpm status | statusline
164
+ cdpm statusline-setup turn on the slot display in Claude Code's status line (backs up settings)
165
+ ```
166
+
167
+ Data lives in `%LOCALAPPDATA%\cdpm\` on Windows `~/Library/Application Support/cdpm/` on macOS and `~/.cdpm/` on Linux (`CDPM_HOME` overrides): `registry.json`, `messages\<slot>.jsonl` (last 500 lines once over 1000) and `messages\<slot>.cursors.json` (read position per agent, latest 200), `locks\` (per-tab and per-slot lock files so Claude sessions never drive one tab, or start/close one slot, at once; removed when the action ends, leftovers of dead processes cleaned every minute), `profiles\<slot>\`, `icons\`, `auto-setup.json` (which setup version ran and which items CDPM added, so removed items are not brought back), optional `config.json` (`chromePath`, `extraArgs`).
168
+
169
+ ## macOS
170
+
171
+ - Launching, driving, network tools, agent messaging and the status line work the same as on Windows.
172
+ - Each slot's Dock icon is set to the same slot-colored numbered icon as on Windows, through Chrome's own CDP command `Browser.setDockTile` (no app copying or re-signing). It returns to the normal Chrome icon if Chrome restarts outside CDPM, and is set again the next time CDPM launches or attaches. This code runs only on macOS.
173
+ - Following the Mac convention, closing a slot's window (red button, Cmd+W) keeps the slot; the status line keeps showing the last-used tab title. Quitting Chrome with Cmd+Q ends the slot and removes it. (On Windows, closing the last window ends the slot.)
174
+ - Chrome on macOS doesn't run editing shortcuts from key events alone, so `Meta+A` (select all), `Meta+Z` (undo), `Meta+←/→`, `Option+←/→` and similar also send the matching Chrome editing command with the same key event — the same thing a person pressing the key gets.
175
+ - Arrow keys on a `<select>` open the macOS popup menu, so `browser_select` types the start of the option text instead. If an earlier option shares that prefix, it sets the value directly and says so.
176
+
177
+ ## What CDPM does not do / refuses
178
+
179
+ - No user-agent or fingerprint changes, device emulation or Chrome patching, and no page script changes except the print guard below.
180
+ - Things you click yourself open as usual. Only while an agent action runs, CDPM keeps OS windows from appearing:
181
+ - File pickers are intercepted however the action opens them (click, Enter on a file input, form submit), with a hint to use `browser_upload`.
182
+ - `window.print()` would open print preview and freeze the tab (it cannot be closed over CDP), so the page's `print` is disabled for the duration of the action only, reported, and restored right after. Use `browser_pdf` for a PDF.
183
+ - Date, time and color inputs are not clicked (they open a picker); `browser_type` sets their value (`#ff0000` for colors).
184
+ - Browser shortcuts such as `Ctrl+S`/`Ctrl+O`/`Ctrl+P` sent over CDP do not trigger Chrome's save/open/print windows.
185
+ - Known limits: a button whose JavaScript navigates to an external-program scheme (`mailto:` etc.) is not caught in advance (links are); HTTP authentication prompts cannot be filled by an agent.
186
+ - Launch flags are only `--remote-debugging-port`, `--user-data-dir`, `--no-first-run`, `--no-default-browser-check`, `--window-name` (plus `--headless` on request, and `--proxy-server` + `--force-webrtc-ip-handling-policy=disable_non_proxied_udp` only when the user asks for a proxy; headless Chrome still reports `HeadlessChrome`).
187
+ - Never changes window size/position/state, viewport, or zoom; if a click makes the page fullscreen, it is exited immediately.
188
+ - No `Runtime.enable`; helper scripts run in an isolated world.
189
+ - Chrome permission bubbles are browser UI, so they never show up in snapshots or screenshots and page tools can't click them, while the page waits on them. On Windows, CDPM spots them (a small window owned by the slot's Chrome whose title contains a tab's host, so translate or password bubbles are ignored and the Chrome language doesn't matter), warns in the result header, stops `browser_wait` as soon as one appears, and lets Claude press a button with `browser_permission` (UI Automation; works while the window is minimized or covered). Claude asks before allowing camera, microphone or location the user didn't ask for.
190
+ - Dialogs (alert/confirm/prompt/beforeunload) are reported, never handled automatically. Claude reads the message and handles it itself with `browser_dialog` (accept or dismiss); it asks the user only when the dialog would confirm something irreversible the user did not ask for (a payment, a deletion).
191
+ - Refuses: `mailto:`/`tel:`/app-scheme links and addresses in click, navigate, launch start pages and new tabs (would launch other programs), clicking `<select>` (popup), `Ctrl+C/X/V`/`Shift+Insert` (user clipboard). Downloads triggered by navigation are reported with the file name.
192
+
193
+ ## Verification
194
+
195
+ 58 unit and 40 integration tests (`npm test`, `npm run test:integration`, real Chrome on test ports 29222+). Long-running checks (`npm run test:long`, ~20 min): 4,000 rounds on an SPA that replaces its DOM, with a new agent name every round, kept the CDPM server heap within a fixed band (26–39 MB, no upward trend) and the page at 1,421 DOM nodes / 0.8 MB JS heap; 3 sessions sharing one slot for 600 rounds each (1,800 tabs opened and closed, the slot restarted 3 times) stayed at ~20 MB heap per session with no lock files or tabs left behind. A 15-subagent, 30-slot concurrent run confirmed that all 30 windows' position/size/state and all 52 tabs' viewport (`innerWidth×innerHeight`) and zoom were unchanged.
196
+
197
+ ## License
198
+
199
+ MIT
@@ -10,7 +10,7 @@ const AGENT_TOOLS = [
10
10
  'browser_navigate', 'browser_back', 'browser_text', 'browser_snapshot', 'browser_screenshot', 'browser_click', 'browser_type',
11
11
  'browser_fill', 'browser_select', 'browser_press_key', 'browser_scroll', 'browser_wait', 'browser_tabs', 'browser_tab_new',
12
12
  'browser_tab_close', 'browser_eval', 'browser_network', 'browser_network_detail', 'browser_block', 'slot_send', 'slot_inbox',
13
- 'browser_upload', 'browser_forward', 'browser_reload', 'browser_hover', 'browser_drag', 'browser_download_wait', 'browser_pdf', 'browser_dialog',
13
+ 'browser_upload', 'browser_forward', 'browser_reload', 'browser_hover', 'browser_drag', 'browser_download_wait', 'browser_pdf', 'browser_dialog', 'browser_permission',
14
14
  ];
15
15
  function claudeDir() {
16
16
  return process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
@@ -50,7 +50,7 @@ omitClaudeMd: true
50
50
  ${MARK}
51
51
  You own one CDPM browser slot. The main agent talks to the user, launches slots, hands out work and merges results; everything on this slot's screen is yours.
52
52
  Instructions from the main agent are short (slot number, your agent name, the task). Work out the rest from these rules and act right away.
53
- - Report back in the language the main agent/user uses.
53
+ - Report back in the language the main agent/user uses. In the report, name the slot and the tab you worked in (e.g. "slot 1, tab 3 [t7]"), not just the slot.
54
54
  - Pass your slot number and agent name to every CDPM tool. Never touch other slots.
55
55
  - If assigned a specific tab, pass that tab to every tool and leave other tabs alone. If told to use a new tab, open one with browser_tab_new and use its ID. If your work depends on another tab's owner finishing first, wait for their signal with slot_inbox(wait); when your own work is done, notify whoever is waiting with slot_send immediately.
56
56
  - When you need the screen, add read to the action tool to get it in one call (text for content, snapshot when you need things to click, changes to see only what changed).
@@ -62,6 +62,7 @@ Instructions from the main agent are short (slot number, your agent name, the ta
62
62
  - If the user pauses the slot, actions are rejected with a pause notice. Then stop acting and wait with slot_inbox(slot=your slot, wait=600); on the resume message, re-read the screen with browser_snapshot and continue. Never resume on your own.
63
63
  - To see another slot's screen, use read-only tools (browser_snapshot, browser_text) on it directly (no actions).
64
64
  - When a dialog appears, normally read it and accept/dismiss it yourself with browser_dialog. Only if it confirms something irreversible outside your task (payment, deletion, etc.), leave it and report to the main agent.
65
+ - If the header warns about a Chrome permission bubble (browser UI, not in snapshots), the page may be waiting on it: answer it with browser_permission when your task needs it (e.g. a work site reaching a local app). Don't allow camera, microphone or location the user didn't ask for; report to the main agent instead.
65
66
  - Return only your own requested part of the output (report, HTML fragment, table, etc.), briefly. If asked for a file, write it to that path.
66
67
  `;
67
68
  }
@@ -12,7 +12,7 @@ import { claudeMdPath, hasCdpmRules, setupClaudeMd } from './claude-md-setup.js'
12
12
  import { cdpmHome } from './paths.js';
13
13
  import { isStatuslineConfigured, setupStatusline } from './statusline-setup.js';
14
14
  /** 자동 설정 내용이 바뀌면 올린다 (그때 한 번 더 적용). */
15
- export const AUTO_SETUP_VERSION = 14; // 2: cdpm-browser 서브에이전트, 3: 권한 허용 목록, 4: 실시간 협업 규칙, 5: 메인은 켜기만·로그인 자동 감지, 6: 역할 구분, 7: 백그라운드로 한꺼번에·짧은 지시, 8: 켜면서 시작 주소 열기, 9: 서브에이전트 도구 추가(업로드·마우스 올리기 등), 10: 알림창 처리(browser_dialog), 11: 알림창은 웬만하면 직접 처리, 12: browser_wait enabled·response, 13: 멈춤·다시 시작, 14: 헤드리스는 말했을 때만·긴 기다림은 백그라운드·슬롯별 다른 일 예시·한 슬롯 안 탭마다 다른 일도 서브에이전트
15
+ export const AUTO_SETUP_VERSION = 15; // 2: cdpm-browser 서브에이전트, 3: 권한 허용 목록, 4: 실시간 협업 규칙, 5: 메인은 켜기만·로그인 자동 감지, 6: 역할 구분, 7: 백그라운드로 한꺼번에·짧은 지시, 8: 켜면서 시작 주소 열기, 9: 서브에이전트 도구 추가(업로드·마우스 올리기 등), 10: 알림창 처리(browser_dialog), 11: 알림창은 웬만하면 직접 처리, 12: browser_wait enabled·response, 13: 멈춤·다시 시작, 14: 헤드리스는 말했을 때만·긴 기다림은 백그라운드·슬롯별 다른 일 예시·한 슬롯 안 탭마다 다른 일도 서브에이전트, 15: 슬롯과 탭을 함께 말하기·권한 말풍선 처리(browser_permission)
16
16
  export function setupItems() {
17
17
  return [
18
18
  { name: 'statusline', present: () => isStatuslineConfigured(), apply: () => setupStatusline().message },
@@ -0,0 +1,108 @@
1
+ // Windows 전용: Chrome이 띄운 권한 요청 말풍선("○○에서 다음 권한을 요청합니다" 등)을 찾고 버튼을 누른다.
2
+ // 말풍선은 페이지가 아니라 브라우저 화면이라 CDP(스냅샷·스크린샷·클릭)로는 보이지도 눌리지도 않고,
3
+ // 이미 뜬 말풍선은 CDP로 권한을 줘도 닫히지 않는다 (실측). 그래서
4
+ // - 찾기: Chrome 본 창에 딸린 작은 창 중 제목에 탭의 사이트 주소가 들어간 것 (EnumWindows, 1ms 미만).
5
+ // 번역·비밀번호 저장 말풍선은 제목에 주소가 없어서 걸러지고, Chrome 표시 언어와도 상관없다.
6
+ // - 버튼 읽기·누르기: Windows UI Automation (PowerShell, 말풍선이 있을 때만 부른다).
7
+ // 창이 최소화돼 있거나 다른 창에 가려져 있어도 읽고 누를 수 있다 (실측).
8
+ import { execFile } from 'node:child_process';
9
+ import { readRegistry } from '../registry/store.js';
10
+ import { win32 } from '../taskbar/win32.js';
11
+ /** 탭 주소들에서 말풍선 제목과 맞춰 볼 호스트 이름을 뽑는다. */
12
+ export function hostsOf(urls) {
13
+ const hosts = new Set();
14
+ for (const u of urls) {
15
+ try {
16
+ const h = new URL(u).hostname;
17
+ if (h)
18
+ hosts.add(h);
19
+ }
20
+ catch {
21
+ // about:blank 등
22
+ }
23
+ }
24
+ return [...hosts];
25
+ }
26
+ /** 슬롯 Chrome에 떠 있는 권한 요청 말풍선. Windows가 아니거나 창 모드가 아니면 늘 빈 목록. */
27
+ export function permissionBubbles(slot, hosts) {
28
+ const w = win32();
29
+ if (!w || !hosts.length)
30
+ return [];
31
+ const pid = readRegistry().slots[String(slot)]?.pid;
32
+ if (!pid)
33
+ return [];
34
+ try {
35
+ return w.ownedWindowsOf(pid)
36
+ .filter((x) => (x.visible || x.ownerMinimized) && hosts.some((h) => x.title.includes(h)))
37
+ .map((x) => ({ key: x.key, title: x.title, hwnd: x.hwnd }));
38
+ }
39
+ catch {
40
+ return [];
41
+ }
42
+ }
43
+ const UIA_SCRIPT = `
44
+ $OutputEncoding = [Console]::OutputEncoding = [Text.Encoding]::UTF8
45
+ Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes
46
+ $A = [Windows.Automation.AutomationElement]
47
+ $e = $A::FromHandle([IntPtr][long]$env:CDPM_BUBBLE_HWND)
48
+ $type = { param($t) New-Object Windows.Automation.PropertyCondition($A::ControlTypeProperty, $t) }
49
+ $btns = @($e.FindAll('Descendants', (& $type ([Windows.Automation.ControlType]::Button))))
50
+ $texts = @($e.FindAll('Descendants', (& $type ([Windows.Automation.ControlType]::Text))) | ForEach-Object { $_.Current.Name } | Where-Object { $_ })
51
+ $pressed = $null
52
+ if ($env:CDPM_BUBBLE_PRESS) {
53
+ $b = $btns | Where-Object { $_.Current.Name -eq $env:CDPM_BUBBLE_PRESS } | Select-Object -First 1
54
+ if ($b) { $b.GetCurrentPattern([Windows.Automation.InvokePattern]::Pattern).Invoke(); $pressed = $true } else { $pressed = $false }
55
+ }
56
+ @{ texts = @($texts); buttons = @($btns | ForEach-Object { $_.Current.Name } | Where-Object { $_ }); pressed = $pressed } | ConvertTo-Json -Compress
57
+ `;
58
+ const ENCODED = Buffer.from(UIA_SCRIPT, 'utf16le').toString('base64');
59
+ function runUia(b, press) {
60
+ return new Promise((resolve, reject) => {
61
+ execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', ENCODED], {
62
+ env: { ...process.env, CDPM_BUBBLE_HWND: b.key, CDPM_BUBBLE_PRESS: press ?? '' },
63
+ timeout: 15_000, windowsHide: true, encoding: 'utf8',
64
+ }, (err, stdout) => {
65
+ if (err)
66
+ return reject(err);
67
+ try {
68
+ const j = JSON.parse(stdout.trim().split('\n').pop() ?? '');
69
+ const arr = (v) => (Array.isArray(v) ? v : v ? [v] : []).map(String);
70
+ resolve({ texts: arr(j.texts), buttons: arr(j.buttons), pressed: typeof j.pressed === 'boolean' ? j.pressed : null });
71
+ }
72
+ catch (e) {
73
+ reject(e);
74
+ }
75
+ });
76
+ });
77
+ }
78
+ /** 같은 말풍선을 매번 다시 읽지 않게 (말풍선 하나에 PowerShell 한 번, 약 0.6초). */
79
+ const details = new Map();
80
+ export async function bubbleDetail(b) {
81
+ const k = `${b.key}|${b.title}`;
82
+ const hit = details.get(k);
83
+ if (hit)
84
+ return hit;
85
+ try {
86
+ const d = await runUia(b);
87
+ if (details.size > 50)
88
+ details.clear();
89
+ details.set(k, { texts: d.texts, buttons: d.buttons });
90
+ return details.get(k);
91
+ }
92
+ catch {
93
+ return undefined;
94
+ }
95
+ }
96
+ /** 말풍선의 버튼을 이름 그대로 누른다. 없는 이름이면 false. */
97
+ export async function pressBubble(b, button) {
98
+ const r = await runUia(b, button);
99
+ details.delete(`${b.key}|${b.title}`);
100
+ return r.pressed === true;
101
+ }
102
+ /** 머리말·기다리기에 쓰는 한 줄 안내. */
103
+ export function bubbleLine(b, d) {
104
+ const what = d?.texts.filter((t) => t !== b.title).join(' / ');
105
+ const buttons = d?.buttons.length ? ` Buttons: ${d.buttons.join(', ')}.` : '';
106
+ return `Chrome permission bubble open: "${b.title}"${what ? ` (${what})` : ''}.${buttons} ` +
107
+ 'It is browser UI (not in snapshot/screenshot; page tools can\'t click it) and the page may be stuck until it is answered. Press a button with browser_permission.';
108
+ }