cdpm-mcp 0.1.4 → 0.1.5
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 +7 -0
- package/README.ko.md +1 -0
- package/README.md +1 -0
- package/dist/agent-setup.js +16 -14
- 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/finder.js +2 -2
- package/dist/chrome/launcher.js +5 -5
- package/dist/chrome/proxy.js +4 -4
- package/dist/claude-md-setup.js +19 -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/tools/format.js +12 -12
- package/dist/tools/read.js +10 -10
- package/dist/tools/register.js +301 -298
- package/dist/util.js +5 -5
- package/package.json +1 -1
package/dist/tools/register.js
CHANGED
|
@@ -16,7 +16,7 @@ import { hasUnread, recentDelivered, sendMessage, takeUnread, waitUnread } from
|
|
|
16
16
|
import { readRegistry, updateRegistry } from '../registry/store.js';
|
|
17
17
|
import { attachSlot, forgetSlot, freeSlots, launchSlot, liveSlots, markCreated, ownershipWarnings, pickTab, recordAction, syncTabs, } from '../service.js';
|
|
18
18
|
import { MAX_SLOT, MIN_SLOT, PORT_BASE, portOf } from '../slots.js';
|
|
19
|
-
import { ago, decodeUrl,
|
|
19
|
+
import { ago, decodeUrl, nowIso, pidAlive, secondsSince, shortUrl, sleep, truncate } from '../util.js';
|
|
20
20
|
import { formatHeader, formatMessages, formatSlotStatus } from './format.js';
|
|
21
21
|
import { readAfter } from './read.js';
|
|
22
22
|
/** 에이전트가 마지막으로 다룬 탭 (보기 도구에서 tab을 생략했을 때 우선). key: `${slot}:${agent}` */
|
|
@@ -38,36 +38,36 @@ function multiSlotRefusal(agent, slot, allowed) {
|
|
|
38
38
|
const others = [...m.keys()].filter((k) => k !== slot).sort((x, y) => x - y);
|
|
39
39
|
if (others.length && !allowed) {
|
|
40
40
|
const how = isClaudeCode()
|
|
41
|
-
?
|
|
42
|
-
|
|
43
|
-
:
|
|
44
|
-
return
|
|
45
|
-
|
|
41
|
+
? `For different jobs per slot, call the Agent tool once per slot in a single message to launch subagents (subagent_type "cdpm-browser") together, ` +
|
|
42
|
+
`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. `
|
|
43
|
+
: `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"). `;
|
|
44
|
+
return `Refused: ${agent} just used slot ${others.join(', ')}, so it won't take slot ${slot}. ` + how +
|
|
45
|
+
`If one agent must handle several slots together (e.g. comparing), call again with multiSlot: true.`;
|
|
46
46
|
}
|
|
47
47
|
m.set(slot, now);
|
|
48
48
|
recentSlots.set(agent, m);
|
|
49
49
|
return undefined;
|
|
50
50
|
}
|
|
51
51
|
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(
|
|
52
|
+
const SLOT_RANGE = `slot must be a number ${MIN_SLOT}-${MAX_SLOT}`;
|
|
53
|
+
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)
|
|
54
|
+
.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
55
|
const agentArg = z.string().min(1).max(40).optional()
|
|
56
|
-
.describe(
|
|
56
|
+
.describe(`Your display name, shown to other agents. Subagents must always set it. Default "${DEFAULT_AGENT}".`);
|
|
57
57
|
const tabArg = z.union([z.string(), z.number()]).optional()
|
|
58
|
-
.describe('
|
|
58
|
+
.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
59
|
const summaryArg = z.string().max(120).optional()
|
|
60
|
-
.describe('
|
|
60
|
+
.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
61
|
const multiSlotArg = z.boolean().optional()
|
|
62
|
-
.describe('
|
|
62
|
+
.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
63
|
const readArg = z.enum(['text', 'snapshot', 'changes']).optional()
|
|
64
|
-
.describe('
|
|
65
|
-
const pageArg = z.number().int().min(1).optional().describe('
|
|
64
|
+
.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)');
|
|
65
|
+
const pageArg = z.number().int().min(1).optional().describe('Page number for long output (default 1)');
|
|
66
66
|
const textResult = (text, isError = false) => ({ content: [{ type: 'text', text }], ...(isError ? { isError } : {}) });
|
|
67
67
|
function errorText(e) {
|
|
68
68
|
if (e instanceof CdpmError)
|
|
69
69
|
return e.message;
|
|
70
|
-
return
|
|
70
|
+
return `Error: ${e?.message ?? String(e)}`;
|
|
71
71
|
}
|
|
72
72
|
/** 탭에 걸린 요청 막기 규칙 중, 건 프로세스가 아직 살아 있는 것. */
|
|
73
73
|
function liveBlocks(tab) {
|
|
@@ -99,7 +99,7 @@ async function header(slot, agent, tabs, opts = {}) {
|
|
|
99
99
|
for (const t of tabs) {
|
|
100
100
|
const blocks = liveBlocks(t);
|
|
101
101
|
if (blocks.length)
|
|
102
|
-
warnings.push(`[${t.id}]
|
|
102
|
+
warnings.push(`[${t.id}] blocking requests: ${blocks.map((b) => `${b.pattern} (${b.agent})`).join(', ')}`);
|
|
103
103
|
}
|
|
104
104
|
const dialogs = dialogsOf(slot, tabs);
|
|
105
105
|
// 탭 목록이 이 에이전트가 지난번에 본 것과 같고 경고·알림창·메시지도 없으면 한 줄로 (읽을 양을 줄여 다음 판단이 빨라지게)
|
|
@@ -111,7 +111,7 @@ async function header(slot, agent, tabs, opts = {}) {
|
|
|
111
111
|
lastTabList.set(key, sig);
|
|
112
112
|
if (opts.compact && same && !warnings.length && !messages.length && !dialogs.size) {
|
|
113
113
|
const exec = tabs.find((t) => t.targetId === opts.executed);
|
|
114
|
-
return `[${slot}
|
|
114
|
+
return `[Slot ${slot}] ${tabs.length} tab(s)${exec ? ` · ran on tab ${exec.no} [${exec.id}]` : ''} (tab list unchanged)`;
|
|
115
115
|
}
|
|
116
116
|
return formatHeader({ slot, tabs, executedTargetId: opts.executed, warnings, dialogs, messages });
|
|
117
117
|
}
|
|
@@ -184,7 +184,7 @@ async function onTab(args, kind, action, fn, opts = {}) {
|
|
|
184
184
|
// 행동 도중 알림창이 뜬 것은 실패가 아니다 (클릭은 이루어졌음).
|
|
185
185
|
if (!(e instanceof act.DialogInterrupt))
|
|
186
186
|
throw e;
|
|
187
|
-
out = { text:
|
|
187
|
+
out = { text: `Action done. Then: ${e.message}` };
|
|
188
188
|
}
|
|
189
189
|
tabs = await syncTabs(slot).catch(() => tabs);
|
|
190
190
|
if (action) {
|
|
@@ -192,17 +192,17 @@ async function onTab(args, kind, action, fn, opts = {}) {
|
|
|
192
192
|
const acted = tabs.find((t) => t.targetId === tab.targetId);
|
|
193
193
|
const ok = await recordAction(slot, tab.targetId, agent, action, args.summary, !args.agent, acted ? acted.title || shortUrl(acted.url) : undefined);
|
|
194
194
|
if (!ok)
|
|
195
|
-
warnings.push('
|
|
195
|
+
warnings.push('Not logged: could not lock the shared registry, so this action was not recorded.');
|
|
196
196
|
}
|
|
197
197
|
const opened = tabs.filter((t) => !before.has(t.targetId));
|
|
198
198
|
if (opened.length) {
|
|
199
|
-
out.text += `\
|
|
199
|
+
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
200
|
}
|
|
201
201
|
if (action && !session.dialog) {
|
|
202
202
|
// 클릭 등으로 페이지가 전체 화면이 되면 사용자 창 상태가 바뀌므로 바로 해제한다.
|
|
203
203
|
const fs = await session.evaluate('(() => { if (!document.fullscreenElement) return false; document.exitFullscreen(); return true; })()', { timeoutMs: 1500 }).catch(() => undefined);
|
|
204
204
|
if (fs?.value)
|
|
205
|
-
out.text += '\n[
|
|
205
|
+
out.text += '\n[warning] The page went fullscreen; exited it right away (CDPM never changes window state).';
|
|
206
206
|
}
|
|
207
207
|
return compose(await header(slot, agent, tabs, { executed: tab.targetId, warnings, compact: true }), out);
|
|
208
208
|
}
|
|
@@ -222,8 +222,8 @@ async function guard(fn) {
|
|
|
222
222
|
function pageFooter(p, total, extra = '') {
|
|
223
223
|
if (p.pages <= 1)
|
|
224
224
|
return '';
|
|
225
|
-
const next = p.page < p.pages ? ` ·
|
|
226
|
-
return `\n\n— ${p.page}/${p.pages}
|
|
225
|
+
const next = p.page < p.pages ? ` · next: page=${p.page + 1}` : ' · last page';
|
|
226
|
+
return `\n\n— page ${p.page}/${p.pages} (${total.toLocaleString()} chars total)${next}${extra}`;
|
|
227
227
|
}
|
|
228
228
|
// ---------- 네트워크 표시 ----------
|
|
229
229
|
function fmtSize(n) {
|
|
@@ -238,8 +238,8 @@ function fmtSize(n) {
|
|
|
238
238
|
function netLine(e, rules = []) {
|
|
239
239
|
const blockedBy = e.blockedBy ?? (e.failed && /BLOCKED_BY_CLIENT/.test(e.failed) ? rules.find((r) => wildcard(r.pattern).test(e.url))?.pattern : undefined);
|
|
240
240
|
const status = e.failed
|
|
241
|
-
?
|
|
242
|
-
: e.status !== undefined ? String(e.status) + (e.fromCache ? ' (
|
|
241
|
+
? `failed ${e.failed}${blockedBy ? ` (blocked: ${blockedBy})` : ''}`
|
|
242
|
+
: e.status !== undefined ? String(e.status) + (e.fromCache ? ' (cache)' : '') : '…';
|
|
243
243
|
const parts = [`n${e.no}`, e.method, status, e.type, fmtSize(e.size), e.durationMs !== undefined ? `${e.durationMs}ms` : ''].filter(Boolean);
|
|
244
244
|
return `${parts.join(' ')} ${truncate(decodeUrl(e.url), 140)}`;
|
|
245
245
|
}
|
|
@@ -247,15 +247,15 @@ function netLine(e, rules = []) {
|
|
|
247
247
|
async function responseBody(s, e) {
|
|
248
248
|
const b = await s.send('Network.getResponseBody', { requestId: e.requestId }, 10_000).catch(() => undefined);
|
|
249
249
|
if (!b)
|
|
250
|
-
return ' (
|
|
250
|
+
return ' (unavailable: still loading, already discarded by Chrome, or a redirect)';
|
|
251
251
|
if (b.base64Encoded && !/json|text|xml|javascript|html/i.test(e.mimeType ?? ''))
|
|
252
|
-
return ` (
|
|
252
|
+
return ` (binary ${fmtSize(Buffer.from(b.body, 'base64').length)}, ${e.mimeType})`;
|
|
253
253
|
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… (
|
|
254
|
+
return raw.length > 20_000 ? raw.slice(0, 20_000) + `\n… (truncated: ${raw.length.toLocaleString()} chars total)` : raw;
|
|
255
255
|
}
|
|
256
256
|
function headersText(h) {
|
|
257
257
|
if (!h)
|
|
258
|
-
return ' (
|
|
258
|
+
return ' (none)';
|
|
259
259
|
return Object.entries(h).map(([k, v]) => ` ${k}: ${truncate(String(v), 300)}`).join('\n');
|
|
260
260
|
}
|
|
261
261
|
/** 도메인만 적으면 그 주소가 들어간 모든 요청으로 넓힌다. */
|
|
@@ -269,14 +269,14 @@ function normalizePattern(p) {
|
|
|
269
269
|
export function registerTools(server) {
|
|
270
270
|
// ---------- 슬롯·탭 ----------
|
|
271
271
|
server.registerTool('browser_status', {
|
|
272
|
-
title: '
|
|
273
|
-
description: '
|
|
272
|
+
title: 'Slot status',
|
|
273
|
+
description: 'Shows running Chrome slots (1-30) with their tabs, opener, last action and one-line summary. Pass slot for just that slot.',
|
|
274
274
|
inputSchema: { slot: slotArg.optional(), agent: agentArg },
|
|
275
275
|
}, async ({ slot, agent }) => guard(async () => {
|
|
276
276
|
const live = await liveSlots();
|
|
277
277
|
const target = slot ? live.filter(([s]) => s === slot) : live;
|
|
278
278
|
if (!target.length)
|
|
279
|
-
return textResult(slot ?
|
|
279
|
+
return textResult(slot ? `Slot ${slot} Chrome is not running.` : 'No slots running. Start one with browser_launch when the user asks.');
|
|
280
280
|
const parts = [];
|
|
281
281
|
for (const [s] of target) {
|
|
282
282
|
const tabs = await syncTabs(s).catch(() => null);
|
|
@@ -285,30 +285,30 @@ export function registerTools(server) {
|
|
|
285
285
|
for (const t of tabs ?? []) {
|
|
286
286
|
const d = knownDialog(s, t.targetId);
|
|
287
287
|
if (d)
|
|
288
|
-
part += `\n [
|
|
288
|
+
part += `\n [warning] dialog open (${d.type}) ([${t.id}]): "${truncate(d.message, 80)}"`;
|
|
289
289
|
}
|
|
290
290
|
parts.push(part);
|
|
291
291
|
}
|
|
292
292
|
const me = agent ?? DEFAULT_AGENT;
|
|
293
|
-
return textResult(`${parts.join('\n\n')}\n\n(
|
|
293
|
+
return textResult(`${parts.join('\n\n')}\n\n(your name: ${me})`);
|
|
294
294
|
}));
|
|
295
295
|
server.registerTool('browser_launch', {
|
|
296
|
-
title: '
|
|
297
|
-
description: '
|
|
298
|
-
'slot
|
|
299
|
-
'
|
|
300
|
-
'
|
|
301
|
-
'
|
|
296
|
+
title: 'Launch slot',
|
|
297
|
+
description: 'Starts slot Chrome. Call only when the user explicitly asks (other tools never start a closed slot). ' +
|
|
298
|
+
'Without slot, uses the lowest free slot. If already running, just attaches. ' +
|
|
299
|
+
'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. ' +
|
|
300
|
+
'Starting a closed slot without headless only returns a confirmation request. ' +
|
|
301
|
+
'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
302
|
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('
|
|
303
|
+
slot: slotArg.optional().describe('One slot to start (1-30). Omit if the user gave no number → lowest free slot'),
|
|
304
|
+
slots: z.array(slotArg).optional().describe('Slot numbers to start at once (e.g. [1,2,3]), lowest first'),
|
|
305
|
+
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'),
|
|
306
|
+
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'),
|
|
307
|
+
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
308
|
agent: agentArg,
|
|
309
|
-
headless: z.boolean().optional().describe('false =
|
|
310
|
-
proxy: z.string().optional().describe('
|
|
311
|
-
proxies: z.array(z.string()).optional().describe('
|
|
309
|
+
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'),
|
|
310
|
+
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'),
|
|
311
|
+
proxies: z.array(z.string()).optional().describe('Per-slot proxies, paired in slots order (count: launch order)'),
|
|
312
312
|
},
|
|
313
313
|
}, async ({ slot: wanted, slots: wantedList, count, agent, headless, url, urls, proxy, proxies }) => guard(async () => {
|
|
314
314
|
const me = agent ?? DEFAULT_AGENT;
|
|
@@ -321,7 +321,7 @@ export function registerTools(server) {
|
|
|
321
321
|
else {
|
|
322
322
|
targets = await freeSlots(count ?? 1);
|
|
323
323
|
if (targets.length < (count ?? 1)) {
|
|
324
|
-
throw new CdpmError(
|
|
324
|
+
throw new CdpmError(`Only ${targets.length} free slot(s) (requested ${count ?? 1}). Close unused slots with browser_close.`);
|
|
325
325
|
}
|
|
326
326
|
}
|
|
327
327
|
// 시작 주소: urls는 slots에 준 순서(없으면 켜지는 번호 순서)대로, 나머지는 url
|
|
@@ -336,7 +336,7 @@ export function registerTools(server) {
|
|
|
336
336
|
for (const u of startUrl.values()) {
|
|
337
337
|
const ext = act.externalScheme(u);
|
|
338
338
|
if (ext)
|
|
339
|
-
throw new CdpmError(
|
|
339
|
+
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
340
|
}
|
|
341
341
|
targets.sort((x, y) => x - y);
|
|
342
342
|
// 모드를 사용자가 정하지 않았으면 꺼진 슬롯은 켜지 않는다 (이미 떠 있으면 그대로 붙는다).
|
|
@@ -344,8 +344,8 @@ export function registerTools(server) {
|
|
|
344
344
|
const states = await Promise.all(targets.map((t) => probe(t)));
|
|
345
345
|
const closed = targets.filter((_, i) => states[i].state !== 'chrome');
|
|
346
346
|
if (closed.length) {
|
|
347
|
-
return textResult(`[
|
|
348
|
-
`headless(
|
|
347
|
+
return textResult(`[Confirm] Slot ${closed.join(', ')} not started yet. Ask the user once: visible window or headless (hidden)? ` +
|
|
348
|
+
`Then call again with headless (windowed false, headless true).`);
|
|
349
349
|
}
|
|
350
350
|
}
|
|
351
351
|
// 작은 번호부터 차례로 켠다 (작업표시줄에도 그 순서로 놓인다). 한 번의 호출로 끝내서 왕복을 줄인다.
|
|
@@ -355,55 +355,54 @@ export function registerTools(server) {
|
|
|
355
355
|
const { launched } = await launchSlot(slot, me, { headless, url: startUrl.get(slot), proxy: proxyOf.get(slot) });
|
|
356
356
|
anyLaunched ||= launched;
|
|
357
357
|
if (launched)
|
|
358
|
-
await recordAction(slot, '', me, '
|
|
358
|
+
await recordAction(slot, '', me, 'launch', undefined, !agent);
|
|
359
359
|
const running = readRegistry().slots[String(slot)];
|
|
360
|
-
const mode = running?.headless ? '
|
|
361
|
-
const via = running?.proxy ? `,
|
|
362
|
-
let line = launched ?
|
|
360
|
+
const mode = running?.headless ? 'headless' : 'windowed';
|
|
361
|
+
const via = running?.proxy ? `, proxy ${running.proxy}` : '';
|
|
362
|
+
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
363
|
if (!launched && headless !== undefined && headless !== !!running?.headless) {
|
|
364
|
-
line += ` [
|
|
364
|
+
line += ` [warning] Already running ${mode}, attached as is. To change, browser_close then launch again.`;
|
|
365
365
|
}
|
|
366
366
|
const askedProxy = proxyOf.get(slot);
|
|
367
367
|
if (!launched && askedProxy && running?.proxy !== describeProxy(askedProxy)) {
|
|
368
|
-
line += ` [
|
|
368
|
+
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
369
|
}
|
|
370
370
|
lines.push(line);
|
|
371
371
|
}
|
|
372
372
|
let msg = lines.join('\n');
|
|
373
373
|
if (anyLaunched && picked) {
|
|
374
|
-
msg += targets.length === 1 ? '\
|
|
374
|
+
msg += targets.length === 1 ? '\nNo number given; picked the lowest free slot.' : '\nNo numbers given; picked free slots, lowest first.';
|
|
375
375
|
}
|
|
376
376
|
if (targets.length > 1 && !isClaudeCode()) {
|
|
377
|
-
msg += '\n[
|
|
378
|
-
'
|
|
377
|
+
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"). ' +
|
|
378
|
+
'If the user must log in, don\'t ask them to "tell me when done"; detect completion with browser_wait url/gone/text.';
|
|
379
379
|
}
|
|
380
380
|
if (targets.length > 1 && isClaudeCode()) {
|
|
381
|
-
msg += '\n[
|
|
382
|
-
'(
|
|
383
|
-
'
|
|
381
|
+
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 ' +
|
|
382
|
+
'(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. ' +
|
|
383
|
+
'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
384
|
if (targets.length > 20) {
|
|
385
|
-
msg += `\n[
|
|
386
|
-
'
|
|
385
|
+
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. ` +
|
|
386
|
+
'To launch all at once, the user must raise the env var CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS.';
|
|
387
387
|
}
|
|
388
388
|
}
|
|
389
389
|
const first = targets[0];
|
|
390
390
|
return textResult(`${await header(first, me, await syncTabs(first))}\n---\n${msg}`);
|
|
391
391
|
}));
|
|
392
392
|
server.registerTool('browser_close', {
|
|
393
|
-
title: '
|
|
394
|
-
description: '
|
|
393
|
+
title: 'Close slot',
|
|
394
|
+
description: 'Closes slot Chrome cleanly (session and cookies saved). The profile (logins) is kept. Reports if another agent used it recently.',
|
|
395
395
|
inputSchema: { slot: slotArg, agent: agentArg },
|
|
396
396
|
}, async ({ slot, agent }) => guard(() => withSlotLock(slot, async () => {
|
|
397
397
|
const me = agent ?? DEFAULT_AGENT;
|
|
398
398
|
if ((await probe(slot)).state !== 'chrome') {
|
|
399
399
|
await forgetSlot(slot);
|
|
400
|
-
return textResult(
|
|
400
|
+
return textResult(`Slot ${slot} Chrome is already closed.`);
|
|
401
401
|
}
|
|
402
402
|
const rec = readRegistry().slots[String(slot)];
|
|
403
403
|
const warnings = [];
|
|
404
404
|
if (rec?.last && rec.last.agent !== me && secondsSince(rec.last.at) <= 120) {
|
|
405
|
-
|
|
406
|
-
warnings.push(`${josa(rec.last.agent, '이', '가')} ${when === '방금' ? when : `${when}에`} 이 슬롯을 썼어요.`);
|
|
405
|
+
warnings.push(`${rec.last.agent} used this slot (${ago(rec.last.at)}).`);
|
|
407
406
|
}
|
|
408
407
|
const browser = await browserConnection(slot);
|
|
409
408
|
await browser.send('Browser.close', {}, 5000).catch(() => undefined);
|
|
@@ -413,11 +412,11 @@ export function registerTools(server) {
|
|
|
413
412
|
for (let i = 0; rec?.pid && i < 50 && pidAlive(rec.pid); i++)
|
|
414
413
|
await sleep(100);
|
|
415
414
|
await forgetSlot(slot);
|
|
416
|
-
return textResult([...warnings,
|
|
415
|
+
return textResult([...warnings, `Closed slot ${slot} Chrome. The profile is kept, so logins persist next launch.`].join('\n'));
|
|
417
416
|
})));
|
|
418
417
|
server.registerTool('browser_tabs', {
|
|
419
|
-
title: '
|
|
420
|
-
description: '
|
|
418
|
+
title: 'List tabs',
|
|
419
|
+
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
420
|
inputSchema: { slot: slotArg, agent: agentArg },
|
|
422
421
|
}, async ({ slot, agent }) => guard(async () => {
|
|
423
422
|
const me = agent ?? DEFAULT_AGENT;
|
|
@@ -425,13 +424,13 @@ export function registerTools(server) {
|
|
|
425
424
|
const tabs = await syncTabs(slot);
|
|
426
425
|
const head = await header(slot, me, tabs);
|
|
427
426
|
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') : '
|
|
427
|
+
.map((t) => `${t.no}. [${t.id}] summary: ${t.rec.summary.agent} — ${t.rec.summary.text} (${ago(t.rec.summary.at)})`);
|
|
428
|
+
return textResult(`${head}\n---\n${detail.length ? detail.join('\n') : 'No per-tab summaries'}`);
|
|
430
429
|
}));
|
|
431
430
|
server.registerTool('browser_tab_new', {
|
|
432
|
-
title: '
|
|
433
|
-
description: '
|
|
434
|
-
inputSchema: { slot: slotArg, agent: agentArg, url: z.string().optional().describe('
|
|
431
|
+
title: 'New tab',
|
|
432
|
+
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.',
|
|
433
|
+
inputSchema: { slot: slotArg, agent: agentArg, url: z.string().optional().describe('URL to open (omit for blank tab)'), summary: summaryArg },
|
|
435
434
|
}, async ({ slot, agent, url, summary }) => guard(async () => {
|
|
436
435
|
const me = agent ?? DEFAULT_AGENT;
|
|
437
436
|
const paused = pausedRefusal(slot);
|
|
@@ -442,21 +441,21 @@ export function registerTools(server) {
|
|
|
442
441
|
const target = url ? (/^[a-z][a-z0-9+.-]*:/i.test(url) ? url : `https://${url}`) : 'about:blank';
|
|
443
442
|
const ext = act.externalScheme(target);
|
|
444
443
|
if (ext)
|
|
445
|
-
throw new CdpmError(
|
|
444
|
+
throw new CdpmError(`Can't open a ${ext} URL (${target.slice(0, 80)}) (it would launch another program on the user's PC).`);
|
|
446
445
|
// background: 사용자가 보고 있는 탭을 바꾸지 않는다.
|
|
447
446
|
const { targetId } = await browser.send('Target.createTarget', { url: target, background: true });
|
|
448
447
|
markCreated(targetId, me);
|
|
449
448
|
lastTabOf.set(`${slot}:${me}`, targetId);
|
|
450
449
|
await syncTabs(slot);
|
|
451
|
-
await recordAction(slot, targetId, me, '
|
|
450
|
+
await recordAction(slot, targetId, me, 'open tab', summary);
|
|
452
451
|
const tabs = await syncTabs(slot);
|
|
453
452
|
const tab = tabs.find((t) => t.targetId === targetId);
|
|
454
|
-
return compose(await header(slot, me, tabs, { executed: targetId }), { text:
|
|
453
|
+
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
454
|
}));
|
|
456
455
|
server.registerTool('browser_tab_close', {
|
|
457
|
-
title: '
|
|
458
|
-
description: '
|
|
459
|
-
inputSchema: { slot: slotArg, agent: agentArg, tab: z.union([z.string(), z.number()]).describe('
|
|
456
|
+
title: 'Close tab',
|
|
457
|
+
description: 'Closes a tab. tab is required.',
|
|
458
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: z.union([z.string(), z.number()]).describe('Tab to close: number or ID ("t7")') },
|
|
460
459
|
}, async ({ slot, agent, tab }) => guard(async () => {
|
|
461
460
|
const me = agent ?? DEFAULT_AGENT;
|
|
462
461
|
const paused = pausedRefusal(slot);
|
|
@@ -472,30 +471,30 @@ export function registerTools(server) {
|
|
|
472
471
|
await browser.send('Target.closeTarget', { targetId: picked.tab.targetId });
|
|
473
472
|
await sleep(200);
|
|
474
473
|
tabs = await syncTabs(slot);
|
|
475
|
-
return textResult(`${await header(slot, me, tabs, { warnings })}\n---\
|
|
474
|
+
return textResult(`${await header(slot, me, tabs, { warnings })}\n---\nClosed tab: tab ${picked.tab.no} [${picked.tab.id}] ${picked.tab.title}`);
|
|
476
475
|
}));
|
|
477
476
|
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', '
|
|
477
|
+
title: 'Bring tab to front',
|
|
478
|
+
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.)',
|
|
479
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: z.union([z.string(), z.number()]).describe('Tab to bring forward: number or ID') },
|
|
480
|
+
}, async (args) => onTab(args, 'action', 'select tab', async (s, tab) => {
|
|
482
481
|
const browser = await browserConnection(s.slot);
|
|
483
482
|
await browser.send('Target.activateTarget', { targetId: tab.targetId });
|
|
484
483
|
forgetSlotVisibility(s.slot);
|
|
485
484
|
await sleep(150);
|
|
486
|
-
return { text:
|
|
485
|
+
return { text: `Brought tab ${tab.no} [${tab.id}] to front.` };
|
|
487
486
|
}));
|
|
488
487
|
// ---------- 보기 ----------
|
|
489
488
|
server.registerTool('browser_snapshot', {
|
|
490
|
-
title: '
|
|
491
|
-
description: '
|
|
492
|
-
'
|
|
493
|
-
'find="
|
|
489
|
+
title: 'Snapshot',
|
|
490
|
+
description: 'Reads the tab as accessibility-tree text. Clickable/typable elements get refs like [e12]. ' +
|
|
491
|
+
'Long pages are split; only page 1 (top) is shown (page=2 to continue; refs stay the same across pages). ' +
|
|
492
|
+
'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
493
|
inputSchema: {
|
|
495
494
|
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('
|
|
495
|
+
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"'),
|
|
496
|
+
interactive: z.boolean().optional().describe('Only actionable elements (lines with refs): inputs, buttons, links. Use first to find inputs on big pages like Gmail'),
|
|
497
|
+
ref: z.string().optional().describe('Only this ref element and its subtree'),
|
|
499
498
|
},
|
|
500
499
|
}, async (args) => onTab(args, 'view', null, async (s, tab, agent) => {
|
|
501
500
|
const page = args.page ?? 1;
|
|
@@ -506,92 +505,92 @@ export function registerTools(server) {
|
|
|
506
505
|
// interactive: ref가 붙은 줄(조작할 수 있는 요소와 제목)만 → 큰 페이지에서도 몇 쪽 안에 입력칸·버튼이 다 보인다
|
|
507
506
|
const text = args.interactive ? full.split('\n').filter((l) => /\[e\d+\]/.test(l)).map((l) => l.trimStart()).join('\n') : full;
|
|
508
507
|
if (!text)
|
|
509
|
-
return { text: '(
|
|
508
|
+
return { text: '(no readable elements)' };
|
|
510
509
|
if (args.ref) {
|
|
511
510
|
const sub = subtree(text, args.ref);
|
|
512
511
|
if (!sub)
|
|
513
|
-
throw new CdpmError(`[${args.ref}]
|
|
512
|
+
throw new CdpmError(`[${args.ref}] not found in this snapshot. Re-snapshot without ref to check.`);
|
|
514
513
|
const p = paginate(sub, page);
|
|
515
514
|
return { text: p.body + pageFooter(p, sub.length) };
|
|
516
515
|
}
|
|
517
516
|
if (args.find) {
|
|
518
517
|
const f = findLines(text, args.find);
|
|
519
518
|
if (!f.matches)
|
|
520
|
-
return { text: `"${args.find}"
|
|
519
|
+
return { text: `No elements contain "${args.find}". (${text.length.toLocaleString()} chars total)` };
|
|
521
520
|
const p = paginate(f.body, page);
|
|
522
|
-
return { text: `${p.body}\n\n— "${args.find}" ${f.matches}
|
|
521
|
+
return { text: `${p.body}\n\n— "${args.find}": ${f.matches} match(es)${f.matches > 150 ? ' (first 150 shown)' : ''}${pageFooter(p, f.body.length)}` };
|
|
523
522
|
}
|
|
524
523
|
const p = paginate(text, page);
|
|
525
524
|
const context = p.page > 1 ? ancestorsOf(text, p.start) : [];
|
|
526
|
-
const head = context.length ? `(
|
|
527
|
-
return { text: head + p.body + pageFooter(p, text.length, ` ·
|
|
525
|
+
const head = context.length ? `(parent context of this page)\n${context.join('\n')}\n ┄┄┄\n` : '';
|
|
526
|
+
return { text: head + p.body + pageFooter(p, text.length, ` · search: find="…" · region: ref="eN"${args.interactive ? '' : ' · inputs/buttons only: interactive=true'}`) };
|
|
528
527
|
}));
|
|
529
528
|
server.registerTool('browser_text', {
|
|
530
|
-
title: '
|
|
531
|
-
description: '
|
|
532
|
-
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, ref: z.string().optional().describe('
|
|
529
|
+
title: 'Read text',
|
|
530
|
+
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.',
|
|
531
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, ref: z.string().optional().describe('Only this element\'s text'), page: pageArg },
|
|
533
532
|
}, async (args) => onTab(args, 'view', null, async (s, _tab, agent) => ({ text: await act.extractText(s, agent, args.ref, args.page ?? 1) })));
|
|
534
533
|
server.registerTool('browser_screenshot', {
|
|
535
|
-
title: '
|
|
536
|
-
description: '
|
|
534
|
+
title: 'Screenshot',
|
|
535
|
+
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
536
|
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg },
|
|
538
537
|
}, async (args) => onTab(args, 'view', null, async (s) => {
|
|
539
538
|
const data = await act.screenshot(s, await browserConnection(s.slot));
|
|
540
|
-
return { text: '
|
|
539
|
+
return { text: 'Captured.', image: data };
|
|
541
540
|
}, { render: true }));
|
|
542
541
|
// ---------- 조작 ----------
|
|
543
542
|
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', '
|
|
543
|
+
title: 'Navigate',
|
|
544
|
+
description: 'Navigates the tab to a URL and waits for the body to load.',
|
|
545
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, url: z.string().describe('URL to go to'), read: readArg, summary: summaryArg },
|
|
546
|
+
}, async (args) => onTab(args, 'action', 'navigate', async (s) => ({ text: (await act.navigate(s, args.url)) + act.downloadNote(s) })));
|
|
548
547
|
server.registerTool('browser_back', {
|
|
549
|
-
title: '
|
|
550
|
-
description: '
|
|
548
|
+
title: 'Back',
|
|
549
|
+
description: 'Go back.',
|
|
551
550
|
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, read: readArg, summary: summaryArg },
|
|
552
|
-
}, async (args) => onTab(args, 'action', '
|
|
551
|
+
}, async (args) => onTab(args, 'action', 'back', async (s) => ({ text: await act.back(s) })));
|
|
553
552
|
server.registerTool('browser_forward', {
|
|
554
|
-
title: '
|
|
555
|
-
description: '
|
|
553
|
+
title: 'Forward',
|
|
554
|
+
description: 'Go forward (after going back).',
|
|
556
555
|
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, read: readArg, summary: summaryArg },
|
|
557
|
-
}, async (args) => onTab(args, 'action', '
|
|
556
|
+
}, async (args) => onTab(args, 'action', 'forward', async (s) => ({ text: await act.forward(s) })));
|
|
558
557
|
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', '
|
|
558
|
+
title: 'Reload',
|
|
559
|
+
description: 'Reloads the page (same as Chrome reload). ignore_cache=true bypasses the cache. Careful: unsaved user input on the page is lost.',
|
|
560
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, ignore_cache: z.boolean().optional().describe('Bypass cache (hard reload)'), read: readArg, summary: summaryArg },
|
|
561
|
+
}, async (args) => onTab(args, 'action', 'reload', async (s) => ({ text: await act.reload(s, args.ignore_cache ?? false) })));
|
|
563
562
|
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', '
|
|
563
|
+
title: 'Handle dialog',
|
|
564
|
+
description: 'Accepts (accept: true) or dismisses (accept: false) an open dialog (alert/confirm/prompt/beforeunload). The tab is frozen while a dialog is open. ' +
|
|
565
|
+
'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.). ' +
|
|
566
|
+
'beforeunload: accept = leave page (input lost), dismiss = stay. For prompt, text is the input.',
|
|
567
|
+
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 },
|
|
568
|
+
}, async (args) => onTab(args, 'action', 'dialog', async (s) => ({ text: await act.handleDialog(s, args.accept, args.text) }), { render: false }));
|
|
570
569
|
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', '
|
|
570
|
+
title: 'Hover',
|
|
571
|
+
description: 'Moves the real mouse over a ref element (no click). For hover menus and tooltips. Use read=changes to see the opened menu.',
|
|
572
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, ref: z.string().describe('ref of the element to hover'), read: readArg, summary: summaryArg },
|
|
573
|
+
}, async (args) => onTab(args, 'action', 'hover', async (s, _tab, agent) => ({ text: await act.hover(s, agent, args.ref) })));
|
|
575
574
|
server.registerTool('browser_drag', {
|
|
576
|
-
title: '
|
|
577
|
-
description: '
|
|
578
|
-
'
|
|
575
|
+
title: 'Drag',
|
|
576
|
+
description: 'Drags with the real mouse (press → move in steps → release): drag and drop, sliders, reordering, drag CAPTCHAs, etc. ' +
|
|
577
|
+
'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
578
|
inputSchema: {
|
|
580
579
|
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('
|
|
580
|
+
from: z.string().describe('ref of the element to drag (including ones marked draggable)'), to: z.string().optional().describe('ref of the drop target'),
|
|
581
|
+
to_text: z.string().optional().describe('Text shown at the drop spot (when it has no ref, e.g. "Drop here")'),
|
|
582
|
+
dx: z.number().optional().describe('Horizontal pixels (right +)'), dy: z.number().optional().describe('Vertical pixels (down +)'),
|
|
584
583
|
read: readArg, summary: summaryArg,
|
|
585
584
|
},
|
|
586
|
-
}, async (args) => onTab(args, 'action', '
|
|
585
|
+
}, 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
586
|
server.registerTool('browser_download_wait', {
|
|
588
|
-
title: '
|
|
589
|
-
description: '
|
|
590
|
-
inputSchema: { slot: slotArg, agent: agentArg, timeout: z.number().min(1).max(600).optional().describe('
|
|
587
|
+
title: 'Wait for download',
|
|
588
|
+
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.',
|
|
589
|
+
inputSchema: { slot: slotArg, agent: agentArg, timeout: z.number().min(1).max(600).optional().describe('Max wait in seconds (default 120)') },
|
|
591
590
|
}, async ({ slot, agent, timeout }) => guard(async () => {
|
|
592
591
|
const me = agent ?? DEFAULT_AGENT;
|
|
593
592
|
await attachSlot(slot);
|
|
594
|
-
const stop = () => (hasUnread(slot, me) ? '
|
|
593
|
+
const stop = () => (hasUnread(slot, me) ? 'Stopped waiting: a new message arrived (check with slot_inbox).' : undefined);
|
|
595
594
|
try {
|
|
596
595
|
return textResult(await waitDownload(slot, timeout ?? 120, stop));
|
|
597
596
|
}
|
|
@@ -600,133 +599,133 @@ export function registerTools(server) {
|
|
|
600
599
|
}
|
|
601
600
|
}));
|
|
602
601
|
server.registerTool('browser_pdf', {
|
|
603
|
-
title: 'PDF
|
|
604
|
-
description: '
|
|
605
|
-
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, path: z.string().optional().describe('
|
|
602
|
+
title: 'Save as PDF',
|
|
603
|
+
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.',
|
|
604
|
+
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
605
|
}, async (args) => onTab(args, 'view', null, async (s, tab) => ({ text: await act.pdf(s, args.path, tab.title) })));
|
|
607
606
|
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', '
|
|
607
|
+
title: 'Click',
|
|
608
|
+
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. ' +
|
|
609
|
+
'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.',
|
|
610
|
+
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 },
|
|
611
|
+
}, async (args) => onTab(args, 'action', 'click', async (s, _tab, agent) => ({ text: await act.click(s, agent, args.ref, args.double ?? false) })));
|
|
613
612
|
server.registerTool('browser_type', {
|
|
614
|
-
title: '
|
|
615
|
-
description: '
|
|
616
|
-
'clear=true
|
|
617
|
-
'fast=true
|
|
613
|
+
title: 'Type',
|
|
614
|
+
description: 'Types text into a ref element, sending real key events (keydown/keypress/input/keyup) per character like a human. ' +
|
|
615
|
+
'clear=true clears existing content; submit=true presses Enter after. Verifies the resulting value and reports a mismatch. ' +
|
|
616
|
+
'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
617
|
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('
|
|
618
|
+
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'),
|
|
619
|
+
clear: z.boolean().optional().describe('Clear existing content'), submit: z.boolean().optional().describe('Press Enter after'),
|
|
620
|
+
fast: z.boolean().optional().describe('Very long text: insert at once without key events'), read: readArg, summary: summaryArg,
|
|
622
621
|
},
|
|
623
|
-
}, async (args) => onTab(args, 'action', '
|
|
622
|
+
}, 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
623
|
server.registerTool('browser_fill', {
|
|
625
|
-
title: '
|
|
626
|
-
description: '
|
|
627
|
-
'
|
|
628
|
-
'submit="Enter"
|
|
624
|
+
title: 'Fill form',
|
|
625
|
+
description: 'Fills several inputs on the same page in order (each cleared, typed with real key events, value verified). ' +
|
|
626
|
+
'Stops on page change, dialog, or any failed field, and reports how far it got. ' +
|
|
627
|
+
'submit="Enter" presses Enter in the last field; a button ref clicks that button. For dropdowns use browser_select.',
|
|
629
628
|
inputSchema: {
|
|
630
629
|
slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg,
|
|
631
|
-
fields: z.array(z.object({ ref: z.string().describe('
|
|
632
|
-
submit: z.string().optional().describe('
|
|
630
|
+
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)'),
|
|
631
|
+
submit: z.string().optional().describe('After filling: "Enter" or a button ref to click'),
|
|
633
632
|
read: readArg, summary: summaryArg,
|
|
634
633
|
},
|
|
635
|
-
}, async (args) => onTab(args, 'action', '
|
|
634
|
+
}, async (args) => onTab(args, 'action', 'fill', async (s, _tab, agent) => {
|
|
636
635
|
const href = async () => (await s.evaluate('location.href', { timeoutMs: 3000 }).catch(() => undefined))?.value;
|
|
637
636
|
const start = await href();
|
|
638
637
|
const done = [];
|
|
639
638
|
const stop = (why) => ({ text: [...done, why].join('\n') });
|
|
640
639
|
for (const [i, f] of args.fields.entries()) {
|
|
641
640
|
if (s.dialog)
|
|
642
|
-
return stop(
|
|
641
|
+
return stop(`Stopped before field ${i + 1}: a dialog appeared.`);
|
|
643
642
|
if (pausedInfo(args.slot))
|
|
644
|
-
return stop(
|
|
643
|
+
return stop(`Stopped before field ${i + 1}: the user paused the slot.\n${pausedRefusal(args.slot)}`);
|
|
645
644
|
if (i > 0 && (await href()) !== start)
|
|
646
|
-
return stop(
|
|
645
|
+
return stop(`Page changed; field ${i + 1} [${f.ref}] and after were not filled.`);
|
|
647
646
|
try {
|
|
648
647
|
const r = await act.type(s, agent, f.ref, f.text, true, false);
|
|
649
648
|
done.push(`${i + 1}. ${r}`);
|
|
650
649
|
if (r.includes(act.VALUE_MISMATCH))
|
|
651
|
-
return stop(
|
|
650
|
+
return stop(`Stopped: field ${i + 1} [${f.ref}] value differs from the intended text (not submitted). Check the value and retry.`);
|
|
652
651
|
}
|
|
653
652
|
catch (e) {
|
|
654
653
|
if (e instanceof act.DialogInterrupt)
|
|
655
654
|
throw e;
|
|
656
|
-
return stop(
|
|
655
|
+
return stop(`Stopped at field ${i + 1} [${f.ref}]: ${e.message}`);
|
|
657
656
|
}
|
|
658
657
|
}
|
|
659
658
|
if (args.submit) {
|
|
660
659
|
if (s.dialog)
|
|
661
|
-
return stop('
|
|
662
|
-
done.push(
|
|
660
|
+
return stop('Stopped before submit: a dialog appeared.');
|
|
661
|
+
done.push(`Submit: ${args.submit.toLowerCase() === 'enter' ? await act.pressKey(s, 'Enter') : await act.click(s, agent, args.submit, false)}`);
|
|
663
662
|
}
|
|
664
663
|
return { text: done.join('\n') };
|
|
665
664
|
}));
|
|
666
665
|
server.registerTool('browser_upload', {
|
|
667
|
-
title: '
|
|
668
|
-
description: '
|
|
669
|
-
'
|
|
666
|
+
title: 'Upload file',
|
|
667
|
+
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 ' +
|
|
668
|
+
'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
669
|
inputSchema: {
|
|
671
670
|
slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg,
|
|
672
|
-
files: z.array(z.string()).min(1).describe('
|
|
673
|
-
ref: z.string().optional().describe('
|
|
671
|
+
files: z.array(z.string()).min(1).describe('File paths on this PC (absolute recommended)'),
|
|
672
|
+
ref: z.string().optional().describe('File input ref. Omit to use the file picker just opened by a click'),
|
|
674
673
|
read: readArg, summary: summaryArg,
|
|
675
674
|
},
|
|
676
|
-
}, async (args) => onTab(args, 'action', '
|
|
675
|
+
}, async (args) => onTab(args, 'action', 'upload', async (s, _tab, agent) => ({ text: await act.upload(s, agent, args.ref, args.files) })));
|
|
677
676
|
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', '
|
|
677
|
+
title: 'Select option',
|
|
678
|
+
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.',
|
|
679
|
+
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 },
|
|
680
|
+
}, async (args) => onTab(args, 'action', 'select', async (s, _tab, agent) => ({ text: await act.select(s, agent, args.ref, args.option) })));
|
|
682
681
|
server.registerTool('browser_press_key', {
|
|
683
|
-
title: '
|
|
682
|
+
title: 'Press key',
|
|
684
683
|
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', '
|
|
684
|
+
? '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).'
|
|
685
|
+
: 'Presses a key on the focused element. E.g. Enter, Tab, Escape, ArrowDown, PageDown, Control+A, Shift+Tab.',
|
|
686
|
+
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 },
|
|
687
|
+
}, async (args) => onTab(args, 'action', 'key', async (s) => ({ text: await act.pressKey(s, args.key) })));
|
|
689
688
|
server.registerTool('browser_scroll', {
|
|
690
|
-
title: '
|
|
691
|
-
description: 'ref
|
|
689
|
+
title: 'Scroll',
|
|
690
|
+
description: 'Scrolls a ref element into view, or by dy pixels (positive = down, negative = up, default 600). Reports the actual resulting position.',
|
|
692
691
|
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', '
|
|
692
|
+
}, async (args) => onTab(args, 'action', 'scroll', async (s, _tab, agent) => ({ text: await act.scroll(s, agent, args.ref, args.dy) })));
|
|
694
693
|
server.registerTool('browser_wait', {
|
|
695
|
-
title: '
|
|
696
|
-
description: '
|
|
697
|
-
'response
|
|
698
|
-
'
|
|
699
|
-
'
|
|
700
|
-
'
|
|
694
|
+
title: 'Wait',
|
|
695
|
+
description: 'Waits until text appears; gone: that text disappears; url: the URL changes; enabled: that button/input becomes enabled; ' +
|
|
696
|
+
'response: a network response for that URL completes (returns its body); network_idle: the network goes quiet; otherwise for seconds. ' +
|
|
697
|
+
'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). ' +
|
|
698
|
+
'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"). ' +
|
|
699
|
+
'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
700
|
inputSchema: {
|
|
702
701
|
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('
|
|
702
|
+
text: z.string().optional().describe('Text to wait for'),
|
|
703
|
+
url: z.string().optional().describe('Until the URL contains this (e.g. "mail.google.com/mail"). "" = until it differs from the current URL'),
|
|
704
|
+
gone: z.string().optional().describe('Until this text disappears from the page (e.g. login form\'s "Password" gone = logged in)'),
|
|
705
|
+
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'),
|
|
706
|
+
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.'),
|
|
707
|
+
network_idle: z.boolean().optional().describe('Until no network requests for 0.5s (before capture/read)'),
|
|
708
|
+
enabled: z.string().optional().describe('Until this ref element (button/input) becomes enabled'),
|
|
709
|
+
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
710
|
},
|
|
712
711
|
}, async (args) => onTab(args, 'view', null, async (s, _tab, agent) => {
|
|
713
712
|
// 다른 에이전트가 메시지를 보내면 기다리기를 바로 멈춘다 (메시지는 결과 머리말로 전달됨)
|
|
714
713
|
const stop = () => {
|
|
715
714
|
if (pausedInfo(args.slot))
|
|
716
715
|
return pausedRefusal(args.slot);
|
|
717
|
-
return hasUnread(args.slot, agent) ? '
|
|
716
|
+
return hasUnread(args.slot, agent) ? 'Stopped waiting: a new message arrived (see it in the header above and continue).' : undefined;
|
|
718
717
|
};
|
|
719
718
|
if (args.response !== undefined) {
|
|
720
719
|
if (!args.response.trim())
|
|
721
|
-
throw new CdpmError('
|
|
720
|
+
throw new CdpmError('Put part of the URL to wait for in response (e.g. "/api/search").');
|
|
722
721
|
// 이 에이전트가 이 탭에서 마지막으로 조작한 뒤(2분 안)의 요청부터. 조작 기록이 없으면 지금부터.
|
|
723
722
|
const last = s.actionStartedAt.get(agent);
|
|
724
723
|
const since = last && Date.now() - last < 120_000 ? last : Date.now();
|
|
725
724
|
try {
|
|
726
725
|
const e = await act.waitForResponse(s, args.response, since, args.timeout ?? 30, stop);
|
|
727
726
|
if (e.failed)
|
|
728
|
-
return { text:
|
|
729
|
-
return { text:
|
|
727
|
+
return { text: `Response failed: ${netLine(e)}` };
|
|
728
|
+
return { text: `Response received: ${netLine(e)}\nURL: ${decodeUrl(e.url).slice(0, 300)}\n\n[Response body]\n${await responseBody(s, e)}` };
|
|
730
729
|
}
|
|
731
730
|
catch (err) {
|
|
732
731
|
if (err instanceof act.WaitStopped)
|
|
@@ -752,24 +751,24 @@ export function registerTools(server) {
|
|
|
752
751
|
return { text: why };
|
|
753
752
|
await sleep(Math.min(100, until - Date.now()));
|
|
754
753
|
}
|
|
755
|
-
return { text:
|
|
754
|
+
return { text: `Waited ${sec}s.` };
|
|
756
755
|
}));
|
|
757
756
|
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
|
|
757
|
+
title: 'Run JS',
|
|
758
|
+
description: 'Evaluates a JavaScript expression in the tab and returns the result as JSON. Escape hatch only when other tools can\'t do it. ' +
|
|
759
|
+
'Runs in an isolated world: DOM can be read and modified, but globals created by page scripts (window.appVar, etc.) are not visible.',
|
|
760
|
+
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, expression: z.string().describe('JS expression (Promises are awaited)'), summary: summaryArg },
|
|
761
|
+
}, async (args) => onTab(args, 'action', 'eval JS', async (s) => ({ text: await act.evaluate(s, args.expression) })));
|
|
763
762
|
// ---------- 네트워크 ----------
|
|
764
763
|
server.registerTool('browser_network', {
|
|
765
|
-
title: '
|
|
766
|
-
description: '
|
|
764
|
+
title: 'Network requests',
|
|
765
|
+
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
766
|
inputSchema: {
|
|
768
767
|
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('
|
|
768
|
+
filter: z.string().optional().describe('Only requests whose URL contains this'),
|
|
769
|
+
type: z.string().optional().describe('Request type (e.g. XHR, Fetch, Document, Script, Image)'),
|
|
770
|
+
failed: z.boolean().optional().describe('Failed requests only'),
|
|
771
|
+
limit: z.number().int().min(1).max(200).optional().describe('Max count (default 40, newest first)'),
|
|
773
772
|
},
|
|
774
773
|
}, async (args) => onTab(args, 'view', null, async (s) => {
|
|
775
774
|
let list = s.network.list();
|
|
@@ -782,41 +781,41 @@ export function registerTools(server) {
|
|
|
782
781
|
list = list.filter((e) => e.failed);
|
|
783
782
|
const limit = args.limit ?? 40;
|
|
784
783
|
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') : '(
|
|
784
|
+
const since = new Date(s.network.startedAt).toLocaleTimeString('en-GB', { hour12: false });
|
|
785
|
+
const head = `Recording since ${since} (when CDPM first attached to this tab) · ${list.length} of ${total} recorded match${list.length > limit ? `, newest ${limit} shown` : ''}`;
|
|
786
|
+
return { text: `${head}\n${shown.length ? shown.map((e) => netLine(e, s.network.rules)).join('\n') : '(no matching requests)'}` };
|
|
788
787
|
}));
|
|
789
788
|
server.registerTool('browser_network_detail', {
|
|
790
|
-
title: '
|
|
791
|
-
description: '
|
|
792
|
-
inputSchema: { slot: slotArg, agent: agentArg, tab: tabArg, multiSlot: multiSlotArg, id: z.string().describe('
|
|
789
|
+
title: 'Network request detail',
|
|
790
|
+
description: 'Shows one request\'s headers, sent data and response body (start of it, if text). id is the n-number from browser_network.',
|
|
791
|
+
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
792
|
}, async (args) => onTab(args, 'view', null, async (s) => {
|
|
794
793
|
const e = s.network.find(args.id);
|
|
795
794
|
if (!e)
|
|
796
|
-
throw new CdpmError(
|
|
797
|
-
const parts = [netLine(e), '',
|
|
795
|
+
throw new CdpmError(`Request "${args.id}" not found. Check numbers with browser_network (only the latest 500 are kept).`);
|
|
796
|
+
const parts = [netLine(e), '', `URL: ${decodeUrl(e.url)}`, '', '[Request headers]', headersText(e.requestHeaders)];
|
|
798
797
|
if (e.hasPostData) {
|
|
799
798
|
const post = await s.send('Network.getRequestPostData', { requestId: e.requestId }, 5000).catch(() => undefined);
|
|
800
|
-
parts.push('', '[
|
|
799
|
+
parts.push('', '[Sent data]', post ? truncate(post.postData, 5000) : ' (unavailable)');
|
|
801
800
|
}
|
|
802
|
-
parts.push('', '[
|
|
801
|
+
parts.push('', '[Response headers]', headersText(e.responseHeaders));
|
|
803
802
|
if (args.body !== false && !e.failed && e.status !== undefined)
|
|
804
|
-
parts.push('', '[
|
|
803
|
+
parts.push('', '[Response body]', await responseBody(s, e));
|
|
805
804
|
return { text: parts.join('\n') };
|
|
806
805
|
}));
|
|
807
806
|
server.registerTool('browser_block', {
|
|
808
|
-
title: '
|
|
809
|
-
description: '
|
|
810
|
-
'
|
|
811
|
-
'
|
|
807
|
+
title: 'Block requests',
|
|
808
|
+
description: 'Blocks tab network requests matching URL patterns (they fail). add adds, remove removes, clear removes all rules you set. ' +
|
|
809
|
+
'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. ' +
|
|
810
|
+
'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
811
|
inputSchema: {
|
|
813
812
|
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('
|
|
813
|
+
add: z.array(z.string()).optional().describe('URL patterns to block'),
|
|
814
|
+
remove: z.array(z.string()).optional().describe('Patterns to unblock'),
|
|
815
|
+
clear: z.boolean().optional().describe('Remove all rules set by this session'),
|
|
817
816
|
summary: summaryArg,
|
|
818
817
|
},
|
|
819
|
-
}, async (args) => onTab(args, args.add?.length || args.remove?.length || args.clear ? 'action' : 'view', args.add?.length ? '
|
|
818
|
+
}, 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
819
|
let rules = [...s.network.rules];
|
|
821
820
|
if (args.clear)
|
|
822
821
|
rules = [];
|
|
@@ -844,97 +843,101 @@ export function registerTools(server) {
|
|
|
844
843
|
}
|
|
845
844
|
const others = liveBlocks(tab).filter((b) => b.pid !== process.pid);
|
|
846
845
|
const lines = [
|
|
847
|
-
changed ? '
|
|
848
|
-
|
|
846
|
+
changed ? 'Block rules updated.' : 'Current block rules:',
|
|
847
|
+
`This session: ${rules.length ? rules.map((r) => `${r.pattern} (${r.agent})`).join(', ') : 'none'}`,
|
|
849
848
|
];
|
|
850
849
|
if (others.length)
|
|
851
|
-
lines.push(
|
|
852
|
-
lines.push('
|
|
850
|
+
lines.push(`Other sessions: ${others.map((b) => `${b.pattern} (${b.agent})`).join(', ')} — only removable from that session`);
|
|
851
|
+
lines.push('Blocked requests show in browser_network as "failed … (blocked: pattern)".');
|
|
853
852
|
return { text: lines.join('\n') };
|
|
854
853
|
}));
|
|
855
854
|
// ---------- 메시지 ----------
|
|
856
|
-
const slotsArg = z.array(slotArg).optional().describe('
|
|
855
|
+
const slotsArg = z.array(slotArg).optional().describe('Multiple slots (e.g. [1,2,3])');
|
|
857
856
|
server.registerTool('slot_pause', {
|
|
858
|
-
title: '
|
|
859
|
-
description: '
|
|
860
|
-
'
|
|
861
|
-
inputSchema: { slot: slotArg.optional(), slots: slotsArg, all: z.boolean().optional().describe('
|
|
857
|
+
title: 'Pause slot',
|
|
858
|
+
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. ' +
|
|
859
|
+
'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.',
|
|
860
|
+
inputSchema: { slot: slotArg.optional(), slots: slotsArg, all: z.boolean().optional().describe('All running slots'), agent: agentArg },
|
|
862
861
|
}, async ({ slot, slots, all, agent }) => guard(async () => {
|
|
863
862
|
const me = agent ?? DEFAULT_AGENT;
|
|
864
863
|
const targets = all ? (await liveSlots()).map(([s]) => s) : [...new Set([...(slots ?? []), ...(slot !== undefined ? [slot] : [])])];
|
|
865
864
|
if (!targets.length)
|
|
866
|
-
throw new CdpmError('
|
|
867
|
-
return textResult((await pauseSlots(targets, me)).join('\n') + '\
|
|
865
|
+
throw new CdpmError('Specify slots to pause (slot, slots or all).');
|
|
866
|
+
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
867
|
}));
|
|
869
868
|
server.registerTool('slot_resume', {
|
|
870
|
-
title: '
|
|
871
|
-
description: '
|
|
872
|
-
inputSchema: { slot: slotArg.optional(), slots: slotsArg, all: z.boolean().optional().describe('
|
|
869
|
+
title: 'Resume slot',
|
|
870
|
+
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.',
|
|
871
|
+
inputSchema: { slot: slotArg.optional(), slots: slotsArg, all: z.boolean().optional().describe('All paused slots'), agent: agentArg },
|
|
873
872
|
}, async ({ slot, slots, all, agent }) => guard(async () => {
|
|
874
873
|
const me = agent ?? DEFAULT_AGENT;
|
|
875
874
|
const targets = all ? (await import('../pause.js')).pausedSlots() : [...new Set([...(slots ?? []), ...(slot !== undefined ? [slot] : [])])];
|
|
876
875
|
if (!targets.length)
|
|
877
|
-
return textResult(all ? '
|
|
876
|
+
return textResult(all ? 'No paused slots.' : 'Specify slots to resume (slot, slots or all).', !all);
|
|
878
877
|
return textResult((await resumeSlots(targets, me)).join('\n'));
|
|
879
878
|
}));
|
|
880
879
|
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('
|
|
880
|
+
title: 'Send message',
|
|
881
|
+
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. ' +
|
|
882
|
+
'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.',
|
|
883
|
+
inputSchema: { slot: slotArg, agent: agentArg, text: z.string().min(1).max(2000), to: z.string().optional().describe('Recipient agent name') },
|
|
885
884
|
}, async ({ slot, agent, text, to }) => guard(async () => {
|
|
886
885
|
const me = agent ?? DEFAULT_AGENT;
|
|
887
886
|
const msg = await sendMessage(slot, me, text, to ?? null);
|
|
888
|
-
return textResult(`[${slot}
|
|
887
|
+
return textResult(`[Slot ${slot}] Message sent (#${msg.seq}${to ? `, to: ${to}` : ', to everyone'}).`);
|
|
889
888
|
}));
|
|
890
889
|
server.registerTool('slot_inbox', {
|
|
891
|
-
title: '
|
|
892
|
-
description: '
|
|
893
|
-
'
|
|
894
|
-
inputSchema: { slot: slotArg, agent: agentArg, wait: z.number().min(0).max(600).optional().describe('
|
|
890
|
+
title: 'Check messages',
|
|
891
|
+
description: 'Shows your unread messages. With wait (seconds), waits up to that long for a new message (for real-time conversation). ' +
|
|
892
|
+
'Messages already delivered in another tool\'s header are not unread; when there are no new ones, recently received ones are noted for reference.',
|
|
893
|
+
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
894
|
}, async ({ slot, agent, wait }) => guard(async () => {
|
|
896
895
|
const me = agent ?? DEFAULT_AGENT;
|
|
897
896
|
const msgs = wait ? await waitUnread(slot, me, wait) : await takeUnread(slot, me);
|
|
898
897
|
if (msgs.length)
|
|
899
|
-
return textResult(`[${slot}
|
|
898
|
+
return textResult(`[Slot ${slot}] ${msgs.length} new message(s)\n${formatMessages(msgs).map((l) => ` ${l}`).join('\n')}`);
|
|
900
899
|
const recent = recentDelivered(slot, me);
|
|
901
|
-
const tail = recent.length ? ` (
|
|
902
|
-
return textResult(`[${slot}
|
|
900
|
+
const tail = recent.length ? ` (${recent.length} message(s) already delivered via other tool headers in the last 10 min are not repeated)` : '';
|
|
901
|
+
return textResult(`[Slot ${slot}] No new messages${wait ? ` (waited ${wait}s)` : ''}.${tail}`);
|
|
903
902
|
}));
|
|
904
903
|
}
|
|
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
|
-
-
|
|
904
|
+
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}).
|
|
905
|
+
- Always reply to the user in the language the user writes in (these instructions are in English only to save tokens).
|
|
906
|
+
- "Look at 3" / "slot 3" means slot=3. Pass slot to every tool.
|
|
907
|
+
- 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).
|
|
908
|
+
- 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).
|
|
909
|
+
- 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).
|
|
910
|
+
- 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.
|
|
911
|
+
- 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).
|
|
912
|
+
- Roles of main agent and subagents (multi-slot/multi-tab work, any site, always):
|
|
913
|
+
- 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.
|
|
914
|
+
- 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.
|
|
915
|
+
- Simple jobs that need just one slot can be done by main directly.
|
|
916
|
+
- 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).
|
|
917
|
+
- Outputs (reports, HTML, etc.) are written by each subagent for its share; main only merges (main writing everything alone is the slowest step).
|
|
918
|
+
- 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.
|
|
919
|
+
- 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.
|
|
920
|
+
- 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).
|
|
921
|
+
- 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.
|
|
922
|
+
- 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.
|
|
923
|
+
- Keep waits minimal. Never use fixed waits (seconds).
|
|
924
|
+
- 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.
|
|
925
|
+
- 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.
|
|
926
|
+
- 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.
|
|
927
|
+
- Other slots' pages can be viewed anytime with view tools (browser_snapshot, browser_text, browser_screenshot); only that slot's owner operates it.
|
|
928
|
+
- Never change window size/position or viewport. Use browser_tab_select (changes the tab the user sees) only when the user wants it.
|
|
929
|
+
- "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).
|
|
930
|
+
- 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.).`;
|
|
929
931
|
/** Claude Code가 아닌 클라이언트(Cursor, Claude Desktop 등)용: Agent 도구·run_in_background·cdpm-browser처럼 Claude Code에만 있는 말을 뺀다. */
|
|
930
|
-
const GENERIC_PARALLEL = '-
|
|
931
|
-
'
|
|
932
|
+
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). ' +
|
|
933
|
+
'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
934
|
function genericInstructions() {
|
|
933
935
|
return INSTRUCTIONS_CLAUDE_CODE
|
|
934
936
|
.split('\n')
|
|
935
937
|
// Claude Code 전용 병렬 처리 안내(Agent 도구·cdpm-browser) → 일반 안내로
|
|
936
|
-
.map((l) => (l.startsWith('-
|
|
937
|
-
.map((l) => l.replace('
|
|
938
|
+
.map((l) => (l.startsWith('- Different jobs on multiple slots') ? GENERIC_PARALLEL : l))
|
|
939
|
+
.map((l) => l.replace('Start subagents first; each, without touching', '(With subagents, start them first.) Each agent, without touching'))
|
|
940
|
+
.map((l) => l.replace('hand them to a background subagent (run_in_background: true)', 'hand them to a subagent or background task'))
|
|
938
941
|
.join('\n');
|
|
939
942
|
}
|
|
940
943
|
/** 클라이언트에 맞는 서버 안내 (initialize 때 정한다). */
|