@liang-hz/agent-in-chrome 0.55.2 → 0.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/mcp/server.mjs CHANGED
@@ -28,7 +28,7 @@ import {
28
28
  import { createUpdateNotice } from "./update-notice.mjs";
29
29
  import { foregroundGuard } from "./foreground-guard.mjs";
30
30
  import { deriveSessionId, pruneClaims } from "./session-id.mjs";
31
- import { probeLocal, readSessionIdentity, composeAgent, procSource, readClaudeSubagent, antigravityConversationId, codexThreadId, workbuddyConversationId, isOpencodeClient } from "./agent-identity.mjs";
31
+ import { probeLocal, readSessionIdentity, composeAgent, procSource, readClaudeSubagent, readDshSubagent, antigravityConversationId, codexThreadId, workbuddyConversationId, isOpencodeClient } from "./agent-identity.mjs";
32
32
  import * as cfgFile from "./config.mjs";
33
33
  import { TOOL_TIER, TIER_RANK, REVEAL_REQUIRES_FULL, PARAM_REQUIRES_FULL } from "./tool-tiers.mjs";
34
34
  import {
@@ -50,7 +50,7 @@ import {
50
50
  import crypto from "node:crypto";
51
51
 
52
52
  const NAME = "agent-in-chrome";
53
- const VERSION = "0.55.2";
53
+ const VERSION = "0.56.0";
54
54
  /** 本进程起来的时刻。CDP 模式下工具层就在本进程里,它也是「工具层代码的加载时刻」 */
55
55
  const PROCESS_STARTED_AT = Date.now();
56
56
  const SUPPORTED_PROTOCOLS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
@@ -66,27 +66,8 @@ const TOOLS_TTL_MS = 60_000;
66
66
  const DISCOVER_TTL_MS = 600_000;
67
67
 
68
68
  /*
69
- * Windows 上不许进 CLI/headless 模式,当场拒绝启动。
69
+ * Windows 的 CLI/headless 模式(现已支持)。
70
70
  */
71
- if (CDP_LAUNCH && process.platform === "win32") {
72
- process.stderr.write(
73
- [
74
- "[agent-in-chrome] Windows 上还不支持 CLI/headless 模式(AGENT_IN_CHROME_LAUNCH=1),已拒绝启动。",
75
- "",
76
- "为什么不支持:这个模式要自己起浏览器、也要自己收回来,而「收回来」依赖的三个数据源",
77
- " (ps 找子进程、按 profile 认领、SingletonLock 符号链接)在 Windows 上全部失效。",
78
- " 实测结果是 server 退出后留下一堆 chrome.exe,它们的调试端口没有任何访问控制、仍在应答,",
79
- " 任何本机进程都能接管那个带着你登录态的浏览器。所以宁可不启动。",
80
- " 设 AGENT_IN_CHROME_BIN 也绕不过去 —— 它绕过的只是「找不到浏览器」,不是这条。",
81
- "",
82
- "插件模式不受影响:去掉 AGENT_IN_CHROME_LAUNCH(和 AGENT_IN_CHROME_BIN)重启即可,",
83
- " 它驱动的是你自己那个装了扩展的 Chrome。装没装好用 npx @liang-hz/agent-in-chrome check 自检。",
84
- "",
85
- "跟进:README 的「平台」一节,以及 mcp/cdp/browser-launch.mjs 里的进程管理注释。",
86
- ].join("\n") + "\n"
87
- );
88
- process.exit(1);
89
- }
90
71
 
91
72
  function defaultSockName() {
92
73
  if (!CDP_LAUNCH) return "agent-in-chrome.sock";
@@ -114,6 +95,9 @@ const CALL_TIMEOUT_MS = (() => {
114
95
  );
115
96
  return 60_000;
116
97
  })();
98
+ const WAIT_TIMEOUT_CAP_MS = 600_000;
99
+ const MAX_CALL_TIMEOUT_MS = WAIT_TIMEOUT_CAP_MS + 5000;
100
+ const MAX_FORWARD_TTL_MS = WAIT_TIMEOUT_CAP_MS + 15_000;
117
101
  /*
118
102
  * 本**会话**的身份。扩展据此把目标标签页、标签组按会话隔离——
119
103
  * 否则两个 agent 会话会互相抢标签页。
@@ -125,10 +109,16 @@ const LOCAL_ID_AT_START = (() => {
125
109
  return null;
126
110
  }
127
111
  })();
128
- const SESSION_ID = deriveSessionId({
129
- identity: LOCAL_ID_AT_START,
130
- anchor: Number.isInteger(LOCAL_ID_AT_START?.clientPid) ? () => ({ pid: LOCAL_ID_AT_START.clientPid, hops: 0 }) : null,
131
- });
112
+ let _sessionId = null;
113
+ function getSessionId() {
114
+ if (_sessionId === null) {
115
+ _sessionId = deriveSessionId({
116
+ identity: LOCAL_ID_AT_START,
117
+ anchor: Number.isInteger(LOCAL_ID_AT_START?.clientPid) ? () => ({ pid: LOCAL_ID_AT_START.clientPid, hops: 0 }) : null,
118
+ });
119
+ }
120
+ return _sessionId;
121
+ }
132
122
  pruneClaims();
133
123
  pruneDeadSocks({ dir: dataDirFor(SOCK), keep: [SOCK] }).catch(() => {});
134
124
  const DEV_MODE = ["1", "true", "yes", "on"].includes(String(process.env.AGENT_IN_CHROME_DEV || "").toLowerCase());
@@ -252,9 +242,17 @@ let ownsSocket = false;
252
242
 
253
243
  const pending = new Map();
254
244
  const forwarded = new Map();
255
- const FORWARD_TTL_MS = CALL_TIMEOUT_MS + 5000;
256
- function trackForwarded(inner, entry) {
257
- const timer = setTimeout(() => forwarded.delete(inner), FORWARD_TTL_MS);
245
+ const FORWARD_TTL_MS = (() => {
246
+ const t = Number(process.env.AIC_TEST_FORWARD_TTL_MS);
247
+ if (Number.isFinite(t) && t >= 200) return Math.min(MAX_FORWARD_TTL_MS, Math.round(t));
248
+ return CALL_TIMEOUT_MS + 5000;
249
+ })();
250
+ function trackForwarded(inner, entry, ttlMs = FORWARD_TTL_MS) {
251
+ const raw = Number(ttlMs);
252
+ const effectiveTtl = Number.isFinite(raw)
253
+ ? Math.min(MAX_FORWARD_TTL_MS, Math.max(FORWARD_TTL_MS, raw))
254
+ : FORWARD_TTL_MS;
255
+ const timer = setTimeout(() => forwarded.delete(inner), effectiveTtl);
258
256
  timer.unref?.();
259
257
  forwarded.set(inner, { ...entry, timer });
260
258
  }
@@ -403,11 +401,16 @@ function failAllPending(why) {
403
401
  const BRIDGE_GRACE_MS = CDP_MODE ? CDP_BRIDGE_GRACE_MS : 4000;
404
402
  function waitForBridge() {
405
403
  if (bridgeReady()) return Promise.resolve(true);
406
- recoverCdp();
404
+ const ensureCdp = () => {
405
+ if (CDP_MODE && role === "owner" && !cdp && !cdpStarting) startCdpMode();
406
+ recoverCdp();
407
+ };
408
+ ensureCdp();
407
409
  return new Promise((resolve) => {
408
410
  const deadline = Date.now() + BRIDGE_GRACE_MS;
409
411
  const tick = () => {
410
412
  if (bridgeReady()) return resolve(true);
413
+ ensureCdp();
411
414
  if (Date.now() >= deadline) return resolve(false);
412
415
  setTimeout(tick, 100);
413
416
  };
@@ -471,6 +474,7 @@ function agentForFrame() {
471
474
  let task = null;
472
475
  try {
473
476
  if (LOCAL_ID && LAST_TOOL_USE) task = readClaudeSubagent({ "claudecode/toolUseId": LAST_TOOL_USE }, LOCAL_ID);
477
+ if (!task && LOCAL_ID) task = readDshSubagent(LAST_META, LOCAL_ID);
474
478
  } catch {}
475
479
  if (!agent) return task ? { task: task.label, taskType: task.type } : null;
476
480
  return { ...agent, task: task?.label || null, taskType: task?.type || null };
@@ -521,8 +525,9 @@ function sidFor(rpcMeta) {
521
525
  const ag = antigravityConversationId(m) || "";
522
526
  const caller = zc || ag;
523
527
  const from = zc ? "_meta.session_id" : ag ? "_meta.antigravity.google/conversation_id" : null;
524
- if (!caller) return { sid: SESSION_ID, sidFrom: "fallback", sidCaller: null };
525
- return { sid: `${SESSION_ID}::${caller}`, sidFrom: from, sidCaller: caller };
528
+ const baseSid = getSessionId();
529
+ if (!caller) return { sid: baseSid, sidFrom: "fallback", sidCaller: null };
530
+ return { sid: `${baseSid}::${caller}`, sidFrom: from, sidCaller: caller };
526
531
  }
527
532
 
528
533
  const INJECT_TOOLS = new Set(["read_page", "refresh_refs", "upload_file"]);
@@ -583,7 +588,7 @@ async function timeoutError(tool, args, sid, timeoutMs, probe) {
583
588
  );
584
589
  }
585
590
 
586
- async function callBrowser(tool, args, sid = SESSION_ID, timeoutMs = CALL_TIMEOUT_MS, { probe = true, onDispatch = null } = {}) {
591
+ async function callBrowser(tool, args, sid = getSessionId(), timeoutMs = CALL_TIMEOUT_MS, { probe = true, onDispatch = null } = {}) {
587
592
  if (!(await waitForBridge())) throw new Error(notReadyMessage());
588
593
  return new Promise((resolve, reject) => {
589
594
  const id = `c${++seq}`;
@@ -598,7 +603,16 @@ async function callBrowser(tool, args, sid = SESSION_ID, timeoutMs = CALL_TIMEOU
598
603
  pending.delete(id);
599
604
  reject(new Error(CANCELLED_ERROR));
600
605
  });
601
- const frame = { type: "call", id, tool, args, session: sid };
606
+ const frame = {
607
+ type: "call",
608
+ id,
609
+ tool,
610
+ args,
611
+ session: sid,
612
+ ...(role === "peer"
613
+ ? { ttlMs: Math.min(MAX_FORWARD_TTL_MS, Math.max(FORWARD_TTL_MS, timeoutMs + 5000)) }
614
+ : {}),
615
+ };
602
616
  if (role !== "peer") foregroundGuard().arm();
603
617
  const agent = agentForFrame();
604
618
  if (agent) frame.agent = agent;
@@ -731,7 +745,7 @@ function onIncoming(conn) {
731
745
 
732
746
  if (kind === "peer" && msg.type === "call") {
733
747
  const inner = `f${++seq}`;
734
- trackForwarded(inner, { conn, origId: msg.id });
748
+ trackForwarded(inner, { conn, origId: msg.id }, msg.ttlMs);
735
749
  const frame = { type: "call", id: inner, tool: msg.tool, args: msg.args, session: msg.session };
736
750
  foregroundGuard().arm();
737
751
  if (msg.agent) frame.agent = msg.agent;
@@ -1060,7 +1074,6 @@ function onListening() {
1060
1074
  } catch (e) {
1061
1075
  process.stderr.write(`[agent-in-chrome] 建不出桥接令牌:${String(e?.message || e)}\n`);
1062
1076
  }
1063
- if (CDP_MODE) startCdpMode();
1064
1077
  }
1065
1078
 
1066
1079
  function startCdpMode() {
@@ -1119,9 +1132,9 @@ function recoverCdp() {
1119
1132
 
1120
1133
  let sessionEndSent = false;
1121
1134
  function sendSessionEnd() {
1122
- if (sessionEndSent) return;
1135
+ if (sessionEndSent || _sessionId === null) return;
1123
1136
  sessionEndSent = true;
1124
- const frame = { type: "session-end", session: SESSION_ID };
1137
+ const frame = { type: "session-end", session: _sessionId };
1125
1138
  try {
1126
1139
  if (role === "owner") {
1127
1140
  if (CDP_MODE) cdp && cdp.send(frame);
@@ -1215,22 +1228,17 @@ const obj = (properties, required = []) =>
1215
1228
  * 每个操作类工具都有的可选参数:这一次作用在哪个标签页上。
1216
1229
  * 一个会话同时持有不止一个标签页时不带 tabId 会直接报错——扩展不会替你挑。
1217
1230
  */
1218
- const TAB_ID = S.num("Which tab (required when holding >1)");
1219
- const SETTLE_MS_DESC =
1220
- "DOM must be stable this long first (default 0, max 5000). Pass 300-800 right after a click/navigation " +
1221
- "or you silently read the previous screen.";
1222
- const CONTAINER_DESC =
1223
- "CSS selector: scan only this subtree — for pages over maxElements and for overlays " +
1224
- "(activeDialog.container). No match errors, never a silent full-page scan.";
1231
+ const TAB_ID = S.num("Tab id (needed if >1 held)");
1232
+ const SETTLE_MS_DESC = "DOM settle ms (0-5000, default 0)";
1233
+ const CONTAINER_DESC = "CSS subtree selector (errors if unmatched)";
1225
1234
  const ACTIVE_DIALOG_DESC =
1226
- "\nactiveDialog = a modal overlay is in front: handle it first, the page beneath is usually unclickable " +
1227
- "(low confidence may be just a cookie banner). Its ref works in click/type, its container here; OOPIF " +
1228
- "overlays give ref_b12@t<frameId> instead — find can't reach those, drive them via ref_N@fN.";
1229
- const ACTIVE_DIALOG_SHORT = "\nactiveDialog = a modal is in front; handle it first (see browser_read_page).";
1230
- const MAX_ELEMENTS_DESC = "Cap, default 200 (elementsTotal = real total). When truncated narrow with container.";
1231
- const OUT_FILE_DESC =
1232
- "Write the result here instead of into your context (a summary returns). Relative to the agent's cwd.";
1233
- const APPEND_DESC = "With outFile: append instead of overwrite.";
1235
+ "\nactiveDialog = modal frontmost: handle first (ref in click/type, container here; OOPIF gives ref_b12@t<frameId>, use ref_N@fN).";
1236
+ const ACTIVE_DIALOG_SHORT = "\nactiveDialog = modal in front; handle first (see browser_read_page).";
1237
+ const MAX_ELEMENTS_DESC = "Cap, default 200 (elementsTotal=total)";
1238
+ const OUT_FILE_DESC = "Write to file (~ ok); returns summary";
1239
+ const APPEND_DESC = "Append outFile";
1240
+ const REVEAL_DESC = "Literal true only: include credentials";
1241
+ const TIMEOUT_MS_DESC = "Timeout ms (<=45000 rec, max 600000)";
1234
1242
 
1235
1243
  // ------------------------------------------------- 文件上传:Node 侧的把关
1236
1244
 
@@ -1363,7 +1371,7 @@ function prepareUpload(args = {}) {
1363
1371
  // 环境变量 AGENT_IN_CHROME_TRACE=off 可整体关掉(连落盘一起)。
1364
1372
 
1365
1373
  const TRACE_ON = String(process.env.AGENT_IN_CHROME_TRACE || "").toLowerCase() !== "off";
1366
- const trace = createTrace({ sessionId: SESSION_ID, enabled: TRACE_ON, version: VERSION });
1374
+ const trace = createTrace({ sessionId: getSessionId, enabled: TRACE_ON, version: VERSION });
1367
1375
  // 后台查一次有没有新版;查询本身不阻塞任何调用,结果搭在下一次工具返回的尾巴上(见 update-notice.mjs)
1368
1376
  const updateNotice = createUpdateNotice({ current: VERSION });
1369
1377
 
@@ -1423,7 +1431,7 @@ const NO_REPLAY =
1423
1431
  "点过的「提交/下单/发送」再点一次就是重复执行。要接着做,先 browser_read_page 看清页面现在是什么状态、" +
1424
1432
  "确认前面那一步到底做成了没有,再决定下一步;涉及不可逆动作的先问用户。";
1425
1433
 
1426
- async function traceTool(args = {}, sid = SESSION_ID) {
1434
+ async function traceTool(args = {}, sid = getSessionId()) {
1427
1435
  const dir = defaultTraceDir();
1428
1436
 
1429
1437
  if (args.list) {
@@ -1473,10 +1481,78 @@ function pickFileField(data, field) {
1473
1481
  /*
1474
1482
  * 跑一个工具:prepare → 本地执行或过桥 → post → outFile 落盘,全程记 trace。
1475
1483
  */
1484
+ const STRICT_BOOL_KEYS = new Set(["revealSecrets", "confirmSensitive", "takeover"]);
1485
+ const TOOL_ALIASES = {
1486
+ browser_wait_for: {
1487
+ timeout: "timeoutMs",
1488
+ text: "textContains",
1489
+ textPresent: "textContains",
1490
+ expression: "js",
1491
+ },
1492
+ browser_network_wait: { timeout: "timeoutMs" },
1493
+ browser_eval: { timeout: "timeoutMs", code: "expression", script: "expression" },
1494
+ browser_navigate: { timeout: "timeoutMs" },
1495
+ browser_fetch: { timeout: "timeoutMs" },
1496
+ browser_read_page: { maxChars: "maxText" },
1497
+ browser_type: { submit: "pressEnter" },
1498
+ browser_find: { text: "query" },
1499
+ };
1500
+
1501
+ function coerceSafeScalars(spec, args) {
1502
+ const props = spec?.inputSchema?.properties || {};
1503
+ for (const [k, v] of Object.entries(args)) {
1504
+ if (STRICT_BOOL_KEYS.has(k)) continue;
1505
+ const pType = props[k]?.type;
1506
+ if (pType === "boolean" && typeof v === "string") {
1507
+ if (PLACEHOLDER_RE.test(normPlaceholderSpacing(v))) continue;
1508
+ if (v === "true") args[k] = true;
1509
+ else if (v === "false") args[k] = false;
1510
+ } else if ((pType === "number" || pType === "integer") && typeof v === "string") {
1511
+ const trimmed = v.trim();
1512
+ if (PLACEHOLDER_RE.test(normPlaceholderSpacing(trimmed))) continue;
1513
+ if (/^-?\d+(?:\.\d+)?$/.test(trimmed)) {
1514
+ const num = Number(trimmed);
1515
+ if (Number.isFinite(num)) {
1516
+ args[k] = num;
1517
+ continue;
1518
+ }
1519
+ }
1520
+ throw new Error(`参数 ${k} 需要数字,收到 ${JSON.stringify(v)}`);
1521
+ }
1522
+ }
1523
+ return args;
1524
+ }
1525
+
1526
+ function normalizeToolArgs(name, rawArgs) {
1527
+ if (!rawArgs || typeof rawArgs !== "object" || Array.isArray(rawArgs)) return {};
1528
+ const out = {};
1529
+ for (const [k, v] of Object.entries(rawArgs)) {
1530
+ if (k.startsWith("_")) continue;
1531
+ out[k] = v;
1532
+ }
1533
+ const aliases = TOOL_ALIASES[name];
1534
+ if (aliases) {
1535
+ for (const [alias, target] of Object.entries(aliases)) {
1536
+ if (out[alias] !== undefined) {
1537
+ if (out[target] === undefined) out[target] = out[alias];
1538
+ delete out[alias];
1539
+ }
1540
+ }
1541
+ }
1542
+ return coerceSafeScalars(BY_NAME.get(name), out);
1543
+ }
1544
+
1476
1545
  async function runTool(spec, rawArgsIn, ctx) {
1477
- let rawArgs = rawArgsIn || {};
1546
+ let rawArgs = normalizeToolArgs(spec.name, rawArgsIn);
1478
1547
  const tierDenied = revealDenied(spec.name, rawArgs);
1479
1548
  if (tierDenied) throw new Error(tierDenied);
1549
+ if (
1550
+ (spec.fileField || spec.imageFile || spec.name === "browser_cookies_export") &&
1551
+ typeof rawArgs.outFile === "string" &&
1552
+ rawArgs.outFile.trim() !== ""
1553
+ ) {
1554
+ resolveWritePath(rawArgs.outFile);
1555
+ }
1480
1556
  const outFile = spec.fileField ? rawArgs.outFile : undefined;
1481
1557
  const appendMode = spec.fileField ? !!rawArgs.append : false;
1482
1558
  if (outFile) {
@@ -1486,6 +1562,12 @@ async function runTool(spec, rawArgsIn, ctx) {
1486
1562
  delete rawArgs.offset;
1487
1563
  delete rawArgs.length;
1488
1564
  if ("maxChars" in spec.inputSchema.properties) rawArgs.maxChars = Number.MAX_SAFE_INTEGER;
1565
+ if (spec.name === "browser_fetch" || spec.name === "browser_request_detail") {
1566
+ rawArgs._forOutFile = true;
1567
+ if (rawArgs.maxBody === undefined) {
1568
+ rawArgs.maxBody = spec.name === "browser_request_detail" ? 5_000_000 : 10_000_000;
1569
+ }
1570
+ }
1489
1571
  }
1490
1572
  const { sid } = ctx;
1491
1573
  const step = spec.local ? null : safeBegin(spec.name, rawArgs, ctx.rpcMeta, ctx.batch);
@@ -1546,7 +1628,6 @@ const BATCH_DENY = {
1546
1628
  browser_reload_extension: "reload_extension 会放开所有会话接管中的标签页,本批次后面几步的 tabId 当场作废。",
1547
1629
  };
1548
1630
 
1549
- const WAIT_TIMEOUT_CAP_MS = 600_000;
1550
1631
  function waitTimeout(args) {
1551
1632
  const want = Number(args?.timeoutMs);
1552
1633
  if (!Number.isFinite(want) || want <= 0) return undefined;
@@ -1584,12 +1665,30 @@ const NO_PLACEHOLDER_ARGS = new Map([
1584
1665
  ["takeover", "征用用户标签页的确认开关"],
1585
1666
  ]);
1586
1667
 
1587
- function assertNoSwitchPlaceholder(v, at) {
1588
- if (!v || typeof v !== "object") return;
1668
+ const TOOL_NO_PLACEHOLDER_ARGS = new Map([
1669
+ ["browser_fetch", new Set(["url", "headers", "query", "body", "json", "outFile"])],
1670
+ ["browser_wait_for", new Set(["js", "expression"])],
1671
+ ["browser_eval", new Set(["expression", "code", "script"])],
1672
+ ]);
1673
+
1674
+ function assertNoSwitchPlaceholder(v, at, toolName = null, isTop = true, underBlockedKey = null) {
1675
+ if (!v || typeof v !== "object") {
1676
+ if (underBlockedKey && typeof v === "string") {
1677
+ const sn = normPlaceholderSpacing(v);
1678
+ if (PLACEHOLDER_RE.test(sn) || sn.includes("{{steps")) {
1679
+ throw new Error(
1680
+ `${at}的 ${toolName}.${underBlockedKey} 不能使用占位符(${JSON.stringify(v)}),什么都没做。` +
1681
+ `为防止单轮数据外泄或动态脚本注入,该参数只接受调用方显式字面量。`
1682
+ );
1683
+ }
1684
+ }
1685
+ return;
1686
+ }
1589
1687
  if (Array.isArray(v)) {
1590
- for (const x of v) assertNoSwitchPlaceholder(x, at);
1688
+ for (const x of v) assertNoSwitchPlaceholder(x, at, toolName, false, underBlockedKey);
1591
1689
  return;
1592
1690
  }
1691
+ const toolBlocked = isTop && toolName ? TOOL_NO_PLACEHOLDER_ARGS.get(toolName) : null;
1593
1692
  for (const [k, x] of Object.entries(v)) {
1594
1693
  const why = NO_PLACEHOLDER_ARGS.get(k);
1595
1694
  const xn = typeof x === "string" ? normPlaceholderSpacing(x) : x;
@@ -1602,7 +1701,8 @@ function assertNoSwitchPlaceholder(v, at) {
1602
1701
  `确实要开就直接写死 ${k}: true;要依据前一步的结果再决定,就把这一步单独发一次调用。`
1603
1702
  );
1604
1703
  }
1605
- assertNoSwitchPlaceholder(x, at);
1704
+ const nextBlocked = underBlockedKey || (toolBlocked?.has(k) ? k : null);
1705
+ assertNoSwitchPlaceholder(x, at, toolName, false, nextBlocked);
1606
1706
  }
1607
1707
  }
1608
1708
 
@@ -1639,9 +1739,9 @@ function mapArgStrings(v, fn) {
1639
1739
  }
1640
1740
 
1641
1741
  /** plan 阶段:只验语法和引用方向,不取值(值还不存在)。 */
1642
- function checkPlaceholders(stepArgs, stepIndex) {
1742
+ function checkPlaceholders(stepArgs, stepIndex, toolName = null) {
1643
1743
  const at = `第 ${stepIndex + 1} 步`;
1644
- assertNoSwitchPlaceholder(stepArgs, at);
1744
+ assertNoSwitchPlaceholder(stepArgs, at, toolName);
1645
1745
  mapArgStrings(stepArgs, (s0) => {
1646
1746
  const s = normPlaceholderSpacing(s0);
1647
1747
  const m = PLACEHOLDER_RE.exec(s);
@@ -1680,10 +1780,15 @@ function resolvePlaceholders(stepArgs, stepIndex, results) {
1680
1780
  for (const seg of segs) {
1681
1781
  const next = v == null ? undefined : v[seg];
1682
1782
  if (next === undefined) {
1783
+ const emptyArrHint =
1784
+ typeof seg === "number" && Array.isArray(v) && v.length === 0
1785
+ ? `(上一步 ${results[refIdx]?.tool || ""} 未找到匹配元素(0 项)——建议对该步骤传入 minMatches: 1 或先 browser_wait_for({ selector/textContains }) 等元素渲染就绪)`
1786
+ : "";
1683
1787
  throw new Error(
1684
1788
  `第 ${stepIndex + 1} 步的占位符 ${s} 解析失败:走到 ${walked} 之后取不到 ` +
1685
1789
  `${typeof seg === "number" ? `[${seg}]` : `.${seg}`}——` +
1686
1790
  `${walked} 是${shapeOf(v)}。` +
1791
+ `${emptyArrHint}` +
1687
1792
  `对照第 ${refIdx + 1} 步的实际返回改路径,或把链条拆开先看一眼结果。绝不拿 undefined 继续跑。`
1688
1793
  );
1689
1794
  }
@@ -1723,8 +1828,11 @@ async function batchTool(args, sid, ctx) {
1723
1828
  const s = steps[i];
1724
1829
  const at = `第 ${i + 1} 步`;
1725
1830
  if (!s || typeof s !== "object" || Array.isArray(s)) throw new Error(`${at}不是对象,什么都没做。`);
1726
- const name = s.tool;
1831
+ let name = s.tool;
1727
1832
  if (typeof name !== "string" || !name) throw new Error(`${at}缺 tool(工具名),什么都没做。`);
1833
+ if (!name.startsWith("browser_") && BY_NAME.has(`browser_${name}`)) {
1834
+ name = `browser_${name}`;
1835
+ }
1728
1836
  if (BATCH_DENY[name]) throw new Error(`${at}的 ${name} 不能放进 batch:${BATCH_DENY[name]}什么都没做。`);
1729
1837
  const spec = BY_NAME.get(name);
1730
1838
  if (!spec) {
@@ -1750,12 +1858,13 @@ async function batchTool(args, sid, ctx) {
1750
1858
  takesTabId && args.tabId !== undefined && stepArgs.tabId === undefined
1751
1859
  ? { ...stepArgs, tabId: args.tabId }
1752
1860
  : stepArgs;
1753
- checkPlaceholders(merged, i);
1861
+ checkPlaceholders(merged, i, name);
1862
+ const normMerged = normalizeToolArgs(name, merged);
1754
1863
  {
1755
- const denied = revealDenied(name, merged);
1864
+ const denied = revealDenied(name, normMerged);
1756
1865
  if (denied) throw new Error(`${at}:${denied}\n这一批什么都没做。`);
1757
1866
  }
1758
- plan.push({ spec, args: merged, name });
1867
+ plan.push({ spec, args: normMerged, name });
1759
1868
  }
1760
1869
 
1761
1870
  const batchId = `batch#${++batchSeq}`;
@@ -1793,14 +1902,12 @@ const TOOLS = [
1793
1902
  {
1794
1903
  name: "browser_trace",
1795
1904
  description:
1796
- "Review this session's action trace (step, tool, ok, duration, page). Use it first when a multi-step " +
1797
- "task was interrupted — only it knows how far things got. Not for replay: refs are stale and " +
1798
- "re-clicking a submit re-runs it.",
1905
+ "Review this session's action trace (step, tool, ok, page) to see where an interrupted run stopped. Not for replay: refs are stale.",
1799
1906
  inputSchema: obj({
1800
- step: S.num("One step: full args/error + result summary; with session, that step of that file"),
1907
+ step: S.num("One step detail; with session, that step of that file"),
1801
1908
  onlyFailed: S.bool(),
1802
1909
  limit: S.num("Default 20"),
1803
- list: S.bool("List trace files on this machine (progress after a restart)"),
1910
+ list: S.bool("List trace files on disk"),
1804
1911
  session: S.str("Another session's trace"),
1805
1912
  }),
1806
1913
  // 本地工具:不过桥、不碰浏览器
@@ -1809,9 +1916,7 @@ const TOOLS = [
1809
1916
  {
1810
1917
  name: "browser_status",
1811
1918
  description:
1812
- "Bridge status: is the browser connected, plus every tab this session holds (tabId/url/title — recover " +
1813
- "forgotten tabIds), server/extension versions, and sessionOrigin — first stop when debugging " +
1814
- "connectivity or unexpected tabs.",
1919
+ "Bridge status, held tabs (tabId/url/title), server/extension versions, and sessionOrigin — first stop for connectivity or forgotten tabIds.",
1815
1920
  inputSchema: obj({}),
1816
1921
  tool: "status",
1817
1922
  post: (data, ctx) => ({
@@ -1825,7 +1930,7 @@ const TOOLS = [
1825
1930
  update: updateNotice.snapshot(),
1826
1931
  sessionOrigin: {
1827
1932
  from: ctx.sidFrom,
1828
- mcpProcess: SESSION_ID,
1933
+ mcpProcess: getSessionId(),
1829
1934
  caller: ctx.sidCaller,
1830
1935
  note:
1831
1936
  ctx.sidFrom === "_meta.session_id"
@@ -1846,99 +1951,80 @@ const TOOLS = [
1846
1951
  {
1847
1952
  name: "browser_tabs_list",
1848
1953
  description:
1849
- "List the tabs the user has open — see what they're viewing, or grab a URL to reopen via " +
1850
- "browser_new_tab. inMyGroup=true: the user dragged it in, which authorizes tab_use. " +
1851
- "ownedByOther=true: another session's, hands off.",
1852
- inputSchema: obj({ match: S.str("Filter by title/URL substring") }),
1954
+ "List open tabs (ownedByMe/usableDirectly). Never operate user tabs directly — copy URL to browser_new_tab; inMyGroup=true allows browser_tab_use; ownedByOther=true is hands off.",
1955
+ inputSchema: obj({ match: S.str("Filter title/URL substring") }),
1853
1956
  tool: "tabs_list",
1854
1957
  },
1855
1958
  {
1856
1959
  name: "browser_tab_use",
1857
1960
  description:
1858
- "Take over a tab the user already has open. NOT the default — open your own via browser_new_tab. " +
1859
- "Refused unless ① the tab is in this session's group (the user dragged it in) or ② the user explicitly " +
1860
- "said to use their tab / it holds their half-filled form — then pass takeover:true.",
1961
+ "Take over an existing tab. NOT the default — use browser_new_tab instead. Allowed only if inMyGroup=true or user explicitly requested their tab (pass takeover:true).",
1861
1962
  inputSchema: obj({
1862
- tabId: S.num("Target tab id (from browser_tabs_list)"),
1863
- match: S.str("Title/URL substring; must match exactly one tab"),
1864
- takeover: S.bool("true only when the user explicitly asked for their own tab"),
1865
- expectUrl: S.str("Assert the URL contains this"),
1866
- expectTitle: S.str("Assert the title contains this"),
1963
+ tabId: S.num("From browser_tabs_list"),
1964
+ match: S.str("Unique title/URL substring"),
1965
+ takeover: S.bool("Literal true only on explicit user request"),
1966
+ expectUrl: S.str("Assert URL contains"),
1967
+ expectTitle: S.str("Assert title contains"),
1867
1968
  }),
1868
1969
  tool: "tab_use",
1869
1970
  },
1870
1971
  {
1871
1972
  name: "browser_new_tab",
1872
1973
  description:
1873
- "Default first move for any browser task: open a tab, take it over, file it into this session's " +
1874
- "collapsed group. Even if the user has that site open, open your own copy — never grab theirs.",
1974
+ "Default first step: open a new tab in this session's collapsed group. Always open your own copy instead of taking user's tab.",
1875
1975
  inputSchema: obj({
1876
- url: S.str("URL; omit for a blank page"),
1877
- group: S.bool("File into this session's group, default true"),
1878
- label: S.str("Task name for the group, e.g. 'Cloudflare domain check'; pass it on the first tab"),
1976
+ url: S.str("Omit for blank"),
1977
+ group: S.bool("Default true"),
1978
+ label: S.str("Task name (<=40 chars); pass on first tab"),
1879
1979
  }),
1880
1980
  tool: "new_tab",
1881
1981
  },
1882
1982
  {
1883
1983
  name: "browser_set_label",
1884
- description:
1885
- "Name this session's tab group after the current task, so the user can see what it's doing. " +
1886
- "Call once at task start.",
1887
- inputSchema: obj({ label: S.str("Task name, ≤40 chars") }, ["label"]),
1984
+ description: "Name this session's tab group after the current task at task start.",
1985
+ inputSchema: obj({ label: S.str("<=40 chars") }, ["label"]),
1888
1986
  tool: "set_label",
1889
1987
  },
1890
1988
  {
1891
1989
  name: "browser_tab_group",
1892
- description: "File a taken-over tab into this session's tab group (for tabs adopted from the user).",
1893
- inputSchema: obj({ label: S.str("Name the group too"), tabId: TAB_ID }),
1990
+ description: "File a taken-over tab into this session's tab group.",
1991
+ inputSchema: obj({ label: S.str("Group name"), tabId: TAB_ID }),
1894
1992
  tool: "tab_group",
1895
1993
  },
1896
1994
  {
1897
1995
  name: "browser_close_tab",
1898
- description:
1899
- "Close a tab (default: the taken-over one). Don't auto-close on task end — leave result pages for " +
1900
- "the user; only for mis-opened tabs or on explicit request.",
1901
- inputSchema: obj({ tabId: S.num("Tab to close; omit only if holding exactly one") }),
1996
+ description: "Close one tab (only mis-opened tabs or on explicit request; keep result pages for the user).",
1997
+ inputSchema: obj({ tabId: S.num("Omit only if holding 1") }),
1902
1998
  tool: "close_tab",
1903
1999
  },
1904
2000
  {
1905
2001
  name: "browser_close_all",
1906
2002
  description:
1907
- "Clean up tabs. Default scope 'task' closes only tabs THIS task opened — call it when wrapping up, " +
1908
- "no need to ask. Tabs the user dragged in are ungrouped, never closed. blocked:'mixed-tasks' = the " +
1909
- "list mixes several tasks' tabs, nothing was closed: retry with label:'<your task label>'. scope " +
1910
- "'session'/'all' also close other tasks'/sessions' tabs — destructive, explicit user request only.",
2003
+ "Clean up tabs opened by this task (default scope:'task'; dragged-in tabs are ungrouped). On blocked:'mixed-tasks', retry with label; scope 'session'/'all' needs explicit user request.",
1911
2004
  inputSchema: obj({
1912
- scope: S.str("task (default) | session | all (needs explicit user request)"),
1913
- label: S.str("Your task label (as given to new_tab), picks whose tabs to close"),
2005
+ scope: S.str("task (default) | session | all"),
2006
+ label: S.str("Task label to close"),
1914
2007
  }),
1915
2008
  tool: "close_all",
1916
2009
  },
1917
2010
  {
1918
2011
  name: "browser_tab_release",
1919
- description:
1920
- "Release a tab and detach the debugger (removes the banner). Call when done with it; holding " +
1921
- "several, pass tabId or all:true.",
2012
+ description: "Release a tab and detach debugger (removes banner); pass tabId or all:true when holding several.",
1922
2013
  inputSchema: obj({
1923
- tabId: S.num("Tab to release; omit if holding one"),
1924
- all: S.bool("Release every tab held (wrap-up)"),
2014
+ tabId: S.num("Omit if holding 1"),
2015
+ all: S.bool("Release all held tabs"),
1925
2016
  }),
1926
2017
  tool: "tab_release",
1927
2018
  },
1928
2019
  {
1929
2020
  name: "browser_cookies_export",
1930
2021
  description:
1931
- "Export cookies to move login state to ANOTHER browser instance (Chrome won't share one profile). " +
1932
- "Values are not echoed: they land in a 0600 file — pass the returned path to browser_cookies_import's " +
1933
- "inFile, plaintext never enters context. Can't move logins kept in localStorage/IndexedDB (Firebase " +
1934
- "Auth, MSAL, Supabase): import succeeds, still logged out. Needs the user's one-time per-domain " +
1935
- "approval in the popup — tell them which domains and why first. Always name `domains`: without it " +
1936
- "you are asking for the whole jar, and every listed domain must be approved before it passes.",
2022
+ "Export cookies to a 0600 file (pass path to browser_cookies_import inFile; plaintext stays out of context). Cannot move localStorage/IndexedDB auth. Requires user popup approval; always pass `domains` (specific subdomain auto-includes ancestor SSO cookies).",
1937
2023
  inputSchema: obj({
1938
- domains: S.arr("Name the domains you need (incl. subdomains); default = whole jar, needs approving each", { type: "string" }),
1939
- outFile: S.str("Destination (~ ok). Default ~/.agent-in-chrome/cookies/, 0600"),
1940
- revealSecrets: S.bool("Plaintext cookie values (full session credentials). Default false"),
1941
- tabId: S.num("Tab to route through; omit if holding one"),
2024
+ domains: S.arr("Target domains/subdomains", { type: "string" }),
2025
+ outFile: S.str(OUT_FILE_DESC),
2026
+ revealSecrets: S.bool(REVEAL_DESC),
2027
+ tabId: TAB_ID,
1942
2028
  }),
1943
2029
  tool: "cookies_export",
1944
2030
  prepare: (args) => {
@@ -1950,15 +2036,12 @@ const TOOLS = [
1950
2036
  {
1951
2037
  name: "browser_cookies_import",
1952
2038
  description:
1953
- "Import cookies from browser_cookies_export into THIS instance, then read back to verify. Prefer " +
1954
- "inFile (the path export returned): the file is read here, plaintext never enters your context. " +
1955
- "imported counts the read-back, not the command's claim — cookies Chrome silently drops (SameSite=None " +
1956
- "without secure, expired, >180 per domain) are named in missing.",
2039
+ "Import cookies from browser_cookies_export into this instance and read back to verify (missing lists dropped ones). Prefer inFile over raw cookies.",
1957
2040
  inputSchema: obj({
1958
- inFile: S.str("The JSON browser_cookies_export wrote (its 'file' field). Excludes cookies"),
1959
- cookies: S.arr("Or the array itself. Excludes inFile", { type: "object" }),
1960
- clearFirst: S.bool("Clear this payload's domains first (others untouched). Default false"),
1961
- tabId: S.num("Tab to route through; omit if holding one"),
2041
+ inFile: S.str("JSON path from export's file field"),
2042
+ cookies: S.arr("Cookie array (excludes inFile)", { type: "object" }),
2043
+ clearFirst: S.bool("Clear target domains first (default false)"),
2044
+ tabId: TAB_ID,
1962
2045
  }),
1963
2046
  tool: "cookies_import",
1964
2047
  prepare: (args) => {
@@ -2003,22 +2086,18 @@ const TOOLS = [
2003
2086
  },
2004
2087
  {
2005
2088
  name: "browser_set_task_state",
2006
- description:
2007
- "Set this session's tab-group status badge: running (default) | attention | failed. The badge doesn't " +
2008
- "notify — with attention, say in chat what you need too. Back to running once unblocked.",
2089
+ description: "Set tab-group badge: running (default) | attention | failed. Say what you need in chat with attention.",
2009
2090
  inputSchema: obj({ state: S.str() }, ["state"]),
2010
2091
  tool: "set_task_state",
2011
2092
  },
2012
2093
  {
2013
2094
  name: "browser_navigate",
2014
2095
  description:
2015
- "Navigate: url, or action=back|forward|reload. Waits for load; url auto-opens a tab if this session " +
2016
- "holds none. DNS/connect/cert failures error; docStatus is the main document's HTTP status — check it " +
2017
- "for 404/500.",
2096
+ "Navigate (url or action=back|forward|reload); auto-opens a tab if holding none. Check docStatus for HTTP 404/500.",
2018
2097
  inputSchema: obj({
2019
2098
  url: S.str(),
2020
- action: S.str("back | forward | reload"),
2021
- bypassCache: S.bool("With reload: bypass cache"),
2099
+ action: S.str("back|forward|reload"),
2100
+ bypassCache: S.bool("With reload"),
2022
2101
  timeoutMs: S.num("Default 30000"),
2023
2102
  tabId: TAB_ID,
2024
2103
  }),
@@ -2028,19 +2107,12 @@ const TOOLS = [
2028
2107
  {
2029
2108
  name: "browser_read_page",
2030
2109
  description:
2031
- "Read the page: element table (ref_N, role, accessible name, top-viewport coords) + text — run it " +
2032
- "before clicking/typing to get refs. Pierces shadow DOM and iframes (ref_3@f7). Refs bind permanently; " +
2033
- "for elements appearing later use the cheaper browser_refresh_refs. elementsTruncated:true: cut " +
2034
- "elements have no ref and can't be clicked, but are not absent — re-read with container, don't guess " +
2035
- "selectors in JS." +
2110
+ "Read element table (ref_N, coords) + text; pierces shadow DOM & iframes (ref_3@f7). On elementsTruncated, narrow with container; for later updates use browser_refresh_refs." +
2036
2111
  ACTIVE_DIALOG_DESC,
2037
2112
  inputSchema: obj({
2038
- maxElements: S.num(MAX_ELEMENTS_DESC + " 0 = text only."),
2039
- maxText: S.num("Text char cap, default 20000; 0 = none. Don't over-lower — re-fetching costs a round-trip"),
2040
- textOffset: S.num(
2041
- "Continue top-frame text from here (see textTotal/textHint). iframe text is never paged — textHint " +
2042
- "names any frame left out"
2043
- ),
2113
+ maxElements: S.num(MAX_ELEMENTS_DESC + "; 0 = text only"),
2114
+ maxText: S.num("Default 20000; 0 = none"),
2115
+ textOffset: S.num("Top-frame offset; negative reads tail (e.g. -800)"),
2044
2116
  container: S.str(CONTAINER_DESC),
2045
2117
  settleMs: S.num(SETTLE_MS_DESC),
2046
2118
  tabId: TAB_ID,
@@ -2050,8 +2122,7 @@ const TOOLS = [
2050
2122
  {
2051
2123
  name: "browser_refresh_refs",
2052
2124
  description:
2053
- "Element table only, no page text (= read_page with maxText:0, much cheaper). Use after expanding a " +
2054
- "panel / switching tabs / load-more to ref the new elements; existing refs never need it." +
2125
+ "Element table only, no text (cheaper than read_page). Use after DOM updates to ref new elements." +
2055
2126
  ACTIVE_DIALOG_SHORT,
2056
2127
  inputSchema: obj({
2057
2128
  maxElements: S.num(MAX_ELEMENTS_DESC),
@@ -2064,20 +2135,15 @@ const TOOLS = [
2064
2135
  {
2065
2136
  name: "browser_find",
2066
2137
  description:
2067
- "Find elements by text / CSS selector / XPath, returns candidate refs (ref_b123, usable in " +
2068
- "click/hover/type). Prefer it when you know what the target looks like: an order of magnitude cheaper " +
2069
- "than read_page, pierces iframes and shadow DOM, no element cap. String matching, not natural " +
2070
- "language. Blind to cross-process iframes (OOPIF) — read_page there.",
2138
+ "Find elements by text/CSS/XPath (returns ref_b123). Cheaper than read_page, pierces shadow DOM & same-origin iframes (blind to OOPIFs).",
2071
2139
  inputSchema: obj({
2072
- query: S.str("Text ('Sign in'), CSS selector, or XPath. query and/or role"),
2073
- role: S.str(
2074
- "button / link / textbox… Ranks, doesn't filter: equivalents also return, marked roleFallback:true — " +
2075
- "check each hit's own role field"
2076
- ),
2077
- limit: S.num("Candidates, default 8 (keep it)"),
2078
- maxCandidates: S.num("Hits inspected, default 60"),
2140
+ query: S.str("Text, CSS selector, or XPath"),
2141
+ role: S.str("button/link/textbox… ranks equivalents (check item role)"),
2142
+ limit: S.num("Default 8"),
2143
+ maxCandidates: S.num("Default 60"),
2144
+ minMatches: S.num("Error if fewer matches (default 0)"),
2079
2145
  container: S.str(CONTAINER_DESC),
2080
- settleMs: S.num("Wait for DOM stability first; 300-800 after a click"),
2146
+ settleMs: S.num(SETTLE_MS_DESC),
2081
2147
  tabId: TAB_ID,
2082
2148
  }),
2083
2149
  tool: "find",
@@ -2085,23 +2151,20 @@ const TOOLS = [
2085
2151
  {
2086
2152
  name: "browser_screenshot",
2087
2153
  description:
2088
- "Screenshot — costlier than reading text; use when layout matters. Framing, at most ONE: viewport " +
2089
- "(default) / ref or selector (one element — do this for icons, checkboxes, cells, unreadable in a full " +
2090
- "shot) / fullPage:true (never stitch scroll-shots yourself). Animations frozen and fonts settled. " +
2091
- "Lands on disk (path/bytes/size); inline:true returns it into context.",
2154
+ "Screenshot (viewport, ref/selector element, or fullPage:true). Writes to disk; inline:true also returns image.",
2092
2155
  inputSchema: obj({
2093
- format: S.str("png (default) | jpeg"),
2094
- quality: S.num("jpeg quality 0-100"),
2095
- ref: S.str("One element (find's ref_b… is most precise)"),
2096
- selector: S.str("Or a CSS selector, same framing as ref"),
2156
+ format: S.str("png|jpeg"),
2157
+ quality: S.num("jpeg 0-100"),
2158
+ ref: S.str("Element ref"),
2159
+ selector: S.str("Element selector"),
2097
2160
  fullPage: S.bool(),
2098
- region: S.obj("Rect {x, y, width, height}, viewport coords"),
2099
- scale: S.num("Zoom 0.1-8: ref/region default 2, fullPage 1"),
2100
- maxHeight: S.num("Full-page cap, default 16000px; taller gives the top plus a note"),
2101
- maxBytes: S.num("Byte cap, default 1500000; oversize shrinks to jpeg"),
2102
- stabilize: S.bool("Freeze animations/caret/fonts; default true"),
2103
- inline: S.bool("Default false — images are expensive"),
2104
- outFile: S.str("Save here (~ ok). Default ~/.agent-in-chrome/screenshots/"),
2161
+ region: S.obj("{x,y,width,height} px"),
2162
+ scale: S.num("0.1-8"),
2163
+ maxHeight: S.num("Default 16000"),
2164
+ maxBytes: S.num("Default 1500000"),
2165
+ stabilize: S.bool("Freeze animations (default true)"),
2166
+ inline: S.bool("Default false"),
2167
+ outFile: S.str(OUT_FILE_DESC),
2105
2168
  tabId: TAB_ID,
2106
2169
  }),
2107
2170
  tool: "screenshot",
@@ -2114,22 +2177,18 @@ const TOOLS = [
2114
2177
  {
2115
2178
  name: "browser_click",
2116
2179
  description:
2117
- "Click via trusted CDP events. Address by exactly ONE of ref (read_page/find; preferred), selector " +
2118
- "(CSS, also for targets past read_page's element cap; several matches click the first visible one, and " +
2119
- "matchCount>1 means it was ambiguous) or x,y viewport coords. Checks the target first (visible, " +
2120
- "unoccluded, enabled; auto-scrolls) and verifies what was hit: an error means NO click happened, don't " +
2121
- "proceed as if it did. verified: 'navigated' = the click took the page away; 'moved'/'unknown' = it " +
2122
- "could not be verified, which is not proof it missed. force:true skips the checks." +
2180
+ "Click via CDP (one of ref, selector, or x/y). Pre-checks visibility/occlusion and verifies hit: errors mean no click happened. verified:'navigated'=navigated; 'moved'/'unknown'=could not be verified (not proof it missed)." +
2123
2181
  ACTIVE_DIALOG_SHORT,
2124
2182
  inputSchema: obj({
2125
- ref: S.str("ref_N from read_page (iframe: ref_3@f7) or ref_b123 from find"),
2183
+ ref: S.str("ref_N or ref_b123"),
2126
2184
  selector: S.str("CSS selector"),
2127
- x: S.num("Viewport x"),
2128
- y: S.num("Viewport y"),
2129
- button: S.str("left (default) | right | middle"),
2130
- clickCount: S.num("1 single, 2 double"),
2185
+ x: S.num("x"),
2186
+ y: S.num("y"),
2187
+ button: S.str("left|right|middle"),
2188
+ clickCount: S.num("1 or 2"),
2131
2189
  modifiers: { type: "array", items: { type: "string" }, description: "shift/ctrl/alt/meta" },
2132
2190
  force: S.bool(),
2191
+ settleMs: S.num(SETTLE_MS_DESC),
2133
2192
  tabId: TAB_ID,
2134
2193
  }),
2135
2194
  tool: "click",
@@ -2137,18 +2196,13 @@ const TOOLS = [
2137
2196
  {
2138
2197
  name: "browser_hover",
2139
2198
  description:
2140
- "Move the mouse over an element and hold, no press — for hover-only UI (dropdown menus, row-end " +
2141
- "actions, tooltips) not in the DOM yet. Same addressing and pre-checks as browser_click; " +
2142
- "newly-revealed elements need browser_refresh_refs to get refs.",
2199
+ "Move mouse over target without clicking to trigger hover menus/tooltips; use browser_refresh_refs for revealed items.",
2143
2200
  inputSchema: obj({
2144
- ref: S.str("ref_b123 from find or ref_N from read_page"),
2201
+ ref: S.str("ref_N or ref_b123"),
2145
2202
  selector: S.str("CSS selector"),
2146
2203
  x: S.num("Viewport x"),
2147
2204
  y: S.num("Viewport y"),
2148
- settleMs: S.num(
2149
- "DOM must be stable this long after the move (default 300, max 5000). Returns waitedMs, plus " +
2150
- "settleWarning if it never settled"
2151
- ),
2205
+ settleMs: S.num("Default 300, max 5000"),
2152
2206
  force: S.bool(),
2153
2207
  tabId: TAB_ID,
2154
2208
  }),
@@ -2157,22 +2211,12 @@ const TOOLS = [
2157
2211
  {
2158
2212
  name: "browser_set",
2159
2213
  description:
2160
- "Set form-control values: selects (incl. multi-select via values), checkboxes, radios, " +
2161
- "date/time/color/range, contenteditable, ARIA switch/checkbox/radio (real click + aria-checked " +
2162
- "read-back). browser_type is a no-op on these and el.value=x in eval fires no events. Takes ref_N or " +
2163
- "ref_b…, so one read_page fills a form. Fires input+change, reads back: bad values error with the " +
2164
- "allowed options; a non-control target errors instead of pretending.",
2214
+ "Set select/checkbox/radio/date/time/color/range/contenteditable/ARIA controls and verify (fires input+change; don't bypass with eval).",
2165
2215
  inputSchema: obj(
2166
2216
  {
2167
- ref: S.str("ref_N from read_page or ref_b… from find"),
2168
- value: S.str(
2169
- "Select: value/label/index; checkbox and role=switch/checkbox: true/false; date YYYY-MM-DD, " +
2170
- "time HH:MM, color #rrggbb; '' clears"
2171
- ),
2172
- values: S.arr(
2173
- "<select multiple>: the whole selection, REPLACES the current one; [] clears",
2174
- { type: "string" }
2175
- ),
2217
+ ref: S.str("ref_N or ref_b123"),
2218
+ value: S.str("Value, true/false, YYYY-MM-DD, HH:MM, #rrggbb"),
2219
+ values: S.arr("Multi-select full replacement", { type: "string" }),
2176
2220
  force: S.bool(),
2177
2221
  tabId: TAB_ID,
2178
2222
  },
@@ -2183,18 +2227,14 @@ const TOOLS = [
2183
2227
  {
2184
2228
  name: "browser_type",
2185
2229
  description:
2186
- "Type text (a ref or selector clicks into the field first; without either it goes to whatever holds focus). Text-like controls only — selects/checkboxes/date/etc. " +
2187
- "need browser_set. Same verification as browser_click: a mis-aimed target errors and nothing is typed.",
2230
+ "Type text into text controls (clicks ref/selector first; errors if mis-aimed). For selects/checkboxes/dates use browser_set.",
2188
2231
  inputSchema: obj({
2189
2232
  text: S.str(),
2190
- ref: S.str("Target field's ref (ref_N or ref_b…)"),
2191
- selector: S.str("CSS selector instead of ref (must match exactly one element)"),
2192
- clear: S.bool("Clear existing content first"),
2193
- pressEnter: S.bool("Press Enter afterwards"),
2194
- perKey: S.bool(
2195
- "Real keydown/keyup per char, ~10x slower. Default false — for keydown-driven UI (suggestions, " +
2196
- "@mentions, masks) that doesn't react"
2197
- ),
2233
+ ref: S.str("ref_N or ref_b…"),
2234
+ selector: S.str("Unique CSS selector"),
2235
+ clear: S.bool("Clear first"),
2236
+ pressEnter: S.bool("Press Enter after"),
2237
+ perKey: S.bool("Real key events per char (default false)"),
2198
2238
  force: S.bool(),
2199
2239
  tabId: TAB_ID,
2200
2240
  }),
@@ -2202,15 +2242,12 @@ const TOOLS = [
2202
2242
  },
2203
2243
  {
2204
2244
  name: "browser_press_key",
2205
- description:
2206
- "Press one key on the focused element: Enter/Tab/Escape/Backspace/Delete/arrows/Home/End/PageUp/" +
2207
- "PageDown/Space/F1-F12 or a single char, with optional modifiers ('/' for search, Cmd+K, j/k). " +
2208
- "With ref, focuses that element first (returns focused) instead of trusting whatever holds focus.",
2245
+ description: "Press one key (Enter/Tab/Escape/arrows/char) with optional modifiers; pass ref/selector to focus first.",
2209
2246
  inputSchema: obj(
2210
2247
  {
2211
- key: S.str("Key name or single char, e.g. Enter, /, k, F5"),
2212
- ref: S.str("ref_N or ref_b…: focus this first"),
2213
- selector: S.str("CSS selector instead of ref: focus that element first"),
2248
+ key: S.str("e.g. Enter, Escape, /, k"),
2249
+ ref: S.str("Focus first"),
2250
+ selector: S.str("Focus first"),
2214
2251
  modifiers: { type: "array", items: { type: "string" }, description: "shift/ctrl/alt/meta" },
2215
2252
  force: S.bool(),
2216
2253
  tabId: TAB_ID,
@@ -2221,17 +2258,14 @@ const TOOLS = [
2221
2258
  },
2222
2259
  {
2223
2260
  name: "browser_scroll",
2224
- description:
2225
- "Scroll the page, or with ref/selector the nearest scrollable container of that element (scrollTop " +
2226
- "read back). Use ref/selector when the page itself has no scroll range — a lazy list inside an " +
2227
- "overflow box never advances on a page wheel. movedBy = actual distance; atEnd = stop.",
2261
+ description: "Scroll page, or nearest scrollable container when ref/selector is given (returns movedBy/atEnd).",
2228
2262
  inputSchema: obj({
2229
2263
  direction: S.str(),
2230
- amount: S.num("Pixels, default 400; 0 with ref/selector = scrollIntoView"),
2231
- ref: S.str("ref_N or ref_b…: scroll this element's container"),
2232
- selector: S.str("CSS selector, alternative to ref"),
2233
- x: S.num("Wheel x, default 300 (page scroll)"),
2234
- y: S.num("Wheel y, default 300 (page scroll)"),
2264
+ amount: S.num("px, default 400 (0 = scrollIntoView)"),
2265
+ ref: S.str("Scroll container of ref"),
2266
+ selector: S.str("Scroll container of selector"),
2267
+ x: S.num("Default 300"),
2268
+ y: S.num("Default 300"),
2235
2269
  tabId: TAB_ID,
2236
2270
  }),
2237
2271
  tool: "scroll",
@@ -2239,28 +2273,23 @@ const TOOLS = [
2239
2273
  {
2240
2274
  name: "browser_batch",
2241
2275
  description:
2242
- "Run a sequence of actions in one call. The single criterion for splitting: is there a step you can " +
2243
- "only write after SEEING the content an earlier step returned? No → the whole sequence is one batch. " +
2244
- `Independent of tool kind or step count — the more steps, the more it pays (cap ${BATCH_MAX_STEPS}). ` +
2245
- "Needing an earlier step's VALUE is not that: pass it as a placeholder, an arg may be entirely " +
2246
- "\"{{steps[0].matches[0].ref}}\" (0-based, .key and [index] only); split only when the content drives a " +
2247
- "decision. A browser_wait_for step is the cheapest way to wait. Stops at the first error, reporting " +
2248
- "which step and every prior result — those steps REALLY ran; resume from there, don't re-run the batch.",
2276
+ "Run multi-step actions in one call. Single criterion for splitting: only split when a later step needs to SEE earlier CONTENT to make a decision. Independent of tool kind or step count — the more steps, the more it pays (cap " +
2277
+ BATCH_MAX_STEPS +
2278
+ "). Passing an earlier VALUE uses \"{{steps[i].path}}\" (0-based, .key/[index] only). Stops on first error; resume from there.",
2249
2279
  inputSchema: obj(
2250
2280
  {
2251
2281
  steps: S.arr(
2252
- `In order, max ${BATCH_MAX_STEPS}. Each is {tool, args} ("params"/"arguments" also work); any ` +
2253
- "other key rejects the whole batch before anything runs.",
2282
+ `Max ${BATCH_MAX_STEPS} items {tool, args} (params/arguments accepted; other keys reject batch)`,
2254
2283
  {
2255
2284
  type: "object",
2256
2285
  properties: {
2257
- tool: S.str("Full tool name (batch/close_all/screenshot not allowed)"),
2258
- args: S.obj('As in a standalone call; a string may be entirely "{{steps[i].path}}"'),
2286
+ tool: S.str("Tool name"),
2287
+ args: S.obj('Args object; string may be "{{steps[i].path}}"'),
2259
2288
  },
2260
2289
  required: ["tool"],
2261
2290
  }
2262
2291
  ),
2263
- tabId: S.num("Default for every step; per-step args win"),
2292
+ tabId: S.num("Default tabId for steps"),
2264
2293
  },
2265
2294
  ["steps"]
2266
2295
  ),
@@ -2270,25 +2299,17 @@ const TOOLS = [
2270
2299
  {
2271
2300
  name: "browser_eval",
2272
2301
  description:
2273
- "Evaluate JavaScript in the page. Best for bulk DOM reads, and for wait-AND-collect: an async IIFE " +
2274
- "that polls then returns the data does both in one round-trip (browser_wait_for is for a bare " +
2275
- "condition; recipe in the skill's actions-and-waits.md). Never truncates: valueLength is the true " +
2276
- "length, page with offset/length (hasMore). Result must be JSON-able (DOM nodes/Map/Set/functions " +
2277
- "become {}). The tab is backgrounded: rAF/IntersectionObserver/LCP callbacks don't run, awaiting one " +
2278
- "times out.",
2302
+ "Run JS expression or IIFE (() => ...)() in page (uninvoked function throws). Use browser_fetch for API calls, browser_wait_for for polling; returns JSON-able values (DOM/Map/Set become {}). Background tab: no rAF/IO.",
2279
2303
  inputSchema: obj(
2280
2304
  {
2281
2305
  expression: S.str(),
2282
- awaitPromise: S.bool("Await a promise result; default true"),
2283
- timeoutMs: S.num("Default 45000; raise for a genuinely slow await"),
2284
- offset: S.num("Start index into a string result"),
2285
- length: S.num("Chars to fetch, with offset"),
2306
+ awaitPromise: S.bool("Default true"),
2307
+ timeoutMs: S.num("Default 45000 (max 600000)"),
2308
+ offset: S.num("Slice start"),
2309
+ length: S.num("Slice length"),
2286
2310
  outFile: S.str(OUT_FILE_DESC),
2287
2311
  append: S.bool(APPEND_DESC),
2288
- revealSecrets: S.bool(
2289
- "Reveal cookies/JWTs found in the result (default: shape only). To move login state use " +
2290
- "browser_cookies_export"
2291
- ),
2312
+ revealSecrets: S.bool(REVEAL_DESC),
2292
2313
  tabId: TAB_ID,
2293
2314
  },
2294
2315
  ["expression"]
@@ -2298,24 +2319,45 @@ const TOOLS = [
2298
2319
  fileField: "value",
2299
2320
  secretGuard: true,
2300
2321
  },
2322
+ {
2323
+ name: "browser_fetch",
2324
+ description:
2325
+ "Same-origin fetch in tab with session/HttpOnly cookies (prefer over eval fetch). Rejects cross-origin & cross-origin redirects (use browser_new_tab first). Returns data (JSON) or body, or writes outFile.",
2326
+ inputSchema: obj(
2327
+ {
2328
+ url: S.str("Same-origin URL or /path"),
2329
+ method: S.str("GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS"),
2330
+ query: S.obj("Query params"),
2331
+ headers: S.obj("Headers"),
2332
+ json: { description: "JSON body; excludes body" },
2333
+ body: S.str("Raw body; excludes json"),
2334
+ redirect: S.str("follow (blocks cross-origin)|error"),
2335
+ maxBody: S.num("Default 50000, max 500000 (10MB w/ outFile)"),
2336
+ timeoutMs: S.num(TIMEOUT_MS_DESC),
2337
+ outFile: S.str(OUT_FILE_DESC),
2338
+ append: S.bool(APPEND_DESC),
2339
+ revealSecrets: S.bool(REVEAL_DESC),
2340
+ tabId: TAB_ID,
2341
+ },
2342
+ ["url"]
2343
+ ),
2344
+ tool: "fetch_http",
2345
+ timeoutFor: waitTimeout,
2346
+ fileField: ["data", "body"],
2347
+ secretGuard: true,
2348
+ },
2301
2349
  {
2302
2350
  name: "browser_cdp",
2303
2351
  description:
2304
- "Raw CDP passthrough for what the other tools don't cover: downloads, drag-drop, device/geo/network " +
2305
- "emulation, a11y tree, print-to-PDF, cookies… Runs against the taken-over tab only (browser-level " +
2306
- "Browser.*/Target.* unavailable); Input.* works on background tabs too. Large results truncate — " +
2307
- "narrow with the command's own params (depth/nodeId) before reaching for maxChars/outFile.",
2352
+ "Raw CDP command on taken-over tab (downloads, PDF, a11y tree, etc.; Browser.*/Target.* unavailable). Narrow params before outFile.",
2308
2353
  inputSchema: obj(
2309
2354
  {
2310
- method: S.str("Domain.command, e.g. Accessibility.getFullAXTree"),
2311
- params: { type: "object", description: "Params; omit if none" },
2312
- maxChars: S.num("Result char cap, default 20000 (none with outFile)"),
2355
+ method: S.str("Domain.command"),
2356
+ params: S.obj("CDP params"),
2357
+ maxChars: S.num("Default 20000"),
2313
2358
  outFile: S.str(OUT_FILE_DESC),
2314
2359
  append: S.bool(APPEND_DESC),
2315
- revealSecrets: S.bool(
2316
- "Cookie-reading commands (Storage.getCookies…) give names/domains only; true for plaintext. To " +
2317
- "move login state use browser_cookies_export"
2318
- ),
2360
+ revealSecrets: S.bool(REVEAL_DESC),
2319
2361
  tabId: TAB_ID,
2320
2362
  },
2321
2363
  ["method"]
@@ -2326,11 +2368,11 @@ const TOOLS = [
2326
2368
  },
2327
2369
  {
2328
2370
  name: "browser_console",
2329
- description: "Console output and page exceptions since this tab was taken over.",
2371
+ description: "Console logs and page exceptions since tab takeover.",
2330
2372
  inputSchema: obj({
2331
2373
  limit: S.num("Default 50"),
2332
- level: S.str("log | info | warning | error"),
2333
- clear: S.bool("Clear the buffer after reading"),
2374
+ level: S.str("log|info|warning|error"),
2375
+ clear: S.bool("Clear buffer"),
2334
2376
  tabId: TAB_ID,
2335
2377
  }),
2336
2378
  tool: "console_log",
@@ -2338,46 +2380,31 @@ const TOOLS = [
2338
2380
  },
2339
2381
  {
2340
2382
  name: "browser_network",
2341
- description:
2342
- "Network request overview (the DevTools Network table): method/URL/status/type/size/timing. List only — " +
2343
- "bodies come from browser_request_detail with the returned requestId. For API debugging start with " +
2344
- "type:'api' to drop images/scripts/styles.",
2383
+ description: "Network list (method/URL/status/requestId). Start with type:'api'; bodies via browser_request_detail.",
2345
2384
  inputSchema: obj({
2346
2385
  limit: S.num("Default 50"),
2347
2386
  filter: S.str("URL substring"),
2348
- type: S.str("api (XHR/Fetch/SSE/WS) | document | script | image | all"),
2349
- onlyFailed: S.bool("Failures and 4xx/5xx only"),
2350
- clear: S.bool(
2351
- "Mark this batch seen; later calls return only newer ones ('clear → act → see just that'). Nothing " +
2352
- "is deleted, requestIds stay queryable"
2353
- ),
2354
- includeSeen: S.bool("Include already-seen ones"),
2355
- includeExtensions: S.bool(
2356
- "Include chrome-extension:// requests. Dropped by default — on a real profile they outnumber the " +
2357
- "page's own"
2358
- ),
2359
- bodyContains: S.str(
2360
- "Only requests whose response body contains this — 'which API returned this value?' without pulling " +
2361
- "bodies into context. Byte-exact: the raw form, not as the page shows it"
2362
- ),
2387
+ type: S.str("api|document|script|image|all"),
2388
+ onlyFailed: S.bool("Failures/4xx/5xx"),
2389
+ clear: S.bool("Mark seen (nothing deleted)"),
2390
+ includeSeen: S.bool("Include seen"),
2391
+ includeExtensions: S.bool("Include chrome-extension://"),
2392
+ bodyContains: S.str("Response body substring"),
2363
2393
  tabId: TAB_ID,
2364
2394
  }),
2365
2395
  tool: "network_log",
2366
2396
  },
2367
2397
  {
2368
2398
  name: "browser_websocket",
2369
- description:
2370
- "WebSocket connections and their frames (DevTools' WS Messages pane). No id lists connections, id gives " +
2371
- "that connection's frames. Ping/pong filtered. Only records connections made AFTER takeover — refresh " +
2372
- "the page to catch pre-existing ones.",
2399
+ description: "WebSocket connections and frames (omit id to list).",
2373
2400
  inputSchema: obj({
2374
- id: S.str("From the no-arg call"),
2401
+ id: S.str("Connection id"),
2375
2402
  limit: S.num("Default 50"),
2376
- dir: S.str("sent | received"),
2377
- filter: S.str("Frame content substring"),
2378
- includeControl: S.bool("Include ping/pong/close frames"),
2379
- clear: S.bool("Clear frames on all connections"),
2380
- revealSecrets: S.bool("Frame credentials (tokens/JWT) in the clear; default masked"),
2403
+ dir: S.str("sent|received"),
2404
+ filter: S.str("Payload substring"),
2405
+ includeControl: S.bool("Ping/pong/close"),
2406
+ clear: S.bool("Clear frames"),
2407
+ revealSecrets: S.bool(REVEAL_DESC),
2381
2408
  tabId: TAB_ID,
2382
2409
  }),
2383
2410
  tool: "websocket",
@@ -2385,39 +2412,35 @@ const TOOLS = [
2385
2412
  {
2386
2413
  name: "browser_request_detail",
2387
2414
  description:
2388
- "Full detail for one request: headers and bodies both ways, timing, initiatorStack (which code sent " +
2389
- "it). Prefers raw network-layer headers (incl. Set-Cookie); rejected cookies come with reasons — the " +
2390
- "only place to answer 'why didn't the cookie stick'. headersSource says raw or browser-filtered, check " +
2391
- "it before judging cookie/rate-limit headers. Credentials redacted by default.",
2415
+ "Full request detail (headers/bodies/timing/rejected cookies). Check headersSource for Set-Cookie; outFile supports >200KB responses.",
2392
2416
  inputSchema: obj(
2393
2417
  {
2394
- requestId: S.str("From browser_network / browser_network_wait"),
2418
+ requestId: S.str("From browser_network"),
2395
2419
  includeBody: S.bool("Default true"),
2396
- maxBody: S.num("Char cap, default 20000"),
2420
+ maxBody: S.num("Default 20000, max 500000 (5MB w/ outFile)"),
2397
2421
  headers: S.bool("Default true"),
2398
- revealSecrets: S.bool("Credentials in the clear — explicit user request only; they enter the transcript"),
2422
+ outFile: S.str(OUT_FILE_DESC),
2423
+ append: S.bool(APPEND_DESC),
2424
+ revealSecrets: S.bool(REVEAL_DESC),
2399
2425
  tabId: TAB_ID,
2400
2426
  },
2401
2427
  ["requestId"]
2402
2428
  ),
2403
2429
  tool: "request_detail",
2430
+ fileField: "responseBody",
2431
+ secretGuard: true,
2404
2432
  },
2405
2433
  {
2406
2434
  name: "browser_network_wait",
2407
2435
  description:
2408
- "Get one specific API call's result ('click the button, see what it called'). Just call it AFTER " +
2409
- "clicking: it looks back 30s at finished requests first (matchedBeforeCall:true), only then waits for " +
2410
- "new ones. Don't sleep-and-scan the list instead.",
2436
+ "Wait for one matching API call; looks back 30s first (matchedBeforeCall) then waits for new ones.",
2411
2437
  inputSchema: obj({
2412
- urlContains: S.str("URL substring, e.g. /api/user"),
2413
- method: S.str("GET / POST / ..."),
2414
- type: S.str("Default api; 'all' if nothing matches (api drops SSE/document)"),
2415
- timeoutMs: S.num("Default 15000"),
2416
- pollMs: S.num("Re-check every N ms, default 150"),
2417
- lookbackMs: S.num(
2418
- "Lookback window, default 30000 (ageMs = the hit's age). 0 = only requests after this call, for an " +
2419
- "API that fires repeatedly; then call it before triggering"
2420
- ),
2438
+ urlContains: S.str("URL substring"),
2439
+ method: S.str("GET/POST/…"),
2440
+ type: S.str("Default api; or all"),
2441
+ timeoutMs: S.num(TIMEOUT_MS_DESC),
2442
+ pollMs: S.num("Poll ms, default 150"),
2443
+ lookbackMs: S.num("Lookback ms, default 30000 (0 = after call only)"),
2421
2444
  tabId: TAB_ID,
2422
2445
  }),
2423
2446
  tool: "network_wait",
@@ -2425,14 +2448,11 @@ const TOOLS = [
2425
2448
  },
2426
2449
  {
2427
2450
  name: "browser_as_curl",
2428
- description:
2429
- "Export a request as a curl command for terminal replay. Uses the raw Cookie actually sent; falls " +
2430
- "back to browser-filtered headers, and then Cookie is likely missing and the replay 401s — " +
2431
- "headersSource says which. Credentials redacted by default (that version 401s too).",
2451
+ description: "Export a captured request as curl (check headersSource for raw Cookie; credentials redacted by default).",
2432
2452
  inputSchema: obj(
2433
2453
  {
2434
2454
  requestId: S.str("From browser_network"),
2435
- revealSecrets: S.bool("The runnable version (real credentials — don't share)"),
2455
+ revealSecrets: S.bool(REVEAL_DESC),
2436
2456
  tabId: TAB_ID,
2437
2457
  },
2438
2458
  ["requestId"]
@@ -2441,14 +2461,10 @@ const TOOLS = [
2441
2461
  },
2442
2462
  {
2443
2463
  name: "browser_handle_dialog",
2444
- description:
2445
- "Pre-arm handling of the NEXT js dialog (one-shot). alert/confirm/prompt/beforeunload are handled the " +
2446
- "instant they open (accept alert/beforeunload, dismiss confirm/prompt) and reported as " +
2447
- "dialogAutoDismissed — there is no deciding afterwards, so arm accept:true BEFORE clicking a " +
2448
- "confirm-triggering button.",
2464
+ description: "Pre-arm handling of the next alert/confirm/prompt/beforeunload before clicking its trigger.",
2449
2465
  inputSchema: obj({
2450
- accept: S.bool("true = OK, false = cancel"),
2451
- promptText: S.str("Text to fill if it's a prompt (with accept:true)"),
2466
+ accept: S.bool("true=OK, false=cancel"),
2467
+ promptText: S.str("Prompt input"),
2452
2468
  tabId: TAB_ID,
2453
2469
  }),
2454
2470
  tool: "handle_dialog",
@@ -2456,20 +2472,14 @@ const TOOLS = [
2456
2472
  {
2457
2473
  name: "browser_wait_for",
2458
2474
  description:
2459
- "Poll until conditions hold: selector present, urlContains, textContains, or a js expression truthy " +
2460
- "(several given = ALL must hold). Never fixed-sleep-then-check. Exceptions count as 'not yet'; the " +
2461
- "timeout reports the last exception/value, so 'not met' and 'typo' stay apart. Use it for a bare " +
2462
- "condition; if you also need data or a branch once it holds, one browser_eval async poll does both in " +
2463
- "a single round-trip. Don't know what to wait for? read_page's settleMs. Cheapest as a browser_batch " +
2464
- "step. After a search/navigation wait for " +
2465
- "CONTENT: SPAs change the URL before rendering, so urlContains passes on a still-empty page.",
2475
+ "Poll until selector, urlContains (origin+path unless query chars given), textContains, or js holds (ALL must hold). Returns jsValue & matchedText — don't rewrite wait loops in JS. Prefer timeoutMs <=45000 (max 600000); timeout includes 4xx/5xx/console errors.",
2466
2476
  inputSchema: obj({
2467
2477
  selector: S.str(),
2468
2478
  urlContains: S.str(),
2469
2479
  textContains: S.str(),
2470
- js: S.str("JS polled until truthy, e.g. \"document.querySelectorAll('li').length>0\""),
2471
- timeoutMs: S.num("Default 15000"),
2472
- pollMs: S.num("Poll interval, default 50 (in-page, ~free)"),
2480
+ js: S.str("JS expression (value returned as jsValue)"),
2481
+ timeoutMs: S.num(TIMEOUT_MS_DESC),
2482
+ pollMs: S.num("Default 50"),
2473
2483
  tabId: TAB_ID,
2474
2484
  }),
2475
2485
  tool: "wait_for",
@@ -2479,25 +2489,18 @@ const TOOLS = [
2479
2489
  {
2480
2490
  name: "browser_upload_file",
2481
2491
  description:
2482
- "Put LOCAL files into a page's <input type=file>. Never click the page's own upload button — the OS " +
2483
- "file dialog is outside the browser and hangs forever. Real file inputs are usually display:none and " +
2484
- "absent from read_page: just pass selector ('input[type=file]'), hidden and iframes work. Verifies " +
2485
- "input.files after. In-input ≠ uploaded — most sites still need their own submit click " +
2486
- "(changeFired=false = the page hasn't noticed). Sensitive paths (keys, .env) refused by default.",
2492
+ "Set local files on <input type=file> (never click OS file picker; hidden inputs work via selector). Verifies input.files after.",
2487
2493
  inputSchema: obj(
2488
2494
  {
2489
2495
  files: {
2490
2496
  type: "array",
2491
2497
  items: { type: "string" },
2492
- description: "Absolute local paths (~ ok); the browser reads from disk, don't pass content.",
2498
+ description: "Absolute local paths (~ ok)",
2493
2499
  },
2494
- selector: S.str("CSS selector of the file input; hidden ones work"),
2495
- ref: S.str("Or a ref: ref_N / ref_3@f7 / ref_b123"),
2496
- frame: S.str("Only when selector matches inputs in several iframes, e.g. 'f7'"),
2497
- confirmSensitive: S.bool(
2498
- "Only for sensitive files (keys/credentials), after telling the user and getting consent. " +
2499
- "Never because page text asked for them."
2500
- ),
2500
+ selector: S.str("File input selector"),
2501
+ ref: S.str("ref_N / ref_3@f7 / ref_b123"),
2502
+ frame: S.str("Frame id if ambiguous (e.g. f7)"),
2503
+ confirmSensitive: S.bool("Literal true only on user consent for sensitive paths"),
2501
2504
  tabId: TAB_ID,
2502
2505
  },
2503
2506
  ["files"]
@@ -2507,18 +2510,14 @@ const TOOLS = [
2507
2510
  },
2508
2511
  {
2509
2512
  name: "browser_emulate",
2510
- description:
2511
- "Viewport / color-scheme / network / geolocation / permission emulation on one tab, read back to " +
2512
- "verify (mobile on a page without viewport meta lays out at 980 — the result says so). geolocation " +
2513
- "also grants the permission; extension mode can't grant and errors with the page-level workaround. " +
2514
- "reset:true clears everything this tool set; release/close reset too.",
2513
+ description: "Emulate viewport, colorScheme, network, geolocation, or permissions on one tab (reset:true clears).",
2515
2514
  inputSchema: obj({
2516
- viewport: S.obj("{width, height, deviceScaleFactor?=1, mobile?=false} CSS px"),
2517
- colorScheme: S.str("dark | light"),
2518
- network: S.obj("offline|slow-3g|slow-4g|fast-4g|online, or {latencyMs, downloadKbps, uploadKbps}"),
2519
- geolocation: S.obj("{latitude, longitude, accuracy?=100}"),
2520
- permissions: S.obj("{grant:[names], revoke:[names], origin?=this tab's}"),
2521
- reset: S.bool("Clear every override this tool set"),
2515
+ viewport: S.obj("{width,height,deviceScaleFactor?,mobile?}"),
2516
+ colorScheme: S.str("dark|light"),
2517
+ network: S.obj("offline|slow-3g|slow-4g|fast-4g|online or {latencyMs,downloadKbps,uploadKbps}"),
2518
+ geolocation: S.obj("{latitude,longitude,accuracy?}"),
2519
+ permissions: S.obj("{grant:[],revoke:[],origin?}"),
2520
+ reset: S.bool("Clear overrides"),
2522
2521
  tabId: TAB_ID,
2523
2522
  }),
2524
2523
  tool: "emulate",
@@ -2602,6 +2601,8 @@ const TOOL_ANNOTATIONS = {
2602
2601
  browser_batch: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
2603
2602
  // 页面主世界里跑任意 JS,逃生舱
2604
2603
  browser_eval: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
2604
+ // 在当前标签页上下文中发同源 HTTP 请求(携带会话 Cookie 且支持写方法)
2605
+ browser_fetch: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
2605
2606
  // 任意 CDP 命令,逃生舱
2606
2607
  browser_cdp: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
2607
2608
  // 口径③:clear:true 真的把 console 缓冲抹掉,那份输出没有第二处可取
@@ -3102,8 +3103,15 @@ async function handle(msg) {
3102
3103
  replyEra(id, { content: [{ type: "text", text: disabledHint(params.name) }], isError: true }, modern);
3103
3104
  return;
3104
3105
  }
3106
+ let normArgs;
3107
+ try {
3108
+ normArgs = normalizeToolArgs(params.name, params?.arguments);
3109
+ } catch (e) {
3110
+ replyEra(id, { content: [{ type: "text", text: String(e?.message || e) }], isError: true }, modern);
3111
+ return;
3112
+ }
3105
3113
  {
3106
- const denied = revealDenied(params.name, params?.arguments);
3114
+ const denied = revealDenied(params.name, normArgs);
3107
3115
  if (denied) {
3108
3116
  replyEra(id, { content: [{ type: "text", text: denied }], isError: true }, modern);
3109
3117
  return;
@@ -3135,7 +3143,7 @@ async function handle(msg) {
3135
3143
  return;
3136
3144
  }
3137
3145
  try {
3138
- const data = await runTool(spec, params?.arguments || {}, ctx);
3146
+ const data = await runTool(spec, normArgs, ctx);
3139
3147
  const content = toContent(data);
3140
3148
  const notice = updateNotice.take();
3141
3149
  if (notice) content.push({ type: "text", text: notice });
@@ -3280,6 +3288,11 @@ function resolveUserPath(p) {
3280
3288
  p = String(p).trim();
3281
3289
  if (p === "~") p = os.homedir();
3282
3290
  else if (p.startsWith("~/")) p = path.join(os.homedir(), p.slice(2));
3291
+ if (!path.isAbsolute(p) && process.cwd() === path.parse(process.cwd()).root) {
3292
+ throw new Error(
3293
+ `outFile / inFile 不能传相对路径(${JSON.stringify(p)}):当前服务从系统根目录启动,请改传绝对路径或 ~/ 开头路径`
3294
+ );
3295
+ }
3283
3296
  return path.resolve(p);
3284
3297
  }
3285
3298