cdpm-mcp 0.1.4 → 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/CHANGELOG.md +18 -0
- package/README.ko.md +276 -273
- package/README.md +199 -196
- package/dist/agent-setup.js +18 -15
- package/dist/auto-setup.js +1 -1
- package/dist/cdp/client.js +7 -7
- package/dist/cdp/downloads.js +4 -4
- package/dist/cdp/sessions.js +7 -7
- package/dist/cdp/targets.js +1 -1
- package/dist/chrome/bubbles.js +108 -0
- package/dist/chrome/finder.js +2 -2
- package/dist/chrome/launcher.js +5 -5
- package/dist/chrome/proxy.js +4 -4
- package/dist/claude-md-setup.js +20 -16
- package/dist/cli.js +1 -1
- package/dist/orphan.js +3 -3
- package/dist/page/actions.js +105 -105
- package/dist/page/snapshot.js +1 -1
- package/dist/pause.js +10 -11
- package/dist/proxy-forwarder.js +8 -8
- package/dist/registry/lock.js +2 -2
- package/dist/service.js +13 -13
- package/dist/slots.js +1 -1
- package/dist/statusline.js +27 -11
- package/dist/taskbar/win32.js +29 -0
- package/dist/tools/format.js +12 -12
- package/dist/tools/read.js +10 -10
- package/dist/tools/register.js +362 -298
- package/dist/util.js +5 -5
- package/package.json +64 -64
package/dist/tools/register.js
CHANGED
|
@@ -5,6 +5,7 @@ import { wildcard } from '../cdp/network.js';
|
|
|
5
5
|
import { browserConnection, forgetSlotVisibility, knownDialog, onAgentForgotten, pageSession, touchAgent } from '../cdp/sessions.js';
|
|
6
6
|
import { ensureDownloadTracking, waitDownload } from '../cdp/downloads.js';
|
|
7
7
|
import { probe } from '../cdp/targets.js';
|
|
8
|
+
import { bubbleDetail, bubbleLine, hostsOf, permissionBubbles, pressBubble } from '../chrome/bubbles.js';
|
|
8
9
|
import { describeProxy, parseProxy } from '../chrome/proxy.js';
|
|
9
10
|
import { isClaudeCode } from '../client-info.js';
|
|
10
11
|
import { CdpmError } from '../errors.js';
|
|
@@ -16,7 +17,7 @@ import { hasUnread, recentDelivered, sendMessage, takeUnread, waitUnread } from
|
|
|
16
17
|
import { readRegistry, updateRegistry } from '../registry/store.js';
|
|
17
18
|
import { attachSlot, forgetSlot, freeSlots, launchSlot, liveSlots, markCreated, ownershipWarnings, pickTab, recordAction, syncTabs, } from '../service.js';
|
|
18
19
|
import { MAX_SLOT, MIN_SLOT, PORT_BASE, portOf } from '../slots.js';
|
|
19
|
-
import { ago, decodeUrl,
|
|
20
|
+
import { ago, decodeUrl, nowIso, pidAlive, secondsSince, shortUrl, sleep, truncate } from '../util.js';
|
|
20
21
|
import { formatHeader, formatMessages, formatSlotStatus } from './format.js';
|
|
21
22
|
import { readAfter } from './read.js';
|
|
22
23
|
/** 에이전트가 마지막으로 다룬 탭 (보기 도구에서 tab을 생략했을 때 우선). key: `${slot}:${agent}` */
|
|
@@ -38,36 +39,36 @@ function multiSlotRefusal(agent, slot, allowed) {
|
|
|
38
39
|
const others = [...m.keys()].filter((k) => k !== slot).sort((x, y) => x - y);
|
|
39
40
|
if (others.length && !allowed) {
|
|
40
41
|
const how = isClaudeCode()
|
|
41
|
-
?
|
|
42
|
-
|
|
43
|
-
:
|
|
44
|
-
return
|
|
45
|
-
|
|
42
|
+
? `For different jobs per slot, call the Agent tool once per slot in a single message to launch subagents (subagent_type "cdpm-browser") together, ` +
|
|
43
|
+
`each using its own slot and agent name (e.g. "slot${slot}-agent"). Each subagent writes its own share of the output (report, HTML fragment, etc.); main only merges. `
|
|
44
|
+
: `For different jobs per slot, give each slot its own subagent if available; otherwise use a distinct agent name per slot (e.g. "slot${slot}-agent"). `;
|
|
45
|
+
return `Refused: ${agent} just used slot ${others.join(', ')}, so it won't take slot ${slot}. ` + how +
|
|
46
|
+
`If one agent must handle several slots together (e.g. comparing), call again with multiSlot: true.`;
|
|
46
47
|
}
|
|
47
48
|
m.set(slot, now);
|
|
48
49
|
recentSlots.set(agent, m);
|
|
49
50
|
return undefined;
|
|
50
51
|
}
|
|
51
52
|
export const DEFAULT_AGENT = `claude-${randomBytes(2).toString('hex')}`;
|
|
52
|
-
const SLOT_RANGE =
|
|
53
|
-
const slotArg = z.number({ error: (iss) => (iss.input === undefined ? `slot
|
|
54
|
-
.describe(
|
|
53
|
+
const SLOT_RANGE = `slot must be a number ${MIN_SLOT}-${MAX_SLOT}`;
|
|
54
|
+
const slotArg = z.number({ error: (iss) => (iss.input === undefined ? `slot is required (number ${MIN_SLOT}-${MAX_SLOT})` : SLOT_RANGE) }).int(SLOT_RANGE).min(MIN_SLOT, SLOT_RANGE).max(MAX_SLOT, SLOT_RANGE)
|
|
55
|
+
.describe(`Browser slot ${MIN_SLOT}-${MAX_SLOT}. "3", "slot 3", "browser 3" → 3. If the user gives a port like ${PORT_BASE + 3}, subtract ${PORT_BASE}.`);
|
|
55
56
|
const agentArg = z.string().min(1).max(40).optional()
|
|
56
|
-
.describe(
|
|
57
|
+
.describe(`Your display name, shown to other agents. Subagents must always set it. Default "${DEFAULT_AGENT}".`);
|
|
57
58
|
const tabArg = z.union([z.string(), z.number()]).optional()
|
|
58
|
-
.describe('
|
|
59
|
+
.describe('Target tab: number (1, 2…) or ID ("t7"). Use the stable ID when agents share a slot. Required for action tools when there are multiple tabs.');
|
|
59
60
|
const summaryArg = z.string().max(120).optional()
|
|
60
|
-
.describe('
|
|
61
|
+
.describe('One-line note of what you are doing (e.g. "comparing laptop prices"). Shown in browser_status (not the status line). Omit to keep the previous one.');
|
|
61
62
|
const multiSlotArg = z.boolean().optional()
|
|
62
|
-
.describe('
|
|
63
|
+
.describe('true only when one agent must handle several slots together (e.g. comparing). Normally omit (one agent = one slot; use subagents for the rest)');
|
|
63
64
|
const readArg = z.enum(['text', 'snapshot', 'changes']).optional()
|
|
64
|
-
.describe('
|
|
65
|
-
const pageArg = z.number().int().min(1).optional().describe('
|
|
65
|
+
.describe('Append the page after the action (no separate read needed): text=body text, snapshot=snapshot page 1 (with refs), changes=only lines added/removed since your last snapshot (shortest; full page if the page changed)');
|
|
66
|
+
const pageArg = z.number().int().min(1).optional().describe('Page number for long output (default 1)');
|
|
66
67
|
const textResult = (text, isError = false) => ({ content: [{ type: 'text', text }], ...(isError ? { isError } : {}) });
|
|
67
68
|
function errorText(e) {
|
|
68
69
|
if (e instanceof CdpmError)
|
|
69
70
|
return e.message;
|
|
70
|
-
return
|
|
71
|
+
return `Error: ${e?.message ?? String(e)}`;
|
|
71
72
|
}
|
|
72
73
|
/** 탭에 걸린 요청 막기 규칙 중, 건 프로세스가 아직 살아 있는 것. */
|
|
73
74
|
function liveBlocks(tab) {
|
|
@@ -99,8 +100,11 @@ async function header(slot, agent, tabs, opts = {}) {
|
|
|
99
100
|
for (const t of tabs) {
|
|
100
101
|
const blocks = liveBlocks(t);
|
|
101
102
|
if (blocks.length)
|
|
102
|
-
warnings.push(`[${t.id}]
|
|
103
|
+
warnings.push(`[${t.id}] blocking requests: ${blocks.map((b) => `${b.pattern} (${b.agent})`).join(', ')}`);
|
|
103
104
|
}
|
|
105
|
+
// Chrome 권한 요청 말풍선 (페이지 밖 브라우저 화면이라 스냅샷에 안 보인다)
|
|
106
|
+
for (const b of permissionBubbles(slot, hostsOf(tabs.map((t) => t.url))))
|
|
107
|
+
warnings.push(bubbleLine(b, await bubbleDetail(b)));
|
|
104
108
|
const dialogs = dialogsOf(slot, tabs);
|
|
105
109
|
// 탭 목록이 이 에이전트가 지난번에 본 것과 같고 경고·알림창·메시지도 없으면 한 줄로 (읽을 양을 줄여 다음 판단이 빨라지게)
|
|
106
110
|
const key = `${slot}:${agent}`;
|
|
@@ -111,7 +115,7 @@ async function header(slot, agent, tabs, opts = {}) {
|
|
|
111
115
|
lastTabList.set(key, sig);
|
|
112
116
|
if (opts.compact && same && !warnings.length && !messages.length && !dialogs.size) {
|
|
113
117
|
const exec = tabs.find((t) => t.targetId === opts.executed);
|
|
114
|
-
return `[${slot}
|
|
118
|
+
return `[Slot ${slot}] ${tabs.length} tab(s)${exec ? ` · ran on tab ${exec.no} [${exec.id}]` : ''} (tab list unchanged)`;
|
|
115
119
|
}
|
|
116
120
|
return formatHeader({ slot, tabs, executedTargetId: opts.executed, warnings, dialogs, messages });
|
|
117
121
|
}
|
|
@@ -184,7 +188,7 @@ async function onTab(args, kind, action, fn, opts = {}) {
|
|
|
184
188
|
// 행동 도중 알림창이 뜬 것은 실패가 아니다 (클릭은 이루어졌음).
|
|
185
189
|
if (!(e instanceof act.DialogInterrupt))
|
|
186
190
|
throw e;
|
|
187
|
-
out = { text:
|
|
191
|
+
out = { text: `Action done. Then: ${e.message}` };
|
|
188
192
|
}
|
|
189
193
|
tabs = await syncTabs(slot).catch(() => tabs);
|
|
190
194
|
if (action) {
|
|
@@ -192,17 +196,17 @@ async function onTab(args, kind, action, fn, opts = {}) {
|
|
|
192
196
|
const acted = tabs.find((t) => t.targetId === tab.targetId);
|
|
193
197
|
const ok = await recordAction(slot, tab.targetId, agent, action, args.summary, !args.agent, acted ? acted.title || shortUrl(acted.url) : undefined);
|
|
194
198
|
if (!ok)
|
|
195
|
-
warnings.push('
|
|
199
|
+
warnings.push('Not logged: could not lock the shared registry, so this action was not recorded.');
|
|
196
200
|
}
|
|
197
201
|
const opened = tabs.filter((t) => !before.has(t.targetId));
|
|
198
202
|
if (opened.length) {
|
|
199
|
-
out.text += `\
|
|
203
|
+
out.text += `\nNew tab opened: ${opened.map((t) => `tab ${t.no} [${t.id}] ${t.url === 'about:blank' || !t.url ? '(loading)' : truncate(t.title || shortUrl(t.url), 40)}`).join(', ')}`;
|
|
200
204
|
}
|
|
201
205
|
if (action && !session.dialog) {
|
|
202
206
|
// 클릭 등으로 페이지가 전체 화면이 되면 사용자 창 상태가 바뀌므로 바로 해제한다.
|
|
203
207
|
const fs = await session.evaluate('(() => { if (!document.fullscreenElement) return false; document.exitFullscreen(); return true; })()', { timeoutMs: 1500 }).catch(() => undefined);
|
|
204
208
|
if (fs?.value)
|
|
205
|
-
out.text += '\n[
|
|
209
|
+
out.text += '\n[warning] The page went fullscreen; exited it right away (CDPM never changes window state).';
|
|
206
210
|
}
|
|
207
211
|
return compose(await header(slot, agent, tabs, { executed: tab.targetId, warnings, compact: true }), out);
|
|
208
212
|
}
|
|
@@ -222,8 +226,8 @@ async function guard(fn) {
|
|
|
222
226
|
function pageFooter(p, total, extra = '') {
|
|
223
227
|
if (p.pages <= 1)
|
|
224
228
|
return '';
|
|
225
|
-
const next = p.page < p.pages ? ` ·
|
|
226
|
-
return `\n\n— ${p.page}/${p.pages}
|
|
229
|
+
const next = p.page < p.pages ? ` · next: page=${p.page + 1}` : ' · last page';
|
|
230
|
+
return `\n\n— page ${p.page}/${p.pages} (${total.toLocaleString()} chars total)${next}${extra}`;
|
|
227
231
|
}
|
|
228
232
|
// ---------- 네트워크 표시 ----------
|
|
229
233
|
function fmtSize(n) {
|
|
@@ -238,8 +242,8 @@ function fmtSize(n) {
|
|
|
238
242
|
function netLine(e, rules = []) {
|
|
239
243
|
const blockedBy = e.blockedBy ?? (e.failed && /BLOCKED_BY_CLIENT/.test(e.failed) ? rules.find((r) => wildcard(r.pattern).test(e.url))?.pattern : undefined);
|
|
240
244
|
const status = e.failed
|
|
241
|
-
?
|
|
242
|
-
: e.status !== undefined ? String(e.status) + (e.fromCache ? ' (
|
|
245
|
+
? `failed ${e.failed}${blockedBy ? ` (blocked: ${blockedBy})` : ''}`
|
|
246
|
+
: e.status !== undefined ? String(e.status) + (e.fromCache ? ' (cache)' : '') : '…';
|
|
243
247
|
const parts = [`n${e.no}`, e.method, status, e.type, fmtSize(e.size), e.durationMs !== undefined ? `${e.durationMs}ms` : ''].filter(Boolean);
|
|
244
248
|
return `${parts.join(' ')} ${truncate(decodeUrl(e.url), 140)}`;
|
|
245
249
|
}
|
|
@@ -247,15 +251,15 @@ function netLine(e, rules = []) {
|
|
|
247
251
|
async function responseBody(s, e) {
|
|
248
252
|
const b = await s.send('Network.getResponseBody', { requestId: e.requestId }, 10_000).catch(() => undefined);
|
|
249
253
|
if (!b)
|
|
250
|
-
return ' (
|
|
254
|
+
return ' (unavailable: still loading, already discarded by Chrome, or a redirect)';
|
|
251
255
|
if (b.base64Encoded && !/json|text|xml|javascript|html/i.test(e.mimeType ?? ''))
|
|
252
|
-
return ` (
|
|
256
|
+
return ` (binary ${fmtSize(Buffer.from(b.body, 'base64').length)}, ${e.mimeType})`;
|
|
253
257
|
const raw = b.base64Encoded ? Buffer.from(b.body, 'base64').toString('utf8') : b.body;
|
|
254
|
-
return raw.length > 20_000 ? raw.slice(0, 20_000) + `\n… (
|
|
258
|
+
return raw.length > 20_000 ? raw.slice(0, 20_000) + `\n… (truncated: ${raw.length.toLocaleString()} chars total)` : raw;
|
|
255
259
|
}
|
|
256
260
|
function headersText(h) {
|
|
257
261
|
if (!h)
|
|
258
|
-
return ' (
|
|
262
|
+
return ' (none)';
|
|
259
263
|
return Object.entries(h).map(([k, v]) => ` ${k}: ${truncate(String(v), 300)}`).join('\n');
|
|
260
264
|
}
|
|
261
265
|
/** 도메인만 적으면 그 주소가 들어간 모든 요청으로 넓힌다. */
|
|
@@ -269,14 +273,14 @@ function normalizePattern(p) {
|
|
|
269
273
|
export function registerTools(server) {
|
|
270
274
|
// ---------- 슬롯·탭 ----------
|
|
271
275
|
server.registerTool('browser_status', {
|
|
272
|
-
title: '
|
|
273
|
-
description: '
|
|
276
|
+
title: 'Slot status',
|
|
277
|
+
description: 'Shows running Chrome slots (1-30) with their tabs, opener, last action and one-line summary. Pass slot for just that slot.',
|
|
274
278
|
inputSchema: { slot: slotArg.optional(), agent: agentArg },
|
|
275
279
|
}, async ({ slot, agent }) => guard(async () => {
|
|
276
280
|
const live = await liveSlots();
|
|
277
281
|
const target = slot ? live.filter(([s]) => s === slot) : live;
|
|
278
282
|
if (!target.length)
|
|
279
|
-
return textResult(slot ?
|
|
283
|
+
return textResult(slot ? `Slot ${slot} Chrome is not running.` : 'No slots running. Start one with browser_launch when the user asks.');
|
|
280
284
|
const parts = [];
|
|
281
285
|
for (const [s] of target) {
|
|
282
286
|
const tabs = await syncTabs(s).catch(() => null);
|
|
@@ -285,30 +289,30 @@ export function registerTools(server) {
|
|
|
285
289
|
for (const t of tabs ?? []) {
|
|
286
290
|
const d = knownDialog(s, t.targetId);
|
|
287
291
|
if (d)
|
|
288
|
-
part += `\n [
|
|
292
|
+
part += `\n [warning] dialog open (${d.type}) ([${t.id}]): "${truncate(d.message, 80)}"`;
|
|
289
293
|
}
|
|
290
294
|
parts.push(part);
|
|
291
295
|
}
|
|
292
296
|
const me = agent ?? DEFAULT_AGENT;
|
|
293
|
-
return textResult(`${parts.join('\n\n')}\n\n(
|
|
297
|
+
return textResult(`${parts.join('\n\n')}\n\n(your name: ${me})`);
|
|
294
298
|
}));
|
|
295
299
|
server.registerTool('browser_launch', {
|
|
296
|
-
title: '
|
|
297
|
-
description: '
|
|
298
|
-
'slot
|
|
299
|
-
'
|
|
300
|
-
'
|
|
301
|
-
'
|
|
300
|
+
title: 'Launch slot',
|
|
301
|
+
description: 'Starts slot Chrome. Call only when the user explicitly asks (other tools never start a closed slot). ' +
|
|
302
|
+
'Without slot, uses the lowest free slot. If already running, just attaches. ' +
|
|
303
|
+
'The user decides windowed (visible) vs headless (hidden): headless: true only if they say "headless/hidden". If unstated, don\'t guess; ask first, then call with headless. ' +
|
|
304
|
+
'Starting a closed slot without headless only returns a confirmation request. ' +
|
|
305
|
+
'Start several slots at once with slots (list) or count (lowest first). For different jobs per slot, after launching give each slot its own subagent in parallel.',
|
|
302
306
|
inputSchema: {
|
|
303
|
-
slot: slotArg.optional().describe('
|
|
304
|
-
slots: z.array(slotArg).optional().describe('
|
|
305
|
-
count: z.number().int().min(1).max(MAX_SLOT).optional().describe('
|
|
306
|
-
url: z.string().optional().describe('
|
|
307
|
-
urls: z.array(z.string()).optional().describe('
|
|
307
|
+
slot: slotArg.optional().describe('One slot to start (1-30). Omit if the user gave no number → lowest free slot'),
|
|
308
|
+
slots: z.array(slotArg).optional().describe('Slot numbers to start at once (e.g. [1,2,3]), lowest first'),
|
|
309
|
+
count: z.number().int().min(1).max(MAX_SLOT).optional().describe('When the user gives only a count ("start 3"): starts that many free slots, lowest first'),
|
|
310
|
+
url: z.string().optional().describe('Same start URL for every launched slot (e.g. "https://mail.google.com"). For per-slot or partial URLs use urls instead. Pass it when the start page is known so subagents need no separate navigation'),
|
|
311
|
+
urls: z.array(z.string()).optional().describe('Per-slot start URLs, paired in slots order (count: launch order). "" = blank tab. E.g. slots [1,2], urls ["https://www.wehago.com", "https://test.igel.kr"] → 1 opens wehago, 2 opens test.igel.kr'),
|
|
308
312
|
agent: agentArg,
|
|
309
|
-
headless: z.boolean().optional().describe('false =
|
|
310
|
-
proxy: z.string().optional().describe('
|
|
311
|
-
proxies: z.array(z.string()).optional().describe('
|
|
313
|
+
headless: z.boolean().optional().describe('false = windowed (visible), true = headless (hidden). true only if the user says "headless/hidden/no window", false for "visible/headful". If unstated, omit and ask first (no guessing). Applies only on first launch'),
|
|
314
|
+
proxy: z.string().optional().describe('Only when the user asks for a proxy (never otherwise). As given: "1.2.3.4:8080", "http://user:pass@host:port", "socks5://host:port", "host:port:user:pass", etc. Applies to all launched slots, first launch only'),
|
|
315
|
+
proxies: z.array(z.string()).optional().describe('Per-slot proxies, paired in slots order (count: launch order)'),
|
|
312
316
|
},
|
|
313
317
|
}, async ({ slot: wanted, slots: wantedList, count, agent, headless, url, urls, proxy, proxies }) => guard(async () => {
|
|
314
318
|
const me = agent ?? DEFAULT_AGENT;
|
|
@@ -321,7 +325,7 @@ export function registerTools(server) {
|
|
|
321
325
|
else {
|
|
322
326
|
targets = await freeSlots(count ?? 1);
|
|
323
327
|
if (targets.length < (count ?? 1)) {
|
|
324
|
-
throw new CdpmError(
|
|
328
|
+
throw new CdpmError(`Only ${targets.length} free slot(s) (requested ${count ?? 1}). Close unused slots with browser_close.`);
|
|
325
329
|
}
|
|
326
330
|
}
|
|
327
331
|
// 시작 주소: urls는 slots에 준 순서(없으면 켜지는 번호 순서)대로, 나머지는 url
|
|
@@ -336,7 +340,7 @@ export function registerTools(server) {
|
|
|
336
340
|
for (const u of startUrl.values()) {
|
|
337
341
|
const ext = act.externalScheme(u);
|
|
338
342
|
if (ext)
|
|
339
|
-
throw new CdpmError(
|
|
343
|
+
throw new CdpmError(`Can't use a ${ext} URL (${u.slice(0, 80)}) as start URL (it would launch another program on the user's PC).`);
|
|
340
344
|
}
|
|
341
345
|
targets.sort((x, y) => x - y);
|
|
342
346
|
// 모드를 사용자가 정하지 않았으면 꺼진 슬롯은 켜지 않는다 (이미 떠 있으면 그대로 붙는다).
|
|
@@ -344,8 +348,8 @@ export function registerTools(server) {
|
|
|
344
348
|
const states = await Promise.all(targets.map((t) => probe(t)));
|
|
345
349
|
const closed = targets.filter((_, i) => states[i].state !== 'chrome');
|
|
346
350
|
if (closed.length) {
|
|
347
|
-
return textResult(`[
|
|
348
|
-
`headless(
|
|
351
|
+
return textResult(`[Confirm] Slot ${closed.join(', ')} not started yet. Ask the user once: visible window or headless (hidden)? ` +
|
|
352
|
+
`Then call again with headless (windowed false, headless true).`);
|
|
349
353
|
}
|
|
350
354
|
}
|
|
351
355
|
// 작은 번호부터 차례로 켠다 (작업표시줄에도 그 순서로 놓인다). 한 번의 호출로 끝내서 왕복을 줄인다.
|
|
@@ -355,55 +359,54 @@ export function registerTools(server) {
|
|
|
355
359
|
const { launched } = await launchSlot(slot, me, { headless, url: startUrl.get(slot), proxy: proxyOf.get(slot) });
|
|
356
360
|
anyLaunched ||= launched;
|
|
357
361
|
if (launched)
|
|
358
|
-
await recordAction(slot, '', me, '
|
|
362
|
+
await recordAction(slot, '', me, 'launch', undefined, !agent);
|
|
359
363
|
const running = readRegistry().slots[String(slot)];
|
|
360
|
-
const mode = running?.headless ? '
|
|
361
|
-
const via = running?.proxy ? `,
|
|
362
|
-
let line = launched ?
|
|
364
|
+
const mode = running?.headless ? 'headless' : 'windowed';
|
|
365
|
+
const via = running?.proxy ? `, proxy ${running.proxy}` : '';
|
|
366
|
+
let line = launched ? `Started slot ${slot} Chrome ${mode} (port ${portOf(slot)}${via})${startUrl.get(slot) ? ` → opening ${truncate(startUrl.get(slot), 60)}` : ''}.` : `Slot ${slot} Chrome already running; attached.`;
|
|
363
367
|
if (!launched && headless !== undefined && headless !== !!running?.headless) {
|
|
364
|
-
line += ` [
|
|
368
|
+
line += ` [warning] Already running ${mode}, attached as is. To change, browser_close then launch again.`;
|
|
365
369
|
}
|
|
366
370
|
const askedProxy = proxyOf.get(slot);
|
|
367
371
|
if (!launched && askedProxy && running?.proxy !== describeProxy(askedProxy)) {
|
|
368
|
-
line += ` [
|
|
372
|
+
line += ` [warning] Already running ${running?.proxy ? `with proxy ${running.proxy}` : 'without proxy'}, so the requested proxy was not applied. To apply, browser_close then launch again with proxy.`;
|
|
369
373
|
}
|
|
370
374
|
lines.push(line);
|
|
371
375
|
}
|
|
372
376
|
let msg = lines.join('\n');
|
|
373
377
|
if (anyLaunched && picked) {
|
|
374
|
-
msg += targets.length === 1 ? '\
|
|
378
|
+
msg += targets.length === 1 ? '\nNo number given; picked the lowest free slot.' : '\nNo numbers given; picked free slots, lowest first.';
|
|
375
379
|
}
|
|
376
380
|
if (targets.length > 1 && !isClaudeCode()) {
|
|
377
|
-
msg += '\n[
|
|
378
|
-
'
|
|
381
|
+
msg += '\n[Next] For different jobs per slot, give each slot its own subagent if available; otherwise process them in turn with a distinct agent name per slot (e.g. "slot1-agent"). ' +
|
|
382
|
+
'If the user must log in, don\'t ask them to "tell me when done"; detect completion with browser_wait url/gone/text.';
|
|
379
383
|
}
|
|
380
384
|
if (targets.length > 1 && isClaudeCode()) {
|
|
381
|
-
msg += '\n[
|
|
382
|
-
'(
|
|
383
|
-
'
|
|
385
|
+
msg += '\n[Next] For different jobs per slot, now call the Agent tool once per slot in a single message (run_in_background: true) to launch subagents (subagent_type "cdpm-browser") together. Prompts: slot number, agent name, task only, 1-3 lines ' +
|
|
386
|
+
'(each uses its slot number and own agent name). Subagents do everything from the first navigation; main must not pre-navigate slots or process them in turn. ' +
|
|
387
|
+
'If the user must log in, don\'t ask them to "tell me when done"; let subagents detect it with browser_wait url/gone/text.';
|
|
384
388
|
if (targets.length > 20) {
|
|
385
|
-
msg += `\n[
|
|
386
|
-
'
|
|
389
|
+
msg += `\n[warning] At most 20 subagents run at once (the 21st+ is refused). Launch 20 of ${targets.length} first, then the remaining ${targets.length - 20} as they finish. ` +
|
|
390
|
+
'To launch all at once, the user must raise the env var CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS.';
|
|
387
391
|
}
|
|
388
392
|
}
|
|
389
393
|
const first = targets[0];
|
|
390
394
|
return textResult(`${await header(first, me, await syncTabs(first))}\n---\n${msg}`);
|
|
391
395
|
}));
|
|
392
396
|
server.registerTool('browser_close', {
|
|
393
|
-
title: '
|
|
394
|
-
description: '
|
|
397
|
+
title: 'Close slot',
|
|
398
|
+
description: 'Closes slot Chrome cleanly (session and cookies saved). The profile (logins) is kept. Reports if another agent used it recently.',
|
|
395
399
|
inputSchema: { slot: slotArg, agent: agentArg },
|
|
396
400
|
}, async ({ slot, agent }) => guard(() => withSlotLock(slot, async () => {
|
|
397
401
|
const me = agent ?? DEFAULT_AGENT;
|
|
398
402
|
if ((await probe(slot)).state !== 'chrome') {
|
|
399
403
|
await forgetSlot(slot);
|
|
400
|
-
return textResult(
|
|
404
|
+
return textResult(`Slot ${slot} Chrome is already closed.`);
|
|
401
405
|
}
|
|
402
406
|
const rec = readRegistry().slots[String(slot)];
|
|
403
407
|
const warnings = [];
|
|
404
408
|
if (rec?.last && rec.last.agent !== me && secondsSince(rec.last.at) <= 120) {
|
|
405
|
-
|
|
406
|
-
warnings.push(`${josa(rec.last.agent, '이', '가')} ${when === '방금' ? when : `${when}에`} 이 슬롯을 썼어요.`);
|
|
409
|
+
warnings.push(`${rec.last.agent} used this slot (${ago(rec.last.at)}).`);
|
|
407
410
|
}
|
|
408
411
|
const browser = await browserConnection(slot);
|
|
409
412
|
await browser.send('Browser.close', {}, 5000).catch(() => undefined);
|
|
@@ -413,11 +416,11 @@ export function registerTools(server) {
|
|
|
413
416
|
for (let i = 0; rec?.pid && i < 50 && pidAlive(rec.pid); i++)
|
|
414
417
|
await sleep(100);
|
|
415
418
|
await forgetSlot(slot);
|
|
416
|
-
return textResult([...warnings,
|
|
419
|
+
return textResult([...warnings, `Closed slot ${slot} Chrome. The profile is kept, so logins persist next launch.`].join('\n'));
|
|
417
420
|
})));
|
|
418
421
|
server.registerTool('browser_tabs', {
|
|
419
|
-
title: '
|
|
420
|
-
description: '
|
|
422
|
+
title: 'List tabs',
|
|
423
|
+
description: 'Slot tab list: number, ID, title, URL, opener, last action, per-tab summary (updated only by actions with summary). "·front" marks the tab currently in front in its window (one per window).',
|
|
421
424
|
inputSchema: { slot: slotArg, agent: agentArg },
|
|
422
425
|
}, async ({ slot, agent }) => guard(async () => {
|
|
423
426
|
const me = agent ?? DEFAULT_AGENT;
|
|
@@ -425,13 +428,13 @@ export function registerTools(server) {
|
|
|
425
428
|
const tabs = await syncTabs(slot);
|
|
426
429
|
const head = await header(slot, me, tabs);
|
|
427
430
|
const detail = tabs.filter((t) => t.rec.summary)
|
|
428
|
-
.map((t) => `${t.no}. [${t.id}]
|
|
429
|
-
return textResult(`${head}\n---\n${detail.length ? detail.join('\n') : '
|
|
431
|
+
.map((t) => `${t.no}. [${t.id}] summary: ${t.rec.summary.agent} — ${t.rec.summary.text} (${ago(t.rec.summary.at)})`);
|
|
432
|
+
return textResult(`${head}\n---\n${detail.length ? detail.join('\n') : 'No per-tab summaries'}`);
|
|
430
433
|
}));
|
|
431
434
|
server.registerTool('browser_tab_new', {
|
|
432
|
-
title: '
|
|
433
|
-
description: '
|
|
434
|
-
inputSchema: { slot: slotArg, agent: agentArg, url: z.string().optional().describe('
|
|
435
|
+
title: 'New tab',
|
|
436
|
+
description: 'Opens a new tab in the slot and returns its ID. When agents share a slot, open your own tab and work only by its ID to avoid mixing.',
|
|
437
|
+
inputSchema: { slot: slotArg, agent: agentArg, url: z.string().optional().describe('URL to open (omit for blank tab)'), summary: summaryArg },
|
|
435
438
|
}, async ({ slot, agent, url, summary }) => guard(async () => {
|
|
436
439
|
const me = agent ?? DEFAULT_AGENT;
|
|
437
440
|
const paused = pausedRefusal(slot);
|
|
@@ -442,21 +445,21 @@ export function registerTools(server) {
|
|
|
442
445
|
const target = url ? (/^[a-z][a-z0-9+.-]*:/i.test(url) ? url : `https://${url}`) : 'about:blank';
|
|
443
446
|
const ext = act.externalScheme(target);
|
|
444
447
|
if (ext)
|
|
445
|
-
throw new CdpmError(
|
|
448
|
+
throw new CdpmError(`Can't open a ${ext} URL (${target.slice(0, 80)}) (it would launch another program on the user's PC).`);
|
|
446
449
|
// background: 사용자가 보고 있는 탭을 바꾸지 않는다.
|
|
447
450
|
const { targetId } = await browser.send('Target.createTarget', { url: target, background: true });
|
|
448
451
|
markCreated(targetId, me);
|
|
449
452
|
lastTabOf.set(`${slot}:${me}`, targetId);
|
|
450
453
|
await syncTabs(slot);
|
|
451
|
-
await recordAction(slot, targetId, me, '
|
|
454
|
+
await recordAction(slot, targetId, me, 'open tab', summary);
|
|
452
455
|
const tabs = await syncTabs(slot);
|
|
453
456
|
const tab = tabs.find((t) => t.targetId === targetId);
|
|
454
|
-
return compose(await header(slot, me, tabs, { executed: targetId }), { text:
|
|
457
|
+
return compose(await header(slot, me, tabs, { executed: targetId }), { text: `Opened new tab: ${tab ? `tab ${tab.no} [${tab.id}]` : targetId}${url ? ` → ${target} (may still be loading)` : ''}` });
|
|
455
458
|
}));
|
|
456
459
|
server.registerTool('browser_tab_close', {
|
|
457
|
-
title: '
|
|
458
|
-
description: '
|
|
459
|
-
inputSchema: { slot: slotArg, agent: agentArg, tab: z.union([z.string(), z.number()]).describe('
|
|
460
|
+
title: 'Close tab',
|
|
461
|
+
description: 'Closes a tab. tab is required.',
|
|
462
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: z.union([z.string(), z.number()]).describe('Tab to close: number or ID ("t7")') },
|
|
460
463
|
}, async ({ slot, agent, tab }) => guard(async () => {
|
|
461
464
|
const me = agent ?? DEFAULT_AGENT;
|
|
462
465
|
const paused = pausedRefusal(slot);
|
|
@@ -472,30 +475,30 @@ export function registerTools(server) {
|
|
|
472
475
|
await browser.send('Target.closeTarget', { targetId: picked.tab.targetId });
|
|
473
476
|
await sleep(200);
|
|
474
477
|
tabs = await syncTabs(slot);
|
|
475
|
-
return textResult(`${await header(slot, me, tabs, { warnings })}\n---\
|
|
478
|
+
return textResult(`${await header(slot, me, tabs, { warnings })}\n---\nClosed tab: tab ${picked.tab.no} [${picked.tab.id}] ${picked.tab.title}`);
|
|
476
479
|
}));
|
|
477
480
|
server.registerTool('browser_tab_select', {
|
|
478
|
-
title: '
|
|
479
|
-
description: '
|
|
480
|
-
inputSchema: { slot: slotArg, agent: agentArg, tab: z.union([z.string(), z.number()]).describe('
|
|
481
|
-
}, async (args) => onTab(args, 'action', '
|
|
481
|
+
title: 'Bring tab to front',
|
|
482
|
+
description: 'Brings a tab to the front of its Chrome window. Changes what the user sees, so use only when the user wants it. (Background tabs can be read, operated and captured; no need to bring them forward to work.)',
|
|
483
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: z.union([z.string(), z.number()]).describe('Tab to bring forward: number or ID') },
|
|
484
|
+
}, async (args) => onTab(args, 'action', 'select tab', async (s, tab) => {
|
|
482
485
|
const browser = await browserConnection(s.slot);
|
|
483
486
|
await browser.send('Target.activateTarget', { targetId: tab.targetId });
|
|
484
487
|
forgetSlotVisibility(s.slot);
|
|
485
488
|
await sleep(150);
|
|
486
|
-
return { text:
|
|
489
|
+
return { text: `Brought tab ${tab.no} [${tab.id}] to front.` };
|
|
487
490
|
}));
|
|
488
491
|
// ---------- 보기 ----------
|
|
489
492
|
server.registerTool('browser_snapshot', {
|
|
490
|
-
title: '
|
|
491
|
-
description: '
|
|
492
|
-
'
|
|
493
|
-
'find="
|
|
493
|
+
title: 'Snapshot',
|
|
494
|
+
description: 'Reads the tab as accessibility-tree text. Clickable/typable elements get refs like [e12]. ' +
|
|
495
|
+
'Long pages are split; only page 1 (top) is shown (page=2 to continue; refs stay the same across pages). ' +
|
|
496
|
+
'find="text" shows only matching elements with their parent context; ref="e40" shows only that element\'s subtree. Refs change when the page changes, so re-snapshot before acting.',
|
|
494
497
|
inputSchema: {
|
|
495
498
|
slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, page: pageArg,
|
|
496
|
-
find: z.string().optional().describe('
|
|
497
|
-
interactive: z.boolean().optional().describe('
|
|
498
|
-
ref: z.string().optional().describe('
|
|
499
|
+
find: z.string().optional().describe('Only lines containing this text, with parent context (ignores case and spaces). If unsure of site language, use | for alternatives, e.g. "제목|subject"'),
|
|
500
|
+
interactive: z.boolean().optional().describe('Only actionable elements (lines with refs): inputs, buttons, links. Use first to find inputs on big pages like Gmail'),
|
|
501
|
+
ref: z.string().optional().describe('Only this ref element and its subtree'),
|
|
499
502
|
},
|
|
500
503
|
}, async (args) => onTab(args, 'view', null, async (s, tab, agent) => {
|
|
501
504
|
const page = args.page ?? 1;
|
|
@@ -506,92 +509,141 @@ export function registerTools(server) {
|
|
|
506
509
|
// interactive: ref가 붙은 줄(조작할 수 있는 요소와 제목)만 → 큰 페이지에서도 몇 쪽 안에 입력칸·버튼이 다 보인다
|
|
507
510
|
const text = args.interactive ? full.split('\n').filter((l) => /\[e\d+\]/.test(l)).map((l) => l.trimStart()).join('\n') : full;
|
|
508
511
|
if (!text)
|
|
509
|
-
return { text: '(
|
|
512
|
+
return { text: '(no readable elements)' };
|
|
510
513
|
if (args.ref) {
|
|
511
514
|
const sub = subtree(text, args.ref);
|
|
512
515
|
if (!sub)
|
|
513
|
-
throw new CdpmError(`[${args.ref}]
|
|
516
|
+
throw new CdpmError(`[${args.ref}] not found in this snapshot. Re-snapshot without ref to check.`);
|
|
514
517
|
const p = paginate(sub, page);
|
|
515
518
|
return { text: p.body + pageFooter(p, sub.length) };
|
|
516
519
|
}
|
|
517
520
|
if (args.find) {
|
|
518
521
|
const f = findLines(text, args.find);
|
|
519
522
|
if (!f.matches)
|
|
520
|
-
return { text: `"${args.find}"
|
|
523
|
+
return { text: `No elements contain "${args.find}". (${text.length.toLocaleString()} chars total)` };
|
|
521
524
|
const p = paginate(f.body, page);
|
|
522
|
-
return { text: `${p.body}\n\n— "${args.find}" ${f.matches}
|
|
525
|
+
return { text: `${p.body}\n\n— "${args.find}": ${f.matches} match(es)${f.matches > 150 ? ' (first 150 shown)' : ''}${pageFooter(p, f.body.length)}` };
|
|
523
526
|
}
|
|
524
527
|
const p = paginate(text, page);
|
|
525
528
|
const context = p.page > 1 ? ancestorsOf(text, p.start) : [];
|
|
526
|
-
const head = context.length ? `(
|
|
527
|
-
return { text: head + p.body + pageFooter(p, text.length, ` ·
|
|
529
|
+
const head = context.length ? `(parent context of this page)\n${context.join('\n')}\n ┄┄┄\n` : '';
|
|
530
|
+
return { text: head + p.body + pageFooter(p, text.length, ` · search: find="…" · region: ref="eN"${args.interactive ? '' : ' · inputs/buttons only: interactive=true'}`) };
|
|
528
531
|
}));
|
|
529
532
|
server.registerTool('browser_text', {
|
|
530
|
-
title: '
|
|
531
|
-
description: '
|
|
532
|
-
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, ref: z.string().optional().describe('
|
|
533
|
+
title: 'Read text',
|
|
534
|
+
description: 'Reads the page body text (main/article if present). With ref, only that element\'s text. Shorter and easier than a snapshot for articles/documents. Use page for long text.',
|
|
535
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, ref: z.string().optional().describe('Only this element\'s text'), page: pageArg },
|
|
533
536
|
}, async (args) => onTab(args, 'view', null, async (s, _tab, agent) => ({ text: await act.extractText(s, agent, args.ref, args.page ?? 1) })));
|
|
534
537
|
server.registerTool('browser_screenshot', {
|
|
535
|
-
title: '
|
|
536
|
-
description: '
|
|
538
|
+
title: 'Screenshot',
|
|
539
|
+
description: 'Captures the visible area of the tab as PNG, even background tabs (without switching). Never changes window size or viewport, so full-page capture is unsupported (scroll then capture, or use snapshot/text).',
|
|
537
540
|
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg },
|
|
538
541
|
}, async (args) => onTab(args, 'view', null, async (s) => {
|
|
539
542
|
const data = await act.screenshot(s, await browserConnection(s.slot));
|
|
540
|
-
return { text: '
|
|
543
|
+
return { text: 'Captured.', image: data };
|
|
541
544
|
}, { render: true }));
|
|
542
545
|
// ---------- 조작 ----------
|
|
543
546
|
server.registerTool('browser_navigate', {
|
|
544
|
-
title: '
|
|
545
|
-
description: '
|
|
546
|
-
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, url: z.string().describe('
|
|
547
|
-
}, async (args) => onTab(args, 'action', '
|
|
547
|
+
title: 'Navigate',
|
|
548
|
+
description: 'Navigates the tab to a URL and waits for the body to load.',
|
|
549
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, url: z.string().describe('URL to go to'), read: readArg, summary: summaryArg },
|
|
550
|
+
}, async (args) => onTab(args, 'action', 'navigate', async (s) => ({ text: (await act.navigate(s, args.url)) + act.downloadNote(s) })));
|
|
548
551
|
server.registerTool('browser_back', {
|
|
549
|
-
title: '
|
|
550
|
-
description: '
|
|
552
|
+
title: 'Back',
|
|
553
|
+
description: 'Go back.',
|
|
551
554
|
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, read: readArg, summary: summaryArg },
|
|
552
|
-
}, async (args) => onTab(args, 'action', '
|
|
555
|
+
}, async (args) => onTab(args, 'action', 'back', async (s) => ({ text: await act.back(s) })));
|
|
553
556
|
server.registerTool('browser_forward', {
|
|
554
|
-
title: '
|
|
555
|
-
description: '
|
|
557
|
+
title: 'Forward',
|
|
558
|
+
description: 'Go forward (after going back).',
|
|
556
559
|
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, read: readArg, summary: summaryArg },
|
|
557
|
-
}, async (args) => onTab(args, 'action', '
|
|
560
|
+
}, async (args) => onTab(args, 'action', 'forward', async (s) => ({ text: await act.forward(s) })));
|
|
558
561
|
server.registerTool('browser_reload', {
|
|
559
|
-
title: '
|
|
560
|
-
description: '
|
|
561
|
-
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, ignore_cache: z.boolean().optional().describe('
|
|
562
|
-
}, async (args) => onTab(args, 'action', '
|
|
562
|
+
title: 'Reload',
|
|
563
|
+
description: 'Reloads the page (same as Chrome reload). ignore_cache=true bypasses the cache. Careful: unsaved user input on the page is lost.',
|
|
564
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, ignore_cache: z.boolean().optional().describe('Bypass cache (hard reload)'), read: readArg, summary: summaryArg },
|
|
565
|
+
}, async (args) => onTab(args, 'action', 'reload', async (s) => ({ text: await act.reload(s, args.ignore_cache ?? false) })));
|
|
563
566
|
server.registerTool('browser_dialog', {
|
|
564
|
-
title: '
|
|
565
|
-
description: '
|
|
566
|
-
'
|
|
567
|
-
'beforeunload
|
|
568
|
-
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, accept: z.boolean().describe('true =
|
|
569
|
-
}, async (args) => onTab(args, 'action', '
|
|
567
|
+
title: 'Handle dialog',
|
|
568
|
+
description: 'Accepts (accept: true) or dismisses (accept: false) an open dialog (alert/confirm/prompt/beforeunload). The tab is frozen while a dialog is open. ' +
|
|
569
|
+
'Usually judge from its content and handle it yourself (accept if it is part of the requested task; close unneeded notices/ads). Ask the user only when it confirms an irreversible action they didn\'t request (payment, deletion, etc.). ' +
|
|
570
|
+
'beforeunload: accept = leave page (input lost), dismiss = stay. For prompt, text is the input.',
|
|
571
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, accept: z.boolean().describe('true = OK, false = cancel'), text: z.string().optional().describe('Text for a prompt dialog (used only when accepting)'), read: readArg, summary: summaryArg },
|
|
572
|
+
}, async (args) => onTab(args, 'action', 'dialog', async (s) => ({ text: await act.handleDialog(s, args.accept, args.text) }), { render: false }));
|
|
573
|
+
server.registerTool('browser_permission', {
|
|
574
|
+
title: 'Answer permission bubble',
|
|
575
|
+
description: 'Lists or answers Chrome permission bubbles ("site wants to: access other apps and services on this device / show notifications / know your location…"). ' +
|
|
576
|
+
'They are browser UI: not in snapshot/screenshot, page tools can\'t click them, and the page often waits until they are answered. The header warns when one is open. ' +
|
|
577
|
+
'Without button: shows the open bubbles with their exact button names. With button: presses that button (exact name as listed, e.g. "허용", "Allow", "Block", "Allow while visiting the site"). Windows, windowed slots only.',
|
|
578
|
+
inputSchema: {
|
|
579
|
+
slot: slotArg, agent: agentArg, multiSlot: multiSlotArg,
|
|
580
|
+
button: z.string().optional().describe('Exact button name to press, as listed in the header or by calling without button'),
|
|
581
|
+
site: z.string().optional().describe('Only when several bubbles are open: part of the bubble title (e.g. the site host) to pick one'),
|
|
582
|
+
},
|
|
583
|
+
}, async ({ slot, agent, multiSlot, button, site }) => guard(async () => {
|
|
584
|
+
const me = agent ?? DEFAULT_AGENT;
|
|
585
|
+
if (button) {
|
|
586
|
+
const refused = multiSlotRefusal(me, slot, multiSlot) ?? pausedRefusal(slot);
|
|
587
|
+
if (refused)
|
|
588
|
+
return textResult(refused, true);
|
|
589
|
+
}
|
|
590
|
+
await attachSlot(slot);
|
|
591
|
+
const tabs = await syncTabs(slot);
|
|
592
|
+
const head = async () => header(slot, me, await syncTabs(slot).catch(() => tabs), { skipMessages: true });
|
|
593
|
+
if (process.platform !== 'win32')
|
|
594
|
+
return textResult(`${await head()}\n---\nPermission bubbles can only be detected and answered on Windows.`, true);
|
|
595
|
+
const hosts = hostsOf(tabs.map((t) => t.url));
|
|
596
|
+
const all = permissionBubbles(slot, hosts);
|
|
597
|
+
const list = site ? all.filter((b) => b.title.includes(site)) : all;
|
|
598
|
+
if (!list.length)
|
|
599
|
+
return textResult(`${await head()}\n---\nNo Chrome permission bubble is open on slot ${slot}${site ? ` matching "${site}"` : ''}.`);
|
|
600
|
+
if (!button) {
|
|
601
|
+
const lines = await Promise.all(list.map(async (b) => `- ${bubbleLine(b, await bubbleDetail(b))}`));
|
|
602
|
+
return textResult(`${await head()}\n---\n${lines.join('\n')}`);
|
|
603
|
+
}
|
|
604
|
+
if (list.length > 1)
|
|
605
|
+
return textResult(`${await head()}\n---\n${list.length} bubbles are open; pass site to pick one: ${list.map((b) => `"${b.title}"`).join(', ')}`, true);
|
|
606
|
+
const b = list[0];
|
|
607
|
+
if (!(await pressBubble(b, button))) {
|
|
608
|
+
const d = await bubbleDetail(b);
|
|
609
|
+
return textResult(`${await head()}\n---\nNo button named "${button}" in "${b.title}".${d?.buttons.length ? ` Buttons: ${d.buttons.join(', ')}.` : ''}`, true);
|
|
610
|
+
}
|
|
611
|
+
// 눌린 뒤 말풍선이 닫혔는지 확인 (보통 바로 닫힌다)
|
|
612
|
+
let gone = false;
|
|
613
|
+
for (let i = 0; i < 10 && !gone; i++) {
|
|
614
|
+
await sleep(100);
|
|
615
|
+
gone = !permissionBubbles(slot, hosts).some((x) => x.key === b.key && x.title === b.title);
|
|
616
|
+
}
|
|
617
|
+
const target = tabs.find((t) => hostsOf([t.url]).some((h) => b.title.includes(h)));
|
|
618
|
+
if (target)
|
|
619
|
+
await recordAction(slot, target.targetId, me, `permission: ${button}`, undefined, !agent).catch(() => false);
|
|
620
|
+
return textResult(`${await head()}\n---\nPressed "${button}" on "${b.title}"${target ? ` (tab ${target.no} [${target.id}])` : ''}${gone ? '; the bubble closed.' : '; the bubble is still open (check again).'}`);
|
|
621
|
+
}));
|
|
570
622
|
server.registerTool('browser_hover', {
|
|
571
|
-
title: '
|
|
572
|
-
description: '
|
|
573
|
-
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, ref: z.string().describe('
|
|
574
|
-
}, async (args) => onTab(args, 'action', '
|
|
623
|
+
title: 'Hover',
|
|
624
|
+
description: 'Moves the real mouse over a ref element (no click). For hover menus and tooltips. Use read=changes to see the opened menu.',
|
|
625
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, ref: z.string().describe('ref of the element to hover'), read: readArg, summary: summaryArg },
|
|
626
|
+
}, async (args) => onTab(args, 'action', 'hover', async (s, _tab, agent) => ({ text: await act.hover(s, agent, args.ref) })));
|
|
575
627
|
server.registerTool('browser_drag', {
|
|
576
|
-
title: '
|
|
577
|
-
description: '
|
|
578
|
-
'
|
|
628
|
+
title: 'Drag',
|
|
629
|
+
description: 'Drags with the real mouse (press → move in steps → release): drag and drop, sliders, reordering, drag CAPTCHAs, etc. ' +
|
|
630
|
+
'Target: to (element ref), to_text (text at the drop spot), or dx/dy (pixels from from). HTML drag is handled without starting an OS drag.',
|
|
579
631
|
inputSchema: {
|
|
580
632
|
slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg,
|
|
581
|
-
from: z.string().describe('
|
|
582
|
-
to_text: z.string().optional().describe('
|
|
583
|
-
dx: z.number().optional().describe('
|
|
633
|
+
from: z.string().describe('ref of the element to drag (including ones marked draggable)'), to: z.string().optional().describe('ref of the drop target'),
|
|
634
|
+
to_text: z.string().optional().describe('Text shown at the drop spot (when it has no ref, e.g. "Drop here")'),
|
|
635
|
+
dx: z.number().optional().describe('Horizontal pixels (right +)'), dy: z.number().optional().describe('Vertical pixels (down +)'),
|
|
584
636
|
read: readArg, summary: summaryArg,
|
|
585
637
|
},
|
|
586
|
-
}, async (args) => onTab(args, 'action', '
|
|
638
|
+
}, async (args) => onTab(args, 'action', 'drag', async (s, _tab, agent) => ({ text: await act.drag(s, agent, args.from, args.to, args.dx, args.dy, args.to_text) })));
|
|
587
639
|
server.registerTool('browser_download_wait', {
|
|
588
|
-
title: '
|
|
589
|
-
description: '
|
|
590
|
-
inputSchema: { slot: slotArg, agent: agentArg, timeout: z.number().min(1).max(600).optional().describe('
|
|
640
|
+
title: 'Wait for download',
|
|
641
|
+
description: 'Waits for the most recently started download to finish and returns the saved file path (user\'s Chrome download folder). Call after clicking the download button. Returns as soon as it finishes.',
|
|
642
|
+
inputSchema: { slot: slotArg, agent: agentArg, timeout: z.number().min(1).max(600).optional().describe('Max wait in seconds (default 120)') },
|
|
591
643
|
}, async ({ slot, agent, timeout }) => guard(async () => {
|
|
592
644
|
const me = agent ?? DEFAULT_AGENT;
|
|
593
645
|
await attachSlot(slot);
|
|
594
|
-
const stop = () => (hasUnread(slot, me) ? '
|
|
646
|
+
const stop = () => (hasUnread(slot, me) ? 'Stopped waiting: a new message arrived (check with slot_inbox).' : undefined);
|
|
595
647
|
try {
|
|
596
648
|
return textResult(await waitDownload(slot, timeout ?? 120, stop));
|
|
597
649
|
}
|
|
@@ -600,133 +652,139 @@ export function registerTools(server) {
|
|
|
600
652
|
}
|
|
601
653
|
}));
|
|
602
654
|
server.registerTool('browser_pdf', {
|
|
603
|
-
title: 'PDF
|
|
604
|
-
description: '
|
|
605
|
-
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, path: z.string().optional().describe('
|
|
655
|
+
title: 'Save as PDF',
|
|
656
|
+
description: 'Saves the page as a PDF (receipts, articles, etc.). Without path, saves to the user\'s Downloads folder named after the page title. Doesn\'t change the screen or window.',
|
|
657
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, path: z.string().optional().describe('File path to save (e.g. C:\\Users\\me\\Desktop\\receipt.pdf)') },
|
|
606
658
|
}, async (args) => onTab(args, 'view', null, async (s, tab) => ({ text: await act.pdf(s, args.path, tab.title) })));
|
|
607
659
|
server.registerTool('browser_click', {
|
|
608
|
-
title: '
|
|
609
|
-
description: 'ref
|
|
610
|
-
'
|
|
611
|
-
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, ref: z.string().describe('browser_snapshot
|
|
612
|
-
}, async (args) => onTab(args, 'action', '
|
|
660
|
+
title: 'Click',
|
|
661
|
+
description: 'Clicks a ref element with real mouse events. If another element covers it, doesn\'t click and reports it. Waits for loading if the click navigates; reports new tabs. ' +
|
|
662
|
+
'Clicking a file input or "attach" button intercepts the OS file picker (not shown); then use browser_upload. Doesn\'t click <select> dropdowns (they open a list popup on the user\'s screen); use browser_select.',
|
|
663
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, ref: z.string().describe('ref from browser_snapshot (e.g. "e12")'), double: z.boolean().optional().describe('Double-click'), read: readArg, summary: summaryArg },
|
|
664
|
+
}, async (args) => onTab(args, 'action', 'click', async (s, _tab, agent) => ({ text: await act.click(s, agent, args.ref, args.double ?? false) })));
|
|
613
665
|
server.registerTool('browser_type', {
|
|
614
|
-
title: '
|
|
615
|
-
description: '
|
|
616
|
-
'clear=true
|
|
617
|
-
'fast=true
|
|
666
|
+
title: 'Type',
|
|
667
|
+
description: 'Types text into a ref element, sending real key events (keydown/keypress/input/keyup) per character like a human. ' +
|
|
668
|
+
'clear=true clears existing content; submit=true presses Enter after. Verifies the resulting value and reports a mismatch. ' +
|
|
669
|
+
'fast=true inserts very long text at once without key events. Date/time inputs get the value set directly in their format (time "19:30", date "2026-10-08"; change event then has isTrusted=false).',
|
|
618
670
|
inputSchema: {
|
|
619
|
-
slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, ref: z.string().describe('
|
|
620
|
-
clear: z.boolean().optional().describe('
|
|
621
|
-
fast: z.boolean().optional().describe('
|
|
671
|
+
slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, ref: z.string().describe('ref of the element to type into'), text: z.string().describe('Text to type'),
|
|
672
|
+
clear: z.boolean().optional().describe('Clear existing content'), submit: z.boolean().optional().describe('Press Enter after'),
|
|
673
|
+
fast: z.boolean().optional().describe('Very long text: insert at once without key events'), read: readArg, summary: summaryArg,
|
|
622
674
|
},
|
|
623
|
-
}, async (args) => onTab(args, 'action', '
|
|
675
|
+
}, async (args) => onTab(args, 'action', 'type', async (s, _tab, agent) => ({ text: await act.type(s, agent, args.ref, args.text, args.clear ?? false, args.submit ?? false, args.fast ?? false) })));
|
|
624
676
|
server.registerTool('browser_fill', {
|
|
625
|
-
title: '
|
|
626
|
-
description: '
|
|
627
|
-
'
|
|
628
|
-
'submit="Enter"
|
|
677
|
+
title: 'Fill form',
|
|
678
|
+
description: 'Fills several inputs on the same page in order (each cleared, typed with real key events, value verified). ' +
|
|
679
|
+
'Stops on page change, dialog, or any failed field, and reports how far it got. ' +
|
|
680
|
+
'submit="Enter" presses Enter in the last field; a button ref clicks that button. For dropdowns use browser_select.',
|
|
629
681
|
inputSchema: {
|
|
630
682
|
slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg,
|
|
631
|
-
fields: z.array(z.object({ ref: z.string().describe('
|
|
632
|
-
submit: z.string().optional().describe('
|
|
683
|
+
fields: z.array(z.object({ ref: z.string().describe('Input ref'), text: z.string().describe('Text to enter') })).min(1).max(30).describe('Fields to fill (top to bottom)'),
|
|
684
|
+
submit: z.string().optional().describe('After filling: "Enter" or a button ref to click'),
|
|
633
685
|
read: readArg, summary: summaryArg,
|
|
634
686
|
},
|
|
635
|
-
}, async (args) => onTab(args, 'action', '
|
|
687
|
+
}, async (args) => onTab(args, 'action', 'fill', async (s, _tab, agent) => {
|
|
636
688
|
const href = async () => (await s.evaluate('location.href', { timeoutMs: 3000 }).catch(() => undefined))?.value;
|
|
637
689
|
const start = await href();
|
|
638
690
|
const done = [];
|
|
639
691
|
const stop = (why) => ({ text: [...done, why].join('\n') });
|
|
640
692
|
for (const [i, f] of args.fields.entries()) {
|
|
641
693
|
if (s.dialog)
|
|
642
|
-
return stop(
|
|
694
|
+
return stop(`Stopped before field ${i + 1}: a dialog appeared.`);
|
|
643
695
|
if (pausedInfo(args.slot))
|
|
644
|
-
return stop(
|
|
696
|
+
return stop(`Stopped before field ${i + 1}: the user paused the slot.\n${pausedRefusal(args.slot)}`);
|
|
645
697
|
if (i > 0 && (await href()) !== start)
|
|
646
|
-
return stop(
|
|
698
|
+
return stop(`Page changed; field ${i + 1} [${f.ref}] and after were not filled.`);
|
|
647
699
|
try {
|
|
648
700
|
const r = await act.type(s, agent, f.ref, f.text, true, false);
|
|
649
701
|
done.push(`${i + 1}. ${r}`);
|
|
650
702
|
if (r.includes(act.VALUE_MISMATCH))
|
|
651
|
-
return stop(
|
|
703
|
+
return stop(`Stopped: field ${i + 1} [${f.ref}] value differs from the intended text (not submitted). Check the value and retry.`);
|
|
652
704
|
}
|
|
653
705
|
catch (e) {
|
|
654
706
|
if (e instanceof act.DialogInterrupt)
|
|
655
707
|
throw e;
|
|
656
|
-
return stop(
|
|
708
|
+
return stop(`Stopped at field ${i + 1} [${f.ref}]: ${e.message}`);
|
|
657
709
|
}
|
|
658
710
|
}
|
|
659
711
|
if (args.submit) {
|
|
660
712
|
if (s.dialog)
|
|
661
|
-
return stop('
|
|
662
|
-
done.push(
|
|
713
|
+
return stop('Stopped before submit: a dialog appeared.');
|
|
714
|
+
done.push(`Submit: ${args.submit.toLowerCase() === 'enter' ? await act.pressKey(s, 'Enter') : await act.click(s, agent, args.submit, false)}`);
|
|
663
715
|
}
|
|
664
716
|
return { text: done.join('\n') };
|
|
665
717
|
}));
|
|
666
718
|
server.registerTool('browser_upload', {
|
|
667
|
-
title: '
|
|
668
|
-
description: '
|
|
669
|
-
'
|
|
719
|
+
title: 'Upload file',
|
|
720
|
+
description: 'Puts files into a file input (no OS file picker shown to the user). Give ref of the file input (<input type=file> or its label), or ' +
|
|
721
|
+
'for a site\'s custom "attach" button, click it first with browser_click (CDPM intercepts the picker) and call without ref. The site gets the same events as a human file pick.',
|
|
670
722
|
inputSchema: {
|
|
671
723
|
slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg,
|
|
672
|
-
files: z.array(z.string()).min(1).describe('
|
|
673
|
-
ref: z.string().optional().describe('
|
|
724
|
+
files: z.array(z.string()).min(1).describe('File paths on this PC (absolute recommended)'),
|
|
725
|
+
ref: z.string().optional().describe('File input ref. Omit to use the file picker just opened by a click'),
|
|
674
726
|
read: readArg, summary: summaryArg,
|
|
675
727
|
},
|
|
676
|
-
}, async (args) => onTab(args, 'action', '
|
|
728
|
+
}, async (args) => onTab(args, 'action', 'upload', async (s, _tab, agent) => ({ text: await act.upload(s, agent, args.ref, args.files) })));
|
|
677
729
|
server.registerTool('browser_select', {
|
|
678
|
-
title: '
|
|
679
|
-
description: '<select>
|
|
680
|
-
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, ref: z.string().describe('
|
|
681
|
-
}, async (args) => onTab(args, 'action', '
|
|
730
|
+
title: 'Select option',
|
|
731
|
+
description: 'Picks an option in a <select> dropdown (by value or visible text; partial match OK). Focuses the dropdown and moves with keys (arrow keys on Windows/Linux, typing the first letters on macOS), so the page gets real events and no list popup opens. If nothing matches, lists the available options.',
|
|
732
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, ref: z.string().describe('ref of the dropdown (combobox)'), option: z.string().describe('Option value or text'), read: readArg, summary: summaryArg },
|
|
733
|
+
}, async (args) => onTab(args, 'action', 'select', async (s, _tab, agent) => ({ text: await act.select(s, agent, args.ref, args.option) })));
|
|
682
734
|
server.registerTool('browser_press_key', {
|
|
683
|
-
title: '
|
|
735
|
+
title: 'Press key',
|
|
684
736
|
description: process.platform === 'darwin'
|
|
685
|
-
? '
|
|
686
|
-
: '
|
|
687
|
-
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, key: z.string().describe(process.platform === 'darwin' ? '
|
|
688
|
-
}, async (args) => onTab(args, 'action', '
|
|
737
|
+
? 'Presses a key on the focused element. E.g. Enter, Tab, Escape, ArrowDown, PageDown, Meta+A (select all), Shift+Tab. This PC is macOS, so shortcuts use Meta (Cmd) (Control+A moves to line start).'
|
|
738
|
+
: 'Presses a key on the focused element. E.g. Enter, Tab, Escape, ArrowDown, PageDown, Control+A, Shift+Tab.',
|
|
739
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, key: z.string().describe(process.platform === 'darwin' ? 'Key name or combo (e.g. "Meta+A")' : 'Key name or combo (e.g. "Control+A")'), read: readArg, summary: summaryArg },
|
|
740
|
+
}, async (args) => onTab(args, 'action', 'key', async (s) => ({ text: await act.pressKey(s, args.key) })));
|
|
689
741
|
server.registerTool('browser_scroll', {
|
|
690
|
-
title: '
|
|
691
|
-
description: 'ref
|
|
742
|
+
title: 'Scroll',
|
|
743
|
+
description: 'Scrolls a ref element into view, or by dy pixels (positive = down, negative = up, default 600). Reports the actual resulting position.',
|
|
692
744
|
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, ref: z.string().optional(), dy: z.number().optional(), read: readArg, summary: summaryArg },
|
|
693
|
-
}, async (args) => onTab(args, 'action', '
|
|
745
|
+
}, async (args) => onTab(args, 'action', 'scroll', async (s, _tab, agent) => ({ text: await act.scroll(s, agent, args.ref, args.dy) })));
|
|
694
746
|
server.registerTool('browser_wait', {
|
|
695
|
-
title: '
|
|
696
|
-
description: '
|
|
697
|
-
'response
|
|
698
|
-
'
|
|
699
|
-
'
|
|
700
|
-
'
|
|
747
|
+
title: 'Wait',
|
|
748
|
+
description: 'Waits until text appears; gone: that text disappears; url: the URL changes; enabled: that button/input becomes enabled; ' +
|
|
749
|
+
'response: a network response for that URL completes (returns its body); network_idle: the network goes quiet; otherwise for seconds. ' +
|
|
750
|
+
'For SPAs (search results, lists, etc.), instead of reading the page, getting the data response (JSON) with response="/api/search" after a click is faster and more accurate (it searches from this agent\'s last action on that tab, so responses that arrived during the click are caught). ' +
|
|
751
|
+
'Only reads, never touches the page, so the user\'s input is not lost (use it to detect login: url, gone="Password" or text="Inbox"). ' +
|
|
752
|
+
'Returns as soon as the condition is met or another agent\'s message arrives. Keep waits minimal: long waits only for humans (login, etc.); to wait for other agents use slot_inbox wait.',
|
|
701
753
|
inputSchema: {
|
|
702
754
|
slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg,
|
|
703
|
-
text: z.string().optional().describe('
|
|
704
|
-
url: z.string().optional().describe('
|
|
705
|
-
gone: z.string().optional().describe('
|
|
706
|
-
seconds: z.number().min(0).max(60).optional().describe('
|
|
707
|
-
timeout: z.number().min(1).max(600).optional().describe('text
|
|
708
|
-
network_idle: z.boolean().optional().describe('
|
|
709
|
-
enabled: z.string().optional().describe('
|
|
710
|
-
response: z.string().optional().describe('
|
|
755
|
+
text: z.string().optional().describe('Text to wait for'),
|
|
756
|
+
url: z.string().optional().describe('Until the URL contains this (e.g. "mail.google.com/mail"). "" = until it differs from the current URL'),
|
|
757
|
+
gone: z.string().optional().describe('Until this text disappears from the page (e.g. login form\'s "Password" gone = logged in)'),
|
|
758
|
+
seconds: z.number().min(0).max(60).optional().describe('Plain wait in seconds. Avoid: wait on a condition (text/gone/url) or slot_inbox wait instead'),
|
|
759
|
+
timeout: z.number().min(1).max(600).optional().describe('Max wait in seconds for text/gone/url/enabled/response/network_idle. 300-600 when waiting for a human login, etc.'),
|
|
760
|
+
network_idle: z.boolean().optional().describe('Until no network requests for 0.5s (before capture/read)'),
|
|
761
|
+
enabled: z.string().optional().describe('Until this ref element (button/input) becomes enabled'),
|
|
762
|
+
response: z.string().optional().describe('Until a network response whose URL contains this completes (e.g. "/api/search"). * ? wildcards work (matched against the full URL, e.g. "*api.example.com/v1/items*"). Returns the response body'),
|
|
711
763
|
},
|
|
712
764
|
}, async (args) => onTab(args, 'view', null, async (s, _tab, agent) => {
|
|
765
|
+
// 기다리는 동안 새로 뜬 권한 말풍선도 바로 알린다 (이미 떠 있던 것은 머리말로 이미 알렸으니 제외)
|
|
766
|
+
const hosts = hostsOf((await syncTabs(args.slot).catch(() => [])).map((t) => t.url));
|
|
767
|
+
const known = new Set(permissionBubbles(args.slot, hosts).map((b) => `${b.key}|${b.title}`));
|
|
713
768
|
// 다른 에이전트가 메시지를 보내면 기다리기를 바로 멈춘다 (메시지는 결과 머리말로 전달됨)
|
|
714
769
|
const stop = () => {
|
|
715
770
|
if (pausedInfo(args.slot))
|
|
716
771
|
return pausedRefusal(args.slot);
|
|
717
|
-
|
|
772
|
+
if (hasUnread(args.slot, agent))
|
|
773
|
+
return 'Stopped waiting: a new message arrived (see it in the header above and continue).';
|
|
774
|
+
const fresh = permissionBubbles(args.slot, hosts).find((b) => !known.has(`${b.key}|${b.title}`));
|
|
775
|
+
return fresh ? `Stopped waiting: Chrome showed a permission bubble "${fresh.title}" (see the header above; answer it with browser_permission).` : undefined;
|
|
718
776
|
};
|
|
719
777
|
if (args.response !== undefined) {
|
|
720
778
|
if (!args.response.trim())
|
|
721
|
-
throw new CdpmError('
|
|
779
|
+
throw new CdpmError('Put part of the URL to wait for in response (e.g. "/api/search").');
|
|
722
780
|
// 이 에이전트가 이 탭에서 마지막으로 조작한 뒤(2분 안)의 요청부터. 조작 기록이 없으면 지금부터.
|
|
723
781
|
const last = s.actionStartedAt.get(agent);
|
|
724
782
|
const since = last && Date.now() - last < 120_000 ? last : Date.now();
|
|
725
783
|
try {
|
|
726
784
|
const e = await act.waitForResponse(s, args.response, since, args.timeout ?? 30, stop);
|
|
727
785
|
if (e.failed)
|
|
728
|
-
return { text:
|
|
729
|
-
return { text:
|
|
786
|
+
return { text: `Response failed: ${netLine(e)}` };
|
|
787
|
+
return { text: `Response received: ${netLine(e)}\nURL: ${decodeUrl(e.url).slice(0, 300)}\n\n[Response body]\n${await responseBody(s, e)}` };
|
|
730
788
|
}
|
|
731
789
|
catch (err) {
|
|
732
790
|
if (err instanceof act.WaitStopped)
|
|
@@ -752,24 +810,24 @@ export function registerTools(server) {
|
|
|
752
810
|
return { text: why };
|
|
753
811
|
await sleep(Math.min(100, until - Date.now()));
|
|
754
812
|
}
|
|
755
|
-
return { text:
|
|
813
|
+
return { text: `Waited ${sec}s.` };
|
|
756
814
|
}));
|
|
757
815
|
server.registerTool('browser_eval', {
|
|
758
|
-
title: 'JS
|
|
759
|
-
description: '
|
|
760
|
-
'
|
|
761
|
-
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, expression: z.string().describe('
|
|
762
|
-
}, async (args) => onTab(args, 'action', 'JS
|
|
816
|
+
title: 'Run JS',
|
|
817
|
+
description: 'Evaluates a JavaScript expression in the tab and returns the result as JSON. Escape hatch only when other tools can\'t do it. ' +
|
|
818
|
+
'Runs in an isolated world: DOM can be read and modified, but globals created by page scripts (window.appVar, etc.) are not visible.',
|
|
819
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, expression: z.string().describe('JS expression (Promises are awaited)'), summary: summaryArg },
|
|
820
|
+
}, async (args) => onTab(args, 'action', 'eval JS', async (s) => ({ text: await act.evaluate(s, args.expression) })));
|
|
763
821
|
// ---------- 네트워크 ----------
|
|
764
822
|
server.registerTool('browser_network', {
|
|
765
|
-
title: '
|
|
766
|
-
description: '
|
|
823
|
+
title: 'Network requests',
|
|
824
|
+
description: 'Tab network request list (newest at bottom). Records the latest 500 since CDPM first attached to the tab. Filter with filter (URL part), type (Document, XHR, Fetch, Script, Image, etc.), failed (failures only). For details pass the n-number to browser_network_detail.',
|
|
767
825
|
inputSchema: {
|
|
768
826
|
slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg,
|
|
769
|
-
filter: z.string().optional().describe('
|
|
770
|
-
type: z.string().optional().describe('
|
|
771
|
-
failed: z.boolean().optional().describe('
|
|
772
|
-
limit: z.number().int().min(1).max(200).optional().describe('
|
|
827
|
+
filter: z.string().optional().describe('Only requests whose URL contains this'),
|
|
828
|
+
type: z.string().optional().describe('Request type (e.g. XHR, Fetch, Document, Script, Image)'),
|
|
829
|
+
failed: z.boolean().optional().describe('Failed requests only'),
|
|
830
|
+
limit: z.number().int().min(1).max(200).optional().describe('Max count (default 40, newest first)'),
|
|
773
831
|
},
|
|
774
832
|
}, async (args) => onTab(args, 'view', null, async (s) => {
|
|
775
833
|
let list = s.network.list();
|
|
@@ -782,41 +840,41 @@ export function registerTools(server) {
|
|
|
782
840
|
list = list.filter((e) => e.failed);
|
|
783
841
|
const limit = args.limit ?? 40;
|
|
784
842
|
const shown = list.slice(-limit);
|
|
785
|
-
const since = new Date(s.network.startedAt).toLocaleTimeString('
|
|
786
|
-
const head =
|
|
787
|
-
return { text: `${head}\n${shown.length ? shown.map((e) => netLine(e, s.network.rules)).join('\n') : '(
|
|
843
|
+
const since = new Date(s.network.startedAt).toLocaleTimeString('en-GB', { hour12: false });
|
|
844
|
+
const head = `Recording since ${since} (when CDPM first attached to this tab) · ${list.length} of ${total} recorded match${list.length > limit ? `, newest ${limit} shown` : ''}`;
|
|
845
|
+
return { text: `${head}\n${shown.length ? shown.map((e) => netLine(e, s.network.rules)).join('\n') : '(no matching requests)'}` };
|
|
788
846
|
}));
|
|
789
847
|
server.registerTool('browser_network_detail', {
|
|
790
|
-
title: '
|
|
791
|
-
description: '
|
|
792
|
-
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, id: z.string().describe('
|
|
848
|
+
title: 'Network request detail',
|
|
849
|
+
description: 'Shows one request\'s headers, sent data and response body (start of it, if text). id is the n-number from browser_network.',
|
|
850
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, id: z.string().describe('Request number (e.g. "n12")'), body: z.boolean().optional().describe('Include response body (default true)') },
|
|
793
851
|
}, async (args) => onTab(args, 'view', null, async (s) => {
|
|
794
852
|
const e = s.network.find(args.id);
|
|
795
853
|
if (!e)
|
|
796
|
-
throw new CdpmError(
|
|
797
|
-
const parts = [netLine(e), '',
|
|
854
|
+
throw new CdpmError(`Request "${args.id}" not found. Check numbers with browser_network (only the latest 500 are kept).`);
|
|
855
|
+
const parts = [netLine(e), '', `URL: ${decodeUrl(e.url)}`, '', '[Request headers]', headersText(e.requestHeaders)];
|
|
798
856
|
if (e.hasPostData) {
|
|
799
857
|
const post = await s.send('Network.getRequestPostData', { requestId: e.requestId }, 5000).catch(() => undefined);
|
|
800
|
-
parts.push('', '[
|
|
858
|
+
parts.push('', '[Sent data]', post ? truncate(post.postData, 5000) : ' (unavailable)');
|
|
801
859
|
}
|
|
802
|
-
parts.push('', '[
|
|
860
|
+
parts.push('', '[Response headers]', headersText(e.responseHeaders));
|
|
803
861
|
if (args.body !== false && !e.failed && e.status !== undefined)
|
|
804
|
-
parts.push('', '[
|
|
862
|
+
parts.push('', '[Response body]', await responseBody(s, e));
|
|
805
863
|
return { text: parts.join('\n') };
|
|
806
864
|
}));
|
|
807
865
|
server.registerTool('browser_block', {
|
|
808
|
-
title: '
|
|
809
|
-
description: '
|
|
810
|
-
'
|
|
811
|
-
'
|
|
866
|
+
title: 'Block requests',
|
|
867
|
+
description: 'Blocks tab network requests matching URL patterns (they fail). add adds, remove removes, clear removes all rules you set. ' +
|
|
868
|
+
'Patterns: * any chars, ? one char. A bare domain matches every request containing it ("ads.example.com" → "*ads.example.com*"). A trailing * is added automatically so query strings still match ("*.png" → "*.png*"). The tab skips the cache while rules exist. ' +
|
|
869
|
+
'Rules last only while this Claude session is alive and are shown to other agents in the header. With no args, shows current rules.',
|
|
812
870
|
inputSchema: {
|
|
813
871
|
slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg,
|
|
814
|
-
add: z.array(z.string()).optional().describe('
|
|
815
|
-
remove: z.array(z.string()).optional().describe('
|
|
816
|
-
clear: z.boolean().optional().describe('
|
|
872
|
+
add: z.array(z.string()).optional().describe('URL patterns to block'),
|
|
873
|
+
remove: z.array(z.string()).optional().describe('Patterns to unblock'),
|
|
874
|
+
clear: z.boolean().optional().describe('Remove all rules set by this session'),
|
|
817
875
|
summary: summaryArg,
|
|
818
876
|
},
|
|
819
|
-
}, async (args) => onTab(args, args.add?.length || args.remove?.length || args.clear ? 'action' : 'view', args.add?.length ? '
|
|
877
|
+
}, async (args) => onTab(args, args.add?.length || args.remove?.length || args.clear ? 'action' : 'view', args.add?.length ? 'block requests' : args.remove?.length || args.clear ? 'unblock requests' : null, async (s, tab, agent) => {
|
|
820
878
|
let rules = [...s.network.rules];
|
|
821
879
|
if (args.clear)
|
|
822
880
|
rules = [];
|
|
@@ -844,97 +902,103 @@ export function registerTools(server) {
|
|
|
844
902
|
}
|
|
845
903
|
const others = liveBlocks(tab).filter((b) => b.pid !== process.pid);
|
|
846
904
|
const lines = [
|
|
847
|
-
changed ? '
|
|
848
|
-
|
|
905
|
+
changed ? 'Block rules updated.' : 'Current block rules:',
|
|
906
|
+
`This session: ${rules.length ? rules.map((r) => `${r.pattern} (${r.agent})`).join(', ') : 'none'}`,
|
|
849
907
|
];
|
|
850
908
|
if (others.length)
|
|
851
|
-
lines.push(
|
|
852
|
-
lines.push('
|
|
909
|
+
lines.push(`Other sessions: ${others.map((b) => `${b.pattern} (${b.agent})`).join(', ')} — only removable from that session`);
|
|
910
|
+
lines.push('Blocked requests show in browser_network as "failed … (blocked: pattern)".');
|
|
853
911
|
return { text: lines.join('\n') };
|
|
854
912
|
}));
|
|
855
913
|
// ---------- 메시지 ----------
|
|
856
|
-
const slotsArg = z.array(slotArg).optional().describe('
|
|
914
|
+
const slotsArg = z.array(slotArg).optional().describe('Multiple slots (e.g. [1,2,3])');
|
|
857
915
|
server.registerTool('slot_pause', {
|
|
858
|
-
title: '
|
|
859
|
-
description: '
|
|
860
|
-
'
|
|
861
|
-
inputSchema: { slot: slotArg.optional(), slots: slotsArg, all: z.boolean().optional().describe('
|
|
916
|
+
title: 'Pause slot',
|
|
917
|
+
description: 'Use only when the user says to pause (e.g. "pause 3"); agents never call it on their own. All action tools on the slot are refused and any browser_wait in progress stops at once. ' +
|
|
918
|
+
'An action already sent to Chrome finishes. Reading still works. Applies immediately to agents in other Claude sessions too. all=true pauses every running slot.',
|
|
919
|
+
inputSchema: { slot: slotArg.optional(), slots: slotsArg, all: z.boolean().optional().describe('All running slots'), agent: agentArg },
|
|
862
920
|
}, async ({ slot, slots, all, agent }) => guard(async () => {
|
|
863
921
|
const me = agent ?? DEFAULT_AGENT;
|
|
864
922
|
const targets = all ? (await liveSlots()).map(([s]) => s) : [...new Set([...(slots ?? []), ...(slot !== undefined ? [slot] : [])])];
|
|
865
923
|
if (!targets.length)
|
|
866
|
-
throw new CdpmError('
|
|
867
|
-
return textResult((await pauseSlots(targets, me)).join('\n') + '\
|
|
924
|
+
throw new CdpmError('Specify slots to pause (slot, slots or all).');
|
|
925
|
+
return textResult((await pauseSlots(targets, me)).join('\n') + '\nTo resume: slot_resume when the user says so, or `cdpm resume <number>` in a terminal.');
|
|
868
926
|
}));
|
|
869
927
|
server.registerTool('slot_resume', {
|
|
870
|
-
title: '
|
|
871
|
-
description: '
|
|
872
|
-
inputSchema: { slot: slotArg.optional(), slots: slotsArg, all: z.boolean().optional().describe('
|
|
928
|
+
title: 'Resume slot',
|
|
929
|
+
description: 'Use only when the user says to resume (e.g. "continue 3"); the agent owning a paused slot never calls it on its own. Unpauses and messages every agent on the slot to wake it (agents re-read the page and continue). all=true resumes every paused slot.',
|
|
930
|
+
inputSchema: { slot: slotArg.optional(), slots: slotsArg, all: z.boolean().optional().describe('All paused slots'), agent: agentArg },
|
|
873
931
|
}, async ({ slot, slots, all, agent }) => guard(async () => {
|
|
874
932
|
const me = agent ?? DEFAULT_AGENT;
|
|
875
933
|
const targets = all ? (await import('../pause.js')).pausedSlots() : [...new Set([...(slots ?? []), ...(slot !== undefined ? [slot] : [])])];
|
|
876
934
|
if (!targets.length)
|
|
877
|
-
return textResult(all ? '
|
|
935
|
+
return textResult(all ? 'No paused slots.' : 'Specify slots to resume (slot, slots or all).', !all);
|
|
878
936
|
return textResult((await resumeSlots(targets, me)).join('\n'));
|
|
879
937
|
}));
|
|
880
938
|
server.registerTool('slot_send', {
|
|
881
|
-
title: '
|
|
882
|
-
description: '
|
|
883
|
-
'
|
|
884
|
-
inputSchema: { slot: slotArg, agent: agentArg, text: z.string().min(1).max(2000), to: z.string().optional().describe('
|
|
939
|
+
title: 'Send message',
|
|
940
|
+
description: 'Sends a message to other agents (real-time collaboration). slot = the slot the recipient owns (to reach another slot\'s agent, use that slot number). Omit to to send to everyone on that slot. ' +
|
|
941
|
+
'Recipients get it instantly if waiting in slot_inbox wait, otherwise in their next tool result header (a running browser_wait stops at once). When you finish a step, notify waiting agents right away.',
|
|
942
|
+
inputSchema: { slot: slotArg, agent: agentArg, text: z.string().min(1).max(2000), to: z.string().optional().describe('Recipient agent name') },
|
|
885
943
|
}, async ({ slot, agent, text, to }) => guard(async () => {
|
|
886
944
|
const me = agent ?? DEFAULT_AGENT;
|
|
887
945
|
const msg = await sendMessage(slot, me, text, to ?? null);
|
|
888
|
-
return textResult(`[${slot}
|
|
946
|
+
return textResult(`[Slot ${slot}] Message sent (#${msg.seq}${to ? `, to: ${to}` : ', to everyone'}).`);
|
|
889
947
|
}));
|
|
890
948
|
server.registerTool('slot_inbox', {
|
|
891
|
-
title: '
|
|
892
|
-
description: '
|
|
893
|
-
'
|
|
894
|
-
inputSchema: { slot: slotArg, agent: agentArg, wait: z.number().min(0).max(600).optional().describe('
|
|
949
|
+
title: 'Check messages',
|
|
950
|
+
description: 'Shows your unread messages. With wait (seconds), waits up to that long for a new message (for real-time conversation). ' +
|
|
951
|
+
'Messages already delivered in another tool\'s header are not unread; when there are no new ones, recently received ones are noted for reference.',
|
|
952
|
+
inputSchema: { slot: slotArg, agent: agentArg, wait: z.number().min(0).max(600).optional().describe('Max seconds to wait for a new message; returns as soon as one arrives (use this instead of repeatedly checking the page while waiting for another agent)') },
|
|
895
953
|
}, async ({ slot, agent, wait }) => guard(async () => {
|
|
896
954
|
const me = agent ?? DEFAULT_AGENT;
|
|
897
955
|
const msgs = wait ? await waitUnread(slot, me, wait) : await takeUnread(slot, me);
|
|
898
956
|
if (msgs.length)
|
|
899
|
-
return textResult(`[${slot}
|
|
957
|
+
return textResult(`[Slot ${slot}] ${msgs.length} new message(s)\n${formatMessages(msgs).map((l) => ` ${l}`).join('\n')}`);
|
|
900
958
|
const recent = recentDelivered(slot, me);
|
|
901
|
-
const tail = recent.length ? ` (
|
|
902
|
-
return textResult(`[${slot}
|
|
959
|
+
const tail = recent.length ? ` (${recent.length} message(s) already delivered via other tool headers in the last 10 min are not repeated)` : '';
|
|
960
|
+
return textResult(`[Slot ${slot}] No new messages${wait ? ` (waited ${wait}s)` : ''}.${tail}`);
|
|
903
961
|
}));
|
|
904
962
|
}
|
|
905
|
-
const INSTRUCTIONS_CLAUDE_CODE = `CDPM: Chrome
|
|
906
|
-
-
|
|
907
|
-
-
|
|
908
|
-
-
|
|
909
|
-
-
|
|
910
|
-
-
|
|
911
|
-
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
-
|
|
916
|
-
-
|
|
917
|
-
-
|
|
918
|
-
-
|
|
919
|
-
-
|
|
920
|
-
-
|
|
921
|
-
-
|
|
922
|
-
-
|
|
923
|
-
-
|
|
924
|
-
-
|
|
925
|
-
-
|
|
926
|
-
-
|
|
927
|
-
-
|
|
928
|
-
-
|
|
963
|
+
const INSTRUCTIONS_CLAUDE_CODE = `CDPM: controls Chrome slots 1-30 over CDP. Slot N's CDP port is ${PORT_BASE}+N (slot 1 = ${PORT_BASE + 1}).
|
|
964
|
+
- Always reply to the user in the language the user writes in (these instructions are in English only to save tokens).
|
|
965
|
+
- When telling the user about slot work, always name the tab too, not just the slot: e.g. "working in slot 1, tab 3 [t7]" (tab order from the header, plus its ID).
|
|
966
|
+
- "Look at 3" / "slot 3" means slot=3. Pass slot to every tool.
|
|
967
|
+
- Start Chrome with browser_launch only when the user asks. Other tools never start a closed slot. "Start one" with no number → omit slot (lowest free slot).
|
|
968
|
+
- The user decides windowed (visible) vs headless (hidden): headless: true only if they say "headless", "hidden" or "no window"; false for "visible window" or "headful". If unstated, don't guess; ask first (once for multiple slots).
|
|
969
|
+
- If the start page is known, pass url (same for all slots) or urls (per slot) to browser_launch so it opens right away (no separate navigation step for subagents).
|
|
970
|
+
- Different jobs on multiple slots (e.g. "open 3, one for Naver, one for Daum…", "log in on 1 and open another site on 2") run in parallel by default: main only calls browser_launch once (slots/count, start URLs url/urls), then immediately hands each slot to its own subagent. Subagents do everything from the first navigation (main doesn't pre-navigate slots). Call the Agent tool several times in one message, all with run_in_background: true (don't launch one at a time or wait for earlier ones). Keep subagent prompts to 1-3 lines: slot number, agent name (e.g. "naver-agent", passed as agent on every tool), and the task. cdpm-browser already knows CDPM usage and rules (login detection, signaling, minimal waiting), so don't re-explain (long prompts cost time). Use subagent_type "cdpm-browser" (CDPM-specific subagent, fast start) if available. At most 20 subagents run at once; with more than 20 slots, launch 20 first and the rest as they finish. Main never works through slots serially, unless the user asks for sequential order.
|
|
971
|
+
- Different jobs on tabs within one slot (e.g. "log in on slot 1's first tab, do X on another site in the second tab") are split per tab just like slots: one subagent per tab (main doesn't hop between tabs). Each uses only its tab number or opens its own with browser_tab_new, with a distinct agent name per tab (e.g. "slot1-tab1"). Same slot, so the one-agent-one-slot rule doesn't apply, and actions queue per tab and run concurrently. If a tab's job needs another to finish first (e.g. only works after login), its agent waits with slot_inbox(wait) and the other notifies with slot_send as soon as it's done (login carries over to other tabs: same profile).
|
|
972
|
+
- Roles of main agent and subagents (multi-slot/multi-tab work, any site, always):
|
|
973
|
+
- Main: talks with the user, starts/stops slots (one browser_launch / browser_close), assigns slots and tasks to subagents (all in one message), merges results and reports to the user. Main does not navigate, read or operate slot pages.
|
|
974
|
+
- Subagent: one slot only. Does everything: navigation, reading, typing, clicking, detecting completion of user login etc., writing its share of the output, and signaling other subagents if needed.
|
|
975
|
+
- Simple jobs that need just one slot can be done by main directly.
|
|
976
|
+
- One agent operates one slot. If the same agent operates another slot within 60s, CDPM refuses (viewing is fine; use multiSlot: true only for jobs that must operate several slots together).
|
|
977
|
+
- Outputs (reports, HTML, etc.) are written by each subagent for its share; main only merges (main writing everything alone is the slowest step).
|
|
978
|
+
- The header at the top of each result shows the slot's tabs, which tab ran, warnings and new messages. Check it every time to decide the next step.
|
|
979
|
+
- With multiple tabs, pass tab (number or ID "t7") to action tools. When several agents share a slot, open your own tab with browser_tab_new and use its ID. Background tabs can be read and operated as is.
|
|
980
|
+
- Action tools (navigate, click, type, key, back, select, scroll, fill) accept read, which appends the page after the action. If the next decision needs the page, use read instead of a separate read call: text for articles, snapshot when you need buttons/links to click, changes to see only what changed on the same page (shortest).
|
|
981
|
+
- Fill several inputs on one page (login, search filters, etc.) with one browser_fill. File attach: browser_upload (file input ref, or click the "attach" button first, then call without ref). Hover menus: browser_hover; drag/sliders: browser_drag; downloads: click the button, then browser_download_wait returns the saved file path.
|
|
982
|
+
- browser_snapshot returns only page 1 (top) of long pages. Don't page through: to find inputs/buttons use interactive=true or find="title|subject" (| for alternatives); for text content use browser_text. A summary you leave is visible to other agents in browser_status.
|
|
983
|
+
- Keep waits minimal. Never use fixed waits (seconds).
|
|
984
|
+
- Waits that may take minutes (bulk collection/processing, waiting for user login, etc.) are not done by main: hand them to a background subagent (run_in_background: true), then tell the user the status right away and keep the conversation going. While main waits in browser_wait or runs a long foreground shell command, it can't answer the user.
|
|
985
|
+
- When the user must do something (login, identity verification, CAPTCHA, payment approval, on any site), don't ask them to "tell me when done". Start subagents first; each, without touching the page (no reload or re-navigation: it wipes the user's input), detects completion with browser_wait and continues: URL change (url), login form text gone (gone), or text shown only after login (text). If the user provides an ID/password (e.g. headless), type it and log in.
|
|
986
|
+
- When working with other agents (e.g. emailing each other), signal in real time: as soon as your part is done, slot_send(slot=their slot, to=their name) something like "sent"; when waiting for them, don't reload the page repeatedly, use slot_inbox(slot=your slot, wait=120-600) (returns as soon as a message arrives). On a signal, check the page and act right away.
|
|
987
|
+
- Other slots' pages can be viewed anytime with view tools (browser_snapshot, browser_text, browser_screenshot); only that slot's owner operates it.
|
|
988
|
+
- Never change window size/position or viewport. Use browser_tab_select (changes the tab the user sees) only when the user wants it.
|
|
989
|
+
- "Pause N" → slot_pause; "resume" → slot_resume. Actions on a paused slot are refused: its agent must not operate it and waits with slot_inbox(wait=600); on the resume message it re-reads with browser_snapshot and continues (never resumes on its own).
|
|
990
|
+
- When a dialog (alert/confirm/prompt/beforeunload) appears, judge from its content and accept/dismiss it yourself with browser_dialog. Ask the user only when it confirms an irreversible action they didn't request (payment, deletion, etc.).
|
|
991
|
+
- Chrome permission bubbles ("site wants to access other apps and services on this device", notifications, location, camera, mic…) are browser UI the page can wait on; the header warns when one is open (Windows). Answer it yourself with browser_permission when the task needs it (e.g. a work site asking to reach a local app). Ask the user before allowing camera, microphone or location they didn't ask for.`;
|
|
929
992
|
/** Claude Code가 아닌 클라이언트(Cursor, Claude Desktop 등)용: Agent 도구·run_in_background·cdpm-browser처럼 Claude Code에만 있는 말을 뺀다. */
|
|
930
|
-
const GENERIC_PARALLEL = '-
|
|
931
|
-
'
|
|
993
|
+
const GENERIC_PARALLEL = '- Different jobs on multiple slots (e.g. "open 3, one for Naver, one for Daum…", "log in on 1 and open another site on 2"): if the client supports subagents, hand each slot to one and run them in parallel (main only launches them with one browser_launch). ' +
|
|
994
|
+
'Without subagents, process slots in turn with a distinct agent name per slot (e.g. "slot1-agent", "slot2-agent"); the same agent name operating another slot within 60s is refused.';
|
|
932
995
|
function genericInstructions() {
|
|
933
996
|
return INSTRUCTIONS_CLAUDE_CODE
|
|
934
997
|
.split('\n')
|
|
935
998
|
// Claude Code 전용 병렬 처리 안내(Agent 도구·cdpm-browser) → 일반 안내로
|
|
936
|
-
.map((l) => (l.startsWith('-
|
|
937
|
-
.map((l) => l.replace('
|
|
999
|
+
.map((l) => (l.startsWith('- Different jobs on multiple slots') ? GENERIC_PARALLEL : l))
|
|
1000
|
+
.map((l) => l.replace('Start subagents first; each, without touching', '(With subagents, start them first.) Each agent, without touching'))
|
|
1001
|
+
.map((l) => l.replace('hand them to a background subagent (run_in_background: true)', 'hand them to a subagent or background task'))
|
|
938
1002
|
.join('\n');
|
|
939
1003
|
}
|
|
940
1004
|
/** 클라이언트에 맞는 서버 안내 (initialize 때 정한다). */
|