cdpm-mcp 0.1.0 → 0.1.1

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/CHANGELOG.md CHANGED
@@ -3,6 +3,15 @@
3
3
  버전 번호는 `package.json`에서 관리해요. 확인: `cdpm --version` (직접 받았으면 `node dist/cli.js --version`).
4
4
  업데이트 방법은 README의 "업데이트" 항목을 보세요.
5
5
 
6
+ ## 0.1.1 (2026-10-11)
7
+
8
+ - `browser_type`·`browser_fill`: 입력한 뒤 실제 값이 넣으려던 글자와 다르면(사이트가 막거나 형식을 바꿈) 제출하지 않고 알려요. 전에는 경고만 붙이고 Enter·제출 버튼을 눌렀어요.
9
+ - `browser_wait response`: 같은 주소의 요청이 여러 개일 때, 앞의 끝나지 않은 요청이 뒤에 끝난 응답을 가리던 문제를 고쳤어요 (끝난 것 중 첫 번째를 돌려줘요).
10
+ - `browser_block`: 그 탭 안의 다른 사이트 iframe(별도 프로세스) 요청에도 같은 규칙이 걸려요. 이미 떠 있는 iframe과 나중에 생기는 iframe 모두요.
11
+ - `browser_tab_new`도 `mailto:` 같은 외부 프로그램 주소는 거절해요.
12
+ - 슬롯 켜기·끄기에 여러 세션 사이 잠금을 넣었어요. 두 세션이 같은 슬롯을 동시에 켜면 Chrome이 두 번 떠서 하나가 실패하던 문제를 고쳤어요.
13
+ - 자동 설정: 넣지 못한 항목이 있으면(설정 파일 형식 오류 등) 그 버전을 끝난 것으로 적지 않고, 다음에 켜질 때 다시 시도해요.
14
+
6
15
  ## 0.1.0 (2026-10-10)
7
16
 
8
17
  첫 공개 버전.
package/README.ko.md CHANGED
@@ -84,7 +84,7 @@ MCP 서버가 처음 켜질 때 한 번, 따로 설정하지 않아도 이렇게
84
84
 
85
85
  한 슬롯(Chrome 하나)을 여러 에이전트가 탭을 나눠 동시에 쓸 수 있어요. 서로 다른 Claude 세션이어도 같아요.
86
86
 
87
- - **탭마다 따로, 동시에**: 조작은 탭마다 줄을 서요. A가 1번 탭에 입력하는 동안 B가 2번 탭을 클릭할 수 있고, 같은 탭에 동시에 온 명령만 차례로 처리해요. 서로 다른 Claude 세션이어도 탭 잠금 파일로 줄을 서서, 두 세션이 한 탭에 동시에 입력해도 글자가 섞이지 않아요 (잠금을 잡은 세션이 죽으면 바로 풀리고, 2분 넘게 안 끝나면 기다리지 않고 알려 줘요). 뒤에 있는 탭도 앞으로 가져오지 않고 조작해요.
87
+ - **탭마다 따로, 동시에**: 조작은 탭마다 줄을 서요. A가 1번 탭에 입력하는 동안 B가 2번 탭을 클릭할 수 있고, 같은 탭에 동시에 온 명령만 차례로 처리해요. 서로 다른 Claude 세션이어도 탭 잠금 파일로 줄을 서서, 두 세션이 한 탭에 동시에 입력해도 글자가 섞이지 않아요 (잠금을 잡은 세션이 죽으면 바로 풀리고, 2분 넘게 안 끝나면 기다리지 않고 알려 줘요). 슬롯 켜기·끄기도 슬롯 잠금으로 줄을 서서, 두 세션이 같은 슬롯을 동시에 켜도 Chrome은 한 번만 뜨고 다른 쪽은 거기에 붙어요. 뒤에 있는 탭도 앞으로 가져오지 않고 조작해요.
88
88
  - **로그인은 같이 써요**: 슬롯 하나는 프로필 하나라서, 한 탭에서 로그인한 사이트는 새 탭에서도 로그인돼 있어요 (탭마다 따로 인증하는 일부 사이트는 예외).
89
89
  - **새 탭은 뒤에서 열려요**: `browser_tab_new`는 사용자가 보는 탭이나 다른 에이전트가 쓰는 탭을 바꾸지 않아요. 연 에이전트는 그 뒤로 자기 탭을 기본으로 써요.
90
90
  - **서로 알아요**: 세션마다 이름이 따로 붙고(`claude-a3f1` 등, 서브에이전트는 자기 이름), 탭마다 연 사람과 마지막 행동이 머리말에 보여요. 남이 방금 쓴 탭을 조작하면 막지 않고 알려 줘요. 같은 계정으로 서로 반대되는 일을 할 때는 `slot_send`로 알리면서 해요.
@@ -146,8 +146,8 @@ MCP 서버가 처음 켜질 때 한 번, 따로 설정하지 않아도 이렇게
146
146
  | `browser_screenshot` | 보이는 화면 PNG (뒤 탭도). 전체 페이지 캡처는 없음 |
147
147
  | `browser_navigate` / `browser_back` | 이동 / 뒤로 (로딩까지 대기, 느린 서버는 오류가 아니라 "아직 로딩 중") |
148
148
  | `browser_click` | ref를 진짜 마우스로 클릭. 가려져 있으면 알려줌, 새 탭이 열리면 알려줌, 폼 검증에 걸리면 이유를 알려줌 |
149
- | `browser_type` | 글자마다 진짜 키 이벤트로 입력 (`clear`, `submit`, `fast`). 입력 후 실제 값 확인. 날짜·시간 칸은 형식 확인 후 값 지정 |
150
- | `browser_fill` | 같은 페이지의 입력칸 여러 개를 차례로 채우고, 원하면 `submit`("Enter" 또는 버튼 ref). 실패·페이지 바뀜·알림창이면 그 자리에서 멈춤 |
149
+ | `browser_type` | 글자마다 진짜 키 이벤트로 입력 (`clear`, `submit`, `fast`). 입력 후 실제 값 확인: 값이 다르면(사이트가 막거나 형식을 바꿈) `submit`이어도 Enter를 누르지 않아요. 날짜·시간 칸은 형식 확인 후 값 지정 |
150
+ | `browser_fill` | 같은 페이지의 입력칸 여러 개를 차례로 채우고, 원하면 `submit`("Enter" 또는 버튼 ref). 실패·페이지 바뀜·알림창, 또는 넣은 값이 다른 칸이 있으면 그 자리에서 멈추고 제출하지 않아요 |
151
151
  | `browser_dialog` | 떠 있는 알림창(alert/confirm/prompt/beforeunload) 확인·취소 (prompt는 `text`로 입력). Claude가 내용을 보고 판단 |
152
152
  | `browser_forward` / `browser_reload` | 앞으로 / 새로고침 (Chrome 새로고침 그대로, `ignore_cache`) |
153
153
  | `browser_hover` | 진짜 마우스를 요소 위에 올리기 (마우스를 올려야 열리는 메뉴) |
@@ -161,7 +161,7 @@ MCP 서버가 처음 켜질 때 한 번, 따로 설정하지 않아도 이렇게
161
161
  | `browser_wait` | 글자(본문·제목)가 나타날 때까지 / `gone`(글자가 사라질 때까지) / `url`(주소가 바뀔 때까지) / `enabled`(버튼·입력칸이 눌릴 수 있게 될 때까지) / `response`(주소가 맞는 네트워크 응답이 다 올 때까지, 응답 본문을 돌려줌: SPA 목록 뒤의 JSON 등. 클릭하는 동안 이미 온 응답도 잡고, 요청을 새로 보내지 않아요) / `network_idle` / N초 |
162
162
  | `browser_eval` | JavaScript 실행 (isolated world: DOM은 보이지만 페이지 전역 변수는 안 보임) |
163
163
  | `browser_network` / `browser_network_detail` | 요청 목록(최근 500개, 30분) / 헤더·보낸 데이터·응답 본문 |
164
- | `browser_block` | 주소 패턴으로 요청 막기·해제 (그 세션이 살아 있는 동안만, 다른 에이전트에게도 표시) |
164
+ | `browser_block` | 탭에서 주소 패턴으로 요청 막기·해제. 그 탭 안의 다른 사이트 iframe에도 걸려요 (이미 떠 있는 것도, 나중에 생기는 것도 첫 요청 전에). 그 세션이 살아 있는 동안만, 다른 에이전트에게도 표시 |
165
165
  | `slot_send` / `slot_inbox` | 에이전트에게 메시지 (받는 쪽 슬롯 번호로, 다른 슬롯 담당에게도) / 받기 (`wait`: 오는 즉시 0.1초 안에 돌아옴, 최대 600초). `browser_wait` 중에 메시지가 오면 기다리기가 바로 멈춰요 |
166
166
  | `slot_pause` / `slot_resume` | 사용자가 "3번 멈춰"라고 할 때 슬롯 멈추기: 조작은 바로 모두 거절되고, 이미 하던 조작도 다음 키·마우스 입력 직전에 멈추고, 기다리기도 바로 끝나요. 화면 읽기는 그대로 돼요. 다시 시작하면 메시지로 에이전트를 바로 깨워서 화면을 다시 읽고 이어 가요. 모든 Claude 세션에 적용 |
167
167
 
@@ -218,7 +218,7 @@ Windows `%LOCALAPPDATA%\cdpm\`, macOS `~/Library/Application Support/cdpm/`, Lin
218
218
  | `registry.json` | 슬롯, 탭, 연 사람·마지막 행동, 요약, 요청 막기 규칙 |
219
219
  | `messages\<슬롯>.jsonl` | 슬롯별 메시지 (1000줄 넘으면 최근 500줄) |
220
220
  | `messages\<슬롯>.cursors.json` | 에이전트별로 어디까지 읽었는지 (최근 200명) |
221
- | `locks\` | 탭 조작 잠금 파일 (여러 Claude 세션이 같은 탭을 동시에 조작하지 않게. 조작이 끝나면 지워지고, 죽은 프로세스가 남긴 것은 1분마다 정리) |
221
+ | `locks\` | 탭 조작·슬롯 켜기/끄기 잠금 파일 (여러 Claude 세션이 같은 탭을 동시에 조작하거나 같은 슬롯을 동시에 켜고 끄지 않게. 조작이 끝나면 지워지고, 죽은 프로세스가 남긴 것은 1분마다 정리) |
222
222
  | `auto-setup.json` | 자동 설정을 어느 버전까지 했는지, 어떤 항목을 넣었는지 (지운 항목을 되살리지 않으려고) |
223
223
  | `profiles\<슬롯>\` | 슬롯별 Chrome 프로필 |
224
224
  | `icons\<슬롯>.ico` | 작업표시줄 아이콘 |
@@ -231,12 +231,12 @@ Windows `%LOCALAPPDATA%\cdpm\`, macOS `~/Library/Application Support/cdpm/`, Lin
231
231
  - 창 크기·위치·상태, 뷰포트, 확대 비율을 바꾸지 않아요. 페이지가 클릭 때문에 전체 화면이 되면 바로 해제해요.
232
232
  - `Runtime.enable`을 쓰지 않고, 판단용 스크립트는 전부 isolated world에서 실행해요.
233
233
  - 알림창(alert/confirm/prompt/beforeunload)을 정해진 규칙으로 자동 처리하지 않아요. 떠 있으면 알리고, Claude가 내용을 보고 `browser_dialog`로 직접 확인·취소해요. 사용자가 시키지 않은 되돌릴 수 없는 일(결제·삭제 등)을 확정하는 창일 때만 먼저 물어봐요.
234
- - 거부하는 동작: `mailto:`·`tel:`·앱 전용 주소 클릭/이동(다른 프로그램 실행), `<select>` 클릭(목록 창), `Ctrl+C/X/V`·`Shift+Insert`(사용자 클립보드)
234
+ - 거부하는 동작: `mailto:`·`tel:`·앱 전용 주소로 클릭·이동·켜면서 열기·새 탭 열기(다른 프로그램 실행), `<select>` 클릭(목록 창), `Ctrl+C/X/V`·`Shift+Insert`(사용자 클립보드)
235
235
  - 파일 응답으로 이동해서 다운로드가 시작되면 파일 이름과 함께 알려줘요 (Chrome 기본 다운로드 폴더에 저장돼요).
236
236
 
237
237
  ## 검증
238
238
 
239
- - 단위 테스트 56개, 통합 테스트 33개 (`npm test`, `npm run test:integration` — 테스트 포트 29222~로 진짜 Chrome 사용)
239
+ - 단위 테스트 57개, 통합 테스트 38개 (`npm test`, `npm run test:integration` — 테스트 포트 29222~로 진짜 Chrome 사용)
240
240
  - 오래 켜 두기 시험 (`npm run test:long`, 약 20분): 화면을 계속 새로 그리는 SPA에서 반복마다 새 에이전트 이름으로 4,000회 → CDPM 서버 힙은 일정한 범위(26~39MB) 안에서만 오르내리고 계속 늘지 않음, 페이지는 요소 1,421개·JS 힙 0.8MB 그대로. 세션 3개가 한 슬롯을 600회씩 동시에 사용(탭 1,800개 열고 닫기, 중간에 슬롯 3번 재시작) → 세션마다 힙 약 20MB 그대로, 남은 잠금 파일·탭 없음.
241
241
  - 서브에이전트 15명이 슬롯 30개를 동시에 쓰는 실사용 테스트: 테스트 전후로 창 30개 위치·크기·상태, 탭 52개 뷰포트(`innerWidth×innerHeight`), 확대 비율이 모두 그대로임을 확인
242
242
 
package/README.md CHANGED
@@ -76,7 +76,7 @@ Each result starts with a header: the slot's tabs (`>` = acted on now, `·앞` =
76
76
 
77
77
  **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.
78
78
 
79
- **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. 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.
79
+ **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.
80
80
 
81
81
  **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.
82
82
 
@@ -97,8 +97,8 @@ All tools take `slot` (1–30) and `agent` (display name). Action tools also tak
97
97
  | `browser_screenshot` | Visible area as PNG, background tabs included; no full-page capture |
98
98
  | `browser_navigate` / `browser_back` | Waits for load; slow servers are reported as "still loading", not as errors |
99
99
  | `browser_click` | Real mouse click; reports covering elements, new tabs, form-validation failures |
100
- | `browser_type` | Real key events per character (`clear`, `submit`, `fast`); verifies the value; date/time inputs are set after format validation |
101
- | `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 or dialog |
100
+ | `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 |
101
+ | `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) |
102
102
  | `browser_dialog` | Accept or dismiss an open alert/confirm/prompt/beforeunload (`text` for prompt). Claude decides from the message |
103
103
  | `browser_forward` / `browser_reload` | Forward / reload (Chrome's own reload, `ignore_cache`) |
104
104
  | `browser_hover` | Real mouse over an element (hover-only menus) |
@@ -112,7 +112,7 @@ All tools take `slot` (1–30) and `agent` (display name). Action tools also tak
112
112
  | `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 |
113
113
  | `browser_eval` | JavaScript in an isolated world (DOM visible, page globals not) |
114
114
  | `browser_network` / `browser_network_detail` | Requests (last 500, 30 min) / headers, post data, body |
115
- | `browser_block` | Block/unblock URL patterns (while the session lives; visible to other agents) |
115
+ | `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 |
116
116
  | `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 |
117
117
  | `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 |
118
118
 
@@ -140,7 +140,7 @@ cdpm status | statusline
140
140
  cdpm statusline-setup turn on the slot display in Claude Code's status line (backs up settings)
141
141
  ```
142
142
 
143
- 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 lock files so Claude sessions never drive one tab 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`).
143
+ 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`).
144
144
 
145
145
  ## macOS
146
146
 
@@ -157,11 +157,11 @@ Data lives in `%LOCALAPPDATA%\cdpm\` on Windows `~/Library/Application Support/c
157
157
  - Never changes window size/position/state, viewport, or zoom; if a click makes the page fullscreen, it is exited immediately.
158
158
  - No `Runtime.enable`; helper scripts run in an isolated world.
159
159
  - 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).
160
- - Refuses: `mailto:`/`tel:`/app-scheme links (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.
160
+ - 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.
161
161
 
162
162
  ## Verification
163
163
 
164
- 56 unit and 33 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.
164
+ 57 unit and 38 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.
165
165
 
166
166
  ## License
167
167
 
@@ -68,6 +68,7 @@ export function runAutoSetup(items, file = stateFile(), version = AUTO_SETUP_VER
68
68
  if (state.version >= version)
69
69
  return [];
70
70
  const out = [];
71
+ let failed = false;
71
72
  for (const item of items) {
72
73
  try {
73
74
  // 전에 넣었는데 지금 없으면 사용자가 지운 것 → 되살리지 않는다
@@ -76,12 +77,16 @@ export function runAutoSetup(items, file = stateFile(), version = AUTO_SETUP_VER
76
77
  out.push(item.apply());
77
78
  if (item.present())
78
79
  state.applied[item.name] = true;
80
+ else
81
+ failed = true; // 넣으려 했는데 안 들어감 (설정 파일 형식 오류 등) → 다음에 다시
79
82
  }
80
83
  catch {
81
- // 이 항목은 다음 기회에
84
+ failed = true; // 이 항목은 다음에 켜질 때 다시
82
85
  }
83
86
  }
84
- state.version = version;
87
+ // 실패한 항목이 있으면 이 버전을 끝난 것으로 적지 않는다 (들어간 항목 기록은 남겨서, 그 뒤 지우면 되살리지 않음)
88
+ if (!failed)
89
+ state.version = version;
85
90
  writeState(state, file);
86
91
  return out;
87
92
  }
@@ -7,6 +7,8 @@ export class CdpConnection {
7
7
  nextId = 1;
8
8
  pending = new Map();
9
9
  handlers = new Map();
10
+ /** 이 연결에 자동으로 붙은 하위 대상(sessionId가 붙은 메시지)의 이벤트. 탭 자신의 이벤트와 섞지 않는다 */
11
+ sessionHandlers = new Map();
10
12
  closedHandlers = new Set();
11
13
  closed = false;
12
14
  constructor(ws) {
@@ -32,7 +34,7 @@ export class CdpConnection {
32
34
  }, { once: true });
33
35
  });
34
36
  }
35
- send(method, params = {}, timeoutMs = 30_000) {
37
+ send(method, params = {}, timeoutMs = 30_000, sessionId) {
36
38
  if (this.closed)
37
39
  return Promise.reject(new CdpmError(`CDP 연결이 끊어졌습니다 (${method}).`));
38
40
  const id = this.nextId++;
@@ -43,7 +45,7 @@ export class CdpConnection {
43
45
  '페이지가 무겁거나, 네트워크가 느리거나, 알림창이 떠 있을 수 있어요. 잠시 뒤 다시 시도하거나 browser_tabs로 상태를 확인하세요.'));
44
46
  }, timeoutMs);
45
47
  this.pending.set(id, { resolve, reject, timer, method });
46
- this.ws.send(JSON.stringify({ id, method, params }));
48
+ this.ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
47
49
  });
48
50
  }
49
51
  on(event, handler) {
@@ -53,6 +55,14 @@ export class CdpConnection {
53
55
  set.add(handler);
54
56
  return () => set.delete(handler);
55
57
  }
58
+ /** 하위 대상(자동으로 붙은 iframe 등)의 이벤트만 받는다. */
59
+ onSession(event, handler) {
60
+ let set = this.sessionHandlers.get(event);
61
+ if (!set)
62
+ this.sessionHandlers.set(event, (set = new Set()));
63
+ set.add(handler);
64
+ return () => set.delete(handler);
65
+ }
56
66
  onClosed(handler) {
57
67
  this.closedHandlers.add(handler);
58
68
  }
@@ -101,6 +111,17 @@ export class CdpConnection {
101
111
  p.resolve(msg.result);
102
112
  return;
103
113
  }
114
+ if (msg.method && msg.sessionId) {
115
+ for (const h of this.sessionHandlers.get(msg.method) ?? []) {
116
+ try {
117
+ h(msg.params, msg.sessionId);
118
+ }
119
+ catch {
120
+ // 핸들러 오류는 연결에 영향 주지 않음
121
+ }
122
+ }
123
+ return;
124
+ }
104
125
  if (msg.method) {
105
126
  for (const h of this.handlers.get(msg.method) ?? []) {
106
127
  try {
@@ -10,6 +10,8 @@ export class NetworkRecorder {
10
10
  /** 아직 끝나지 않은 요청 */
11
11
  inflight = new Set();
12
12
  rules = [];
13
+ /** 규칙이 있는 동안 자동으로 붙은 하위 대상(다른 사이트 iframe 등). 같은 규칙을 건다 */
14
+ children = new Set();
13
15
  constructor(conn) {
14
16
  this.conn = conn;
15
17
  conn.on('Network.requestWillBeSent', (p) => {
@@ -60,17 +62,41 @@ export class NetworkRecorder {
60
62
  e.failed = p.blockedReason ? `${p.errorText} (${p.blockedReason})` : p.errorText;
61
63
  e.durationMs = this.elapsed(e, p.timestamp);
62
64
  });
63
- conn.on('Fetch.requestPaused', (p) => {
64
- // Fetch 패턴에 걸린 요청 = 막을 요청
65
- const rule = this.rules.find((r) => wildcard(r.pattern).test(p.request.url));
66
- const e = p.networkId ? this.byId.get(p.networkId) : undefined;
67
- if (e && rule)
68
- e.blockedBy = rule.pattern;
69
- if (rule)
70
- void conn.send('Fetch.failRequest', { requestId: p.requestId, errorReason: 'BlockedByClient' }).catch(() => undefined);
71
- else
72
- void conn.send('Fetch.continueRequest', { requestId: p.requestId }).catch(() => undefined);
73
- });
65
+ conn.on('Fetch.requestPaused', (p) => this.onPaused(p));
66
+ // 다른 사이트 iframe은 Chrome에서 별도 대상이라 탭에 건 Fetch가 닿지 않는다.
67
+ // 규칙이 있는 동안에는 자동으로 붙어서(요청을 보내기 전에 멈춘 채로) 같은 규칙을 건다. 그 안의 iframe도 같은 방식으로.
68
+ const attached = (p) => void this.onChild(p.sessionId);
69
+ conn.on('Target.attachedToTarget', attached);
70
+ conn.onSession('Target.attachedToTarget', attached);
71
+ conn.onSession('Fetch.requestPaused', (p, sid) => this.onPaused(p, sid));
72
+ const detached = (p) => this.children.delete(p.sessionId);
73
+ conn.on('Target.detachedFromTarget', detached);
74
+ conn.onSession('Target.detachedFromTarget', detached);
75
+ }
76
+ onPaused(p, sessionId) {
77
+ // Fetch 패턴에 걸린 요청 = 막을 요청
78
+ const rule = this.rules.find((r) => wildcard(r.pattern).test(p.request.url));
79
+ const e = !sessionId && p.networkId ? this.byId.get(p.networkId) : undefined;
80
+ if (e && rule)
81
+ e.blockedBy = rule.pattern;
82
+ if (rule)
83
+ void this.conn.send('Fetch.failRequest', { requestId: p.requestId, errorReason: 'BlockedByClient' }, 5000, sessionId).catch(() => undefined);
84
+ else
85
+ void this.conn.send('Fetch.continueRequest', { requestId: p.requestId }, 5000, sessionId).catch(() => undefined);
86
+ }
87
+ fetchPatterns() {
88
+ return { patterns: this.rules.map((r) => ({ urlPattern: r.pattern, requestStage: 'Request' })) };
89
+ }
90
+ /** 자동으로 붙은 하위 대상: 규칙을 걸고, 그 안의 iframe에도 붙게 한 뒤, 멈춰 있던 대상을 풀어 준다. */
91
+ async onChild(sessionId) {
92
+ this.children.add(sessionId);
93
+ const send = (m, p = {}) => this.conn.send(m, p, 5000, sessionId).catch(() => undefined);
94
+ if (this.rules.length) {
95
+ await send('Network.setCacheDisabled', { cacheDisabled: true });
96
+ await send('Fetch.enable', this.fetchPatterns());
97
+ await send('Target.setAutoAttach', { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });
98
+ }
99
+ await send('Runtime.runIfWaitingForDebugger');
74
100
  }
75
101
  elapsed(e, monoSec) {
76
102
  if (this.wallOffset === undefined)
@@ -104,11 +130,19 @@ export class NetworkRecorder {
104
130
  await this.conn.send('Network.setCacheDisabled', { cacheDisabled: rules.length > 0 }, 5000).catch(() => undefined);
105
131
  if (!rules.length) {
106
132
  await this.conn.send('Fetch.disable', {}, 5000).catch(() => undefined);
133
+ // 하위 대상의 규칙도 풀고 자동으로 붙기를 멈춘다
134
+ for (const sid of this.children) {
135
+ await this.conn.send('Fetch.disable', {}, 5000, sid).catch(() => undefined);
136
+ await this.conn.send('Network.setCacheDisabled', { cacheDisabled: false }, 5000, sid).catch(() => undefined);
137
+ }
138
+ await this.conn.send('Target.setAutoAttach', { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, 5000).catch(() => undefined);
107
139
  return;
108
140
  }
109
- await this.conn.send('Fetch.enable', {
110
- patterns: rules.map((r) => ({ urlPattern: r.pattern, requestStage: 'Request' })),
111
- }, 5000);
141
+ await this.conn.send('Fetch.enable', this.fetchPatterns(), 5000);
142
+ // 이미 붙어 있는 하위 대상은 새 규칙으로 바꾸고, 아직이면 붙는다 (이미 떠 있는 iframe도 이때 붙음)
143
+ for (const sid of this.children)
144
+ await this.conn.send('Fetch.enable', this.fetchPatterns(), 5000, sid).catch(() => undefined);
145
+ await this.conn.send('Target.setAutoAttach', { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }, 5000).catch(() => undefined);
112
146
  }
113
147
  }
114
148
  /** Fetch 패턴과 같은 규칙: * 는 아무 글자 여러 개, ? 는 한 글자. */
package/dist/cli.js CHANGED
@@ -44,6 +44,10 @@ function slotsFrom(args) {
44
44
  });
45
45
  }
46
46
  async function closeSlot(slot) {
47
+ const { withSlotLock } = await import('./registry/lock.js');
48
+ return withSlotLock(slot, () => closeSlotLocked(slot));
49
+ }
50
+ async function closeSlotLocked(slot) {
47
51
  const { probe } = await lazy.targets();
48
52
  const { browserConnection } = await lazy.sessions();
49
53
  const { forgetSlot } = await lazy.service();
@@ -26,6 +26,8 @@ export const DIALOG_NOTE = '내용을 보고 판단해서 browser_dialog로 직
26
26
  /** 행동 도중 페이지가 알림창을 띄움. 행동 자체는 이루어진 것이므로 오류가 아니라 결과로 알린다. */
27
27
  export class DialogInterrupt extends CdpmError {
28
28
  }
29
+ /** 입력한 뒤 실제 값이 넣으려던 글자와 다를 때 결과에 붙는 표시 (이때는 제출하지 않는다) */
30
+ export const VALUE_MISMATCH = '[주의] 입력한 뒤 값이 예상과 달라요';
29
31
  /** 사용자가 슬롯을 멈춤: 하던 조작을 다음 입력을 보내기 직전에 그만둔다. */
30
32
  export class PausedInterrupt extends CdpmError {
31
33
  }
@@ -543,17 +545,21 @@ export async function type(s, agent, ref, text, clear, submit, fast = false) {
543
545
  if (info.editable !== 'none' && text) {
544
546
  const now = await callOn(fs, obj, `function () { return ('value' in this && typeof this.value === 'string') ? this.value : (this.innerText || ''); }`);
545
547
  if (!now.includes(text))
546
- warn = `\n[주의] 입력한 뒤 값이 예상과 달라요 (현재 값: ${JSON.stringify(now.slice(0, 100))}). 사이트가 입력을 막거나 형식을 바꿨을 수 있어요.`;
548
+ warn = `\n${VALUE_MISMATCH} (현재 값: ${JSON.stringify(now.slice(0, 100))}). 사이트가 입력을 막거나 형식을 바꿨을 수 있어요.`;
547
549
  }
548
550
  else if (info.editable === 'none') {
549
551
  warn = `\n[주의] [${ref}]는 입력칸이 아니라서(${info.tag}) 포커스된 곳에 글자를 보냈어요. 결과를 스냅샷으로 확인하세요.`;
550
552
  }
551
553
  let note = '';
552
554
  const human = await humanFocusNote(s);
553
- if (submit)
555
+ // 값이 다르면 잘못된 내용이 제출될 수 있으므로 Enter를 누르지 않는다
556
+ const mismatch = warn.includes(VALUE_MISMATCH);
557
+ if (submit && mismatch)
558
+ note = '\n값이 달라서 제출(Enter)은 하지 않았어요. 값을 확인한 뒤 다시 입력하거나 browser_press_key로 제출하세요.';
559
+ else if (submit)
554
560
  note = await settleAfter(s, () => pressCombo(s, parseCombo('Enter')));
555
561
  warn += human;
556
- return `입력했어요: [${ref}] ${JSON.stringify(text)}${clear ? ' (기존 내용 지움)' : ''}${fast ? ' (빠른 입력: 키 이벤트 없이 한 번에)' : ''}${submit ? ' + Enter' : ''}${warn}${note}`;
562
+ return `입력했어요: [${ref}] ${JSON.stringify(text)}${clear ? ' (기존 내용 지움)' : ''}${fast ? ' (빠른 입력: 키 이벤트 없이 한 번에)' : ''}${submit && !mismatch ? ' + Enter' : ''}${warn}${note}`;
557
563
  }
558
564
  finally {
559
565
  await release(fs);
@@ -914,8 +920,9 @@ export async function waitForResponse(s, pattern, since, timeoutSec, stop) {
914
920
  const why = stop?.();
915
921
  if (why)
916
922
  throw new WaitStopped(why);
917
- const hit = s.network.list().find((e) => e.startedAt >= since && !e.blockedBy && matches(e.url) && e.type !== 'Preflight');
918
- if (hit && (hit.failed || (hit.status !== undefined && !s.network.inflight.has(hit.requestId))))
923
+ const finished = (e) => !!e.failed || (e.status !== undefined && !s.network.inflight.has(e.requestId));
924
+ const hit = s.network.list().find((e) => e.startedAt >= since && !e.blockedBy && e.type !== 'Preflight' && matches(e.url) && finished(e));
925
+ if (hit)
919
926
  return hit;
920
927
  await sleep(50);
921
928
  }
package/dist/paths.js CHANGED
@@ -18,6 +18,8 @@ export const paths = {
18
18
  profile: (slot) => path.join(cdpmHome(), 'profiles', String(slot)),
19
19
  icon: (slot) => path.join(cdpmHome(), 'icons', `${slot}.ico`),
20
20
  config: () => path.join(cdpmHome(), 'config.json'),
21
+ /** 슬롯 켜기·끄기 잠금 (여러 Claude 세션이 같은 슬롯을 동시에 켜거나 끄지 않게) */
22
+ slotLock: (slot) => path.join(cdpmHome(), 'locks', `slot-${slot}.lock`),
21
23
  /** 탭 조작 잠금 (여러 Claude 세션이 같은 탭을 동시에 조작하지 않게) */
22
24
  tabLock: (slot, targetId) => path.join(cdpmHome(), 'locks', `${slot}-${targetId.replace(/[^A-Za-z0-9]/g, '')}.lock`),
23
25
  };
@@ -15,6 +15,10 @@ export class LockTimeoutError extends Error {
15
15
  export async function withLock(fn, timeoutMs = 10_000) {
16
16
  return withFileLock(paths.lock(), fn, timeoutMs, '저장소 잠금을 얻지 못했어요 (다른 프로세스가 오래 쓰는 중).');
17
17
  }
18
+ /** 슬롯 켜기·끄기를 여러 Claude 세션 사이에서 하나씩 (동시에 켜면 Chrome이 두 번 떠서 하나가 실패함). */
19
+ export function withSlotLock(slot, fn) {
20
+ return withFileLock(paths.slotLock(slot), fn, 90_000, `다른 Claude 세션이 ${slot}번을 켜거나 끄는 중이에요. 잠시 뒤 다시 하세요.`);
21
+ }
18
22
  /** 같은 방식의 잠금을 원하는 파일로 (예: 탭 하나를 여러 Claude 세션이 동시에 조작하지 않게). */
19
23
  export async function withFileLock(lockPath, fn, timeoutMs, timeoutMessage) {
20
24
  fs.mkdirSync(path.dirname(lockPath), { recursive: true });
package/dist/service.js CHANGED
@@ -4,6 +4,7 @@ import { describeProxy } from './chrome/proxy.js';
4
4
  import { browserConnection, dropSlotConnections, hasLiveBrowserConnection, pageSession } from './cdp/sessions.js';
5
5
  import { listPages, probe } from './cdp/targets.js';
6
6
  import { CdpmError } from './errors.js';
7
+ import { withSlotLock } from './registry/lock.js';
7
8
  import { newSlotRecord, readRegistry, updateRegistry } from './registry/store.js';
8
9
  import { MAX_SLOT, portOf } from './slots.js';
9
10
  import { applyDock, DOCK_SUPPORTED } from './taskbar/dock.js';
@@ -74,7 +75,11 @@ function portBusy(slot, detail) {
74
75
  return new CdpmError(`${slot}번 슬롯의 포트 ${portOf(slot)}를 Chrome이 아닌 프로그램이 사용 중입니다 (${detail}). 그 프로그램을 종료하거나 다른 슬롯을 쓰세요.`);
75
76
  }
76
77
  /** 사용자가 켜라고 했을 때만 부른다. 이미 떠 있으면 붙기만 한다. */
77
- export async function launchSlot(slot, agent, opts = {}) {
78
+ export function launchSlot(slot, agent, opts = {}) {
79
+ // 여러 세션이 같은 슬롯을 동시에 켜면 둘 다 "비어 있음"으로 보고 Chrome을 두 번 띄운다 → 슬롯 잠금 안에서 하나씩
80
+ return withSlotLock(slot, () => launchSlotLocked(slot, agent, opts));
81
+ }
82
+ async function launchSlotLocked(slot, agent, opts) {
78
83
  const p = await probeSure(slot);
79
84
  if (p.state === 'other')
80
85
  throw portBusy(slot, p.detail);
@@ -7,6 +7,7 @@ import { ensureDownloadTracking, waitDownload } from '../cdp/downloads.js';
7
7
  import { probe } from '../cdp/targets.js';
8
8
  import { describeProxy, parseProxy } from '../chrome/proxy.js';
9
9
  import { CdpmError } from '../errors.js';
10
+ import { withSlotLock } from '../registry/lock.js';
10
11
  import { pausedInfo, pausedRefusal, pauseSlots, resumeSlots } from '../pause.js';
11
12
  import * as act from '../page/actions.js';
12
13
  import { ancestorsOf, findLines, paginate, subtree, takeSnapshot } from '../page/snapshot.js';
@@ -378,7 +379,7 @@ export function registerTools(server) {
378
379
  title: '슬롯 종료',
379
380
  description: '슬롯 Chrome을 정상 종료한다 (세션·쿠키 저장). 프로필(로그인 정보)은 지우지 않는다. 다른 에이전트가 최근에 썼으면 결과에 알려준다.',
380
381
  inputSchema: { slot: slotArg, agent: agentArg },
381
- }, async ({ slot, agent }) => guard(async () => {
382
+ }, async ({ slot, agent }) => guard(() => withSlotLock(slot, async () => {
382
383
  const me = agent ?? DEFAULT_AGENT;
383
384
  if ((await probe(slot)).state !== 'chrome') {
384
385
  await forgetSlot(slot);
@@ -399,7 +400,7 @@ export function registerTools(server) {
399
400
  await sleep(100);
400
401
  await forgetSlot(slot);
401
402
  return textResult([...warnings, `${slot}번 Chrome을 종료했어요. 프로필은 남아 있어서 다음에 켜면 로그인이 유지돼요.`].join('\n'));
402
- }));
403
+ })));
403
404
  server.registerTool('browser_tabs', {
404
405
  title: '탭 목록',
405
406
  description: '슬롯의 탭 목록: 번호, ID, 제목, 주소, 연 사람, 마지막 행동, 탭별 요약(summary를 넣은 행동만 갱신). "·앞"은 그 창에서 지금 화면 앞에 보이는 탭 (창이 여러 개면 창마다 하나).',
@@ -425,6 +426,9 @@ export function registerTools(server) {
425
426
  await attachSlot(slot);
426
427
  const browser = await browserConnection(slot);
427
428
  const target = url ? (/^[a-z][a-z0-9+.-]*:/i.test(url) ? url : `https://${url}`) : 'about:blank';
429
+ const ext = act.externalScheme(target);
430
+ if (ext)
431
+ throw new CdpmError(`${ext} 주소(${target.slice(0, 80)})는 열 수 없어요 (사용자 PC의 다른 프로그램이 실행돼요).`);
428
432
  // background: 사용자가 보고 있는 탭을 바꾸지 않는다.
429
433
  const { targetId } = await browser.send('Target.createTarget', { url: target, background: true });
430
434
  markCreated(targetId, me);
@@ -627,7 +631,10 @@ export function registerTools(server) {
627
631
  if (i > 0 && (await href()) !== start)
628
632
  return stop(`페이지가 바뀌어서 ${i + 1}번째 칸 [${f.ref}]부터는 채우지 않았어요.`);
629
633
  try {
630
- done.push(`${i + 1}. ${await act.type(s, agent, f.ref, f.text, true, false)}`);
634
+ const r = await act.type(s, agent, f.ref, f.text, true, false);
635
+ done.push(`${i + 1}. ${r}`);
636
+ if (r.includes(act.VALUE_MISMATCH))
637
+ return stop(`${i + 1}번째 칸 [${f.ref}]의 값이 넣으려던 글자와 달라서 멈췄어요 (제출하지 않았어요). 값을 확인한 뒤 다시 하세요.`);
631
638
  }
632
639
  catch (e) {
633
640
  if (e instanceof act.DialogInterrupt)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cdpm-mcp",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "CDP Manager - an MCP server that runs Chrome slots 1-30 over CDP so multiple Claude agents can share and drive them by number",
5
5
  "type": "module",
6
6
  "bin": {