browserpilot-cdp 1.2.5 → 1.3.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/dist/cli.js CHANGED
@@ -8,7 +8,7 @@ import path7 from "node:path";
8
8
  import { fileURLToPath as fileURLToPath3 } from "node:url";
9
9
 
10
10
  // ../protocol/dist/constants.js
11
- var BROWSERPILOT_VERSION = "1.2.5";
11
+ var BROWSERPILOT_VERSION = "1.3.0";
12
12
  var DEFAULT_DAEMON_HOST = "127.0.0.1";
13
13
  var DEFAULT_DAEMON_PORT = 19888;
14
14
  var NATIVE_HOST_NAME = "com.browserpilot.bridge";
@@ -704,6 +704,14 @@ var ExtensionBridgeTransport = class {
704
704
  await this.rpc("extension.ghostCursor", { tabId, x, y, clicking }).catch(() => {
705
705
  });
706
706
  }
707
+ async setOverlayVisible(tabId, visible) {
708
+ await this.rpc("extension.setOverlayVisible", { tabId, visible }).catch(() => {
709
+ });
710
+ }
711
+ async setControlBanner(tabId, banner) {
712
+ await this.rpc("extension.setControlBanner", { tabId, ...banner }).catch(() => {
713
+ });
714
+ }
707
715
  async getPinnedElement(tabId) {
708
716
  return await this.rpc("extension.getPinnedElement", { tabId });
709
717
  }
@@ -1780,6 +1788,34 @@ function buttonBitmask(button) {
1780
1788
  return 4;
1781
1789
  return 1;
1782
1790
  }
1791
+ function resolveEditingCommands(key, mods) {
1792
+ const hasAccel = mods.includes("Meta") || mods.includes("Control");
1793
+ const hasShift = mods.includes("Shift");
1794
+ const lower = key.toLowerCase();
1795
+ if (hasAccel && !mods.includes("Alt")) {
1796
+ if (lower === "a" && !hasShift)
1797
+ return ["selectAll"];
1798
+ if (lower === "c" && !hasShift)
1799
+ return ["copy"];
1800
+ if (lower === "x" && !hasShift)
1801
+ return ["cut"];
1802
+ if (lower === "v" && !hasShift)
1803
+ return ["paste"];
1804
+ if (lower === "v" && hasShift)
1805
+ return ["pasteAndMatchStyle"];
1806
+ if (lower === "z" && !hasShift)
1807
+ return ["undo"];
1808
+ if (lower === "z" && hasShift || lower === "y" && !hasShift)
1809
+ return ["redo"];
1810
+ }
1811
+ if (!hasAccel && !mods.includes("Alt")) {
1812
+ if (key === "Backspace")
1813
+ return ["deleteBackward"];
1814
+ if (key === "Delete")
1815
+ return ["deleteForward"];
1816
+ }
1817
+ return [];
1818
+ }
1783
1819
  function resolveKeyDef(keyName) {
1784
1820
  if (SPECIAL_KEYS[keyName])
1785
1821
  return SPECIAL_KEYS[keyName];
@@ -1920,8 +1956,9 @@ var PageController = class {
1920
1956
  }
1921
1957
  if (!box || box.width === 0 && box.height === 0)
1922
1958
  return null;
1959
+ let frameOffset;
1923
1960
  if (sessionId) {
1924
- const frameOffset = await this.getIframeOffset(refTarget?.frameId, sessionId);
1961
+ frameOffset = await this.getIframeOffset(refTarget?.frameId, sessionId);
1925
1962
  box = {
1926
1963
  x: box.x + frameOffset.x,
1927
1964
  y: box.y + frameOffset.y,
@@ -1933,6 +1970,7 @@ var PageController = class {
1933
1970
  objectId,
1934
1971
  backendNodeId,
1935
1972
  sessionId,
1973
+ frameOffset,
1936
1974
  box,
1937
1975
  center: {
1938
1976
  x: Math.round(box.x + box.width / 2),
@@ -2115,23 +2153,189 @@ var PageController = class {
2115
2153
  });
2116
2154
  return res.result?.objectId;
2117
2155
  }
2156
+ /**
2157
+ * Verifies pre-click actionability (position stability, enabled state, and non-occlusion).
2158
+ * If a fixed/sticky header occludes the target, automatically re-centers it in viewport.
2159
+ */
2160
+ async ensureClickActionable(el, targetLabel) {
2161
+ let current = el;
2162
+ let underOwnPill = false;
2163
+ for (let attempt = 0; attempt < 6; attempt++) {
2164
+ await sleep(35);
2165
+ const nextBox = await this.readElementViewportBox(current);
2166
+ if (!nextBox)
2167
+ break;
2168
+ const moved = Math.abs(nextBox.x - current.box.x) > 2 || Math.abs(nextBox.y - current.box.y) > 2;
2169
+ current = {
2170
+ ...current,
2171
+ box: nextBox,
2172
+ center: { x: nextBox.x + nextBox.width / 2, y: nextBox.y + nextBox.height / 2 }
2173
+ };
2174
+ if (!moved)
2175
+ break;
2176
+ }
2177
+ if (current.sessionId)
2178
+ return { el: current, underOwnPill: false };
2179
+ for (let retry = 0; retry < 2; retry++) {
2180
+ const check = await this.session.send("Runtime.callFunctionOn", {
2181
+ objectId: current.objectId,
2182
+ arguments: [{ value: current.center.x }, { value: current.center.y }],
2183
+ functionDeclaration: `function(cx, cy) {
2184
+ if (this.disabled === true || this.getAttribute?.('aria-disabled') === 'true') {
2185
+ return { ok: false, reason: 'disabled' };
2186
+ }
2187
+ const style = getComputedStyle(this);
2188
+ if (style.pointerEvents === 'none') {
2189
+ return { ok: false, reason: 'pointer-events-none' };
2190
+ }
2191
+ function deepHit(root, x, y) {
2192
+ let hit = root.elementFromPoint(x, y);
2193
+ while (hit && hit.shadowRoot) {
2194
+ const inner = hit.shadowRoot.elementFromPoint(x, y);
2195
+ if (!inner || inner === hit) break;
2196
+ hit = inner;
2197
+ }
2198
+ return hit;
2199
+ }
2200
+ let hit = deepHit(document, cx, cy);
2201
+ let hitOwnPill = false;
2202
+ if (hit && hit.id === '__browserpilot_ui_host') {
2203
+ hitOwnPill = true;
2204
+ const prevDisplay = hit.style.display;
2205
+ hit.style.display = 'none';
2206
+ hit = deepHit(document, cx, cy);
2207
+ const uiHost = document.getElementById('__browserpilot_ui_host');
2208
+ if (uiHost) uiHost.style.display = prevDisplay;
2209
+ }
2210
+ if (!hit) return { ok: true, underOwnPill: hitOwnPill };
2211
+ if (hit === this || this.contains(hit) || hit.contains(this)) return { ok: true, underOwnPill: hitOwnPill };
2212
+ // Allow clicking associated <label> for form controls
2213
+ if (this.id && hit.closest && hit.closest('label[for="' + CSS.escape(this.id) + '"]')) return { ok: true, underOwnPill: hitOwnPill };
2214
+ // Walk up occluder to detect fixed/sticky header vs modal overlay
2215
+ let cur = hit;
2216
+ let isFixedOrSticky = false;
2217
+ while (cur && cur !== document.body && cur !== document.documentElement) {
2218
+ const pos = getComputedStyle(cur).position;
2219
+ if (pos === 'fixed' || pos === 'sticky') {
2220
+ isFixedOrSticky = true;
2221
+ break;
2222
+ }
2223
+ cur = cur.parentElement;
2224
+ }
2225
+ const tag = hit.tagName?.toLowerCase() || 'element';
2226
+ const cls = typeof hit.className === 'string' && hit.className.trim()
2227
+ ? '.' + hit.className.trim().split(/\\s+/).slice(0, 2).join('.')
2228
+ : '';
2229
+ const id = hit.id ? '#' + hit.id : '';
2230
+ const txt = (hit.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 40);
2231
+ return {
2232
+ ok: false,
2233
+ reason: 'occluded',
2234
+ occluder: '<' + tag + id + cls + '>' + (txt ? ' ("' + txt + '")' : ''),
2235
+ isFixedOrSticky,
2236
+ underOwnPill: hitOwnPill,
2237
+ };
2238
+ }`,
2239
+ returnByValue: true
2240
+ }).catch(() => null);
2241
+ const val = check?.result?.value;
2242
+ if (val?.underOwnPill)
2243
+ underOwnPill = true;
2244
+ if (!val || val.ok)
2245
+ return { el: current, underOwnPill };
2246
+ if (val.reason === "disabled") {
2247
+ throw new Error(`Element "${targetLabel}" is disabled and cannot be clicked.`);
2248
+ }
2249
+ if (val.reason === "pointer-events-none") {
2250
+ throw new Error(`Element "${targetLabel}" has pointer-events: none (pass force: true to override).`);
2251
+ }
2252
+ if (val.reason === "occluded" && val.isFixedOrSticky && retry === 0) {
2253
+ await this.session.send("Runtime.callFunctionOn", {
2254
+ objectId: current.objectId,
2255
+ functionDeclaration: `function() { this.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' }); }`
2256
+ }).catch(() => {
2257
+ });
2258
+ await sleep(60);
2259
+ const recentered = await this.readElementViewportBox(current);
2260
+ if (recentered) {
2261
+ current = {
2262
+ ...current,
2263
+ box: recentered,
2264
+ center: { x: recentered.x + recentered.width / 2, y: recentered.y + recentered.height / 2 }
2265
+ };
2266
+ continue;
2267
+ }
2268
+ }
2269
+ if (val.reason === "occluded") {
2270
+ throw new Error(`Element "${targetLabel}" is occluded at (${Math.round(current.center.x)}, ${Math.round(current.center.y)}) by ${val.occluder ?? "another element"}. Dismiss the overlay/banner first or pass force: true.`);
2271
+ }
2272
+ }
2273
+ return { el: current, underOwnPill };
2274
+ }
2275
+ async readElementViewportBox(el) {
2276
+ try {
2277
+ const res = await this.session.send("Runtime.callFunctionOn", {
2278
+ objectId: el.objectId,
2279
+ functionDeclaration: `function() {
2280
+ const r = this.getBoundingClientRect();
2281
+ return { x: r.left, y: r.top, width: r.width, height: r.height };
2282
+ }`,
2283
+ returnByValue: true
2284
+ }, { sessionId: el.sessionId });
2285
+ const b = res.result?.value;
2286
+ if (!b || b.width <= 0 || b.height <= 0)
2287
+ return null;
2288
+ if (el.frameOffset) {
2289
+ return {
2290
+ x: b.x + el.frameOffset.x,
2291
+ y: b.y + el.frameOffset.y,
2292
+ width: b.width,
2293
+ height: b.height
2294
+ };
2295
+ }
2296
+ return b;
2297
+ } catch {
2298
+ return null;
2299
+ }
2300
+ }
2118
2301
  async click(targetOrCoords, options = {}) {
2119
2302
  const button = options.button ?? "left";
2120
2303
  const clickCount = options.clickCount ?? 1;
2121
2304
  const modifiers = modifierBitmask(options.modifiers);
2122
2305
  let x;
2123
2306
  let y;
2307
+ let underOwnPill = false;
2124
2308
  if (typeof targetOrCoords === "string") {
2125
- const el = await this.resolveElement(targetOrCoords, options.timeoutMs);
2309
+ let el = await this.resolveElement(targetOrCoords, options.timeoutMs);
2310
+ if (!options.force) {
2311
+ const checked = await this.ensureClickActionable(el, targetOrCoords);
2312
+ el = checked.el;
2313
+ underOwnPill = checked.underOwnPill;
2314
+ }
2126
2315
  x = el.center.x;
2127
2316
  y = el.center.y;
2317
+ await this.session.transport.setControlBanner?.(this.tabId, { active: true, status: `Clicking ${targetOrCoords}`, mode: "working" }).catch(() => {
2318
+ });
2128
2319
  await this.session.transport.highlightElement?.(this.tabId, el.box, `click ${targetOrCoords}`).catch(() => {
2129
2320
  });
2130
2321
  } else {
2131
2322
  x = targetOrCoords.x;
2132
2323
  y = targetOrCoords.y;
2324
+ await this.session.transport.setControlBanner?.(this.tabId, { active: true, status: `Clicking (${Math.round(x)}, ${Math.round(y)})`, mode: "working" }).catch(() => {
2325
+ });
2326
+ }
2327
+ if (underOwnPill) {
2328
+ await this.evaluate(`(() => { const h = document.getElementById('__browserpilot_ui_host'); if (h) h.style.display = 'none'; })()`).catch(() => {
2329
+ });
2330
+ }
2331
+ try {
2332
+ await this.mouseClick(x, y, { button, clickCount, modifiers });
2333
+ } finally {
2334
+ if (underOwnPill) {
2335
+ await this.evaluate(`(() => { const h = document.getElementById('__browserpilot_ui_host'); if (h) h.style.display = ''; })()`).catch(() => {
2336
+ });
2337
+ }
2133
2338
  }
2134
- await this.mouseClick(x, y, { button, clickCount, modifiers });
2135
2339
  }
2136
2340
  async dblclick(targetOrCoords) {
2137
2341
  await this.click(targetOrCoords, { clickCount: 2 });
@@ -2159,19 +2363,26 @@ var PageController = class {
2159
2363
  const startX = this.lastMousePos.x;
2160
2364
  const startY = this.lastMousePos.y;
2161
2365
  for (let i = 1; i <= steps; i++) {
2162
- const cx = startX + (x - startX) * i / steps;
2163
- const cy = startY + (y - startY) * i / steps;
2366
+ const t = i / steps;
2367
+ const eased = steps > 1 ? 1 - Math.pow(1 - t, 2) : 1;
2368
+ const cx = startX + (x - startX) * eased;
2369
+ const cy = startY + (y - startY) * eased;
2164
2370
  await this.session.send("Input.dispatchMouseEvent", {
2165
2371
  type: "mouseMoved",
2166
2372
  x: cx,
2167
2373
  y: cy
2168
2374
  });
2169
- if (steps > 1)
2170
- await sleep(12);
2375
+ if (steps > 1) {
2376
+ await this.session.transport.moveGhostCursor?.(this.tabId, cx, cy, false).catch(() => {
2377
+ });
2378
+ await sleep(8);
2379
+ }
2171
2380
  }
2172
2381
  this.lastMousePos = { x, y };
2173
- await this.session.transport.moveGhostCursor?.(this.tabId, x, y, false).catch(() => {
2174
- });
2382
+ if (steps === 1) {
2383
+ await this.session.transport.moveGhostCursor?.(this.tabId, x, y, false).catch(() => {
2384
+ });
2385
+ }
2175
2386
  }
2176
2387
  async mouseDown(x, y, opts = {}) {
2177
2388
  const button = opts.button ?? "left";
@@ -2206,7 +2417,8 @@ var PageController = class {
2206
2417
  async mouseClick(x, y, opts = {}) {
2207
2418
  const button = opts.button ?? "left";
2208
2419
  const clicks = opts.clickCount ?? 1;
2209
- await this.mouseMove(x, y);
2420
+ const dist = Math.hypot(x - this.lastMousePos.x, y - this.lastMousePos.y);
2421
+ await this.mouseMove(x, y, { steps: dist > 40 ? 4 : 1 });
2210
2422
  for (let c = 1; c <= clicks; c++) {
2211
2423
  await this.mouseDown(x, y, { button, clickCount: c, modifiers: opts.modifiers });
2212
2424
  await this.mouseUp(x, y, { button, clickCount: c, modifiers: opts.modifiers });
@@ -2243,14 +2455,87 @@ var PageController = class {
2243
2455
  dx = amount;
2244
2456
  else if (options.direction === "left")
2245
2457
  dx = -amount;
2458
+ await this.session.transport.setControlBanner?.(this.tabId, {
2459
+ active: true,
2460
+ status: `Scrolling ${options.direction ?? (dy >= 0 ? "down" : "up")}`,
2461
+ mode: "working"
2462
+ }).catch(() => {
2463
+ });
2464
+ const probeMainScrollContainer = async () => {
2465
+ return await this.evaluate(`(() => {
2466
+ const vw = window.innerWidth || 1280;
2467
+ const vh = window.innerHeight || 720;
2468
+ const docEl = document.scrollingElement || document.documentElement;
2469
+ const docMaxY = Math.max(0, (docEl?.scrollHeight || 0) - vh);
2470
+ if (docMaxY > 24) {
2471
+ return {
2472
+ x: Math.round(vw / 2),
2473
+ y: Math.round(vh / 2),
2474
+ scrollX: Math.round(window.scrollX || docEl.scrollLeft || 0),
2475
+ scrollY: Math.round(window.scrollY || docEl.scrollTop || 0),
2476
+ maxScrollY: Math.round(docMaxY),
2477
+ container: 'window',
2478
+ };
2479
+ }
2480
+ // SPA layout where an inner container (main/section/div) owns scroll
2481
+ let best = null;
2482
+ let bestArea = 0;
2483
+ for (const el of document.querySelectorAll('main, [role="main"], section, article, div')) {
2484
+ const st = getComputedStyle(el);
2485
+ if (!/(auto|scroll|overlay)/.test(st.overflowY)) continue;
2486
+ const maxY = el.scrollHeight - el.clientHeight;
2487
+ if (maxY <= 24) continue;
2488
+ const r = el.getBoundingClientRect();
2489
+ if (r.width < 160 || r.height < 160) continue;
2490
+ const visW = Math.max(0, Math.min(r.right, vw) - Math.max(r.left, 0));
2491
+ const visH = Math.max(0, Math.min(r.bottom, vh) - Math.max(r.top, 0));
2492
+ const area = visW * visH;
2493
+ if (area > bestArea) {
2494
+ bestArea = area;
2495
+ const id = el.id ? '#' + el.id : '';
2496
+ best = {
2497
+ x: Math.round(Math.max(r.left, 0) + visW / 2),
2498
+ y: Math.round(Math.max(r.top, 0) + visH / 2),
2499
+ scrollX: Math.round(el.scrollLeft),
2500
+ scrollY: Math.round(el.scrollTop),
2501
+ maxScrollY: Math.round(maxY),
2502
+ container: el.tagName.toLowerCase() + id,
2503
+ };
2504
+ }
2505
+ }
2506
+ return best || {
2507
+ x: Math.round(vw / 2),
2508
+ y: Math.round(vh / 2),
2509
+ scrollX: Math.round(window.scrollX || 0),
2510
+ scrollY: Math.round(window.scrollY || 0),
2511
+ maxScrollY: Math.round(docMaxY),
2512
+ container: 'window',
2513
+ };
2514
+ })()`);
2515
+ };
2516
+ const before = await probeMainScrollContainer();
2246
2517
  if (options.target) {
2247
2518
  const el = await this.resolveElement(options.target);
2248
- if (dx === 0 && dy === 0)
2249
- return;
2250
- await this.wheel(dx, dy, el.center);
2519
+ if (dx !== 0 || dy !== 0) {
2520
+ await this.wheel(dx, dy, el.center);
2521
+ await sleep(120);
2522
+ }
2251
2523
  } else {
2252
- await this.wheel(dx, dy, { x: 400, y: 300 });
2524
+ await this.wheel(dx, dy, { x: before.x, y: before.y });
2525
+ await sleep(120);
2253
2526
  }
2527
+ const after = await probeMainScrollContainer();
2528
+ const percentY = after.maxScrollY > 0 ? Math.min(100, Math.round(after.scrollY / after.maxScrollY * 100)) : 100;
2529
+ return {
2530
+ scrolled: after.scrollY !== before.scrollY || after.scrollX !== before.scrollX,
2531
+ scrollX: after.scrollX,
2532
+ scrollY: after.scrollY,
2533
+ maxScrollY: after.maxScrollY,
2534
+ percentY,
2535
+ atTop: after.scrollY <= 1,
2536
+ atBottom: after.maxScrollY <= 1 || after.scrollY >= after.maxScrollY - 2,
2537
+ container: after.container
2538
+ };
2254
2539
  }
2255
2540
  /**
2256
2541
  * Focuses element, clears existing value, and inserts text via trusted CDP Input.insertText.
@@ -2258,6 +2543,8 @@ var PageController = class {
2258
2543
  */
2259
2544
  async fill(target, value, options = {}) {
2260
2545
  const el = await this.resolveElement(target, options.timeoutMs);
2546
+ await this.session.transport.setControlBanner?.(this.tabId, { active: true, status: `Filling ${target}`, mode: "working" }).catch(() => {
2547
+ });
2261
2548
  await this.session.transport.highlightElement?.(this.tabId, el.box, `fill ${target}`).catch(() => {
2262
2549
  });
2263
2550
  await this.mouseClick(el.center.x, el.center.y);
@@ -2333,17 +2620,23 @@ var PageController = class {
2333
2620
  }
2334
2621
  const mask = modifierBitmask(mods);
2335
2622
  const def = resolveKeyDef(keyPart);
2336
- for (const m of mods)
2337
- await this.keyDown(m);
2623
+ const commands = resolveEditingCommands(def.key, mods);
2624
+ const hasAccel = mods.includes("Meta") || mods.includes("Control");
2625
+ const activeMods = [];
2626
+ for (const m of mods) {
2627
+ activeMods.push(m);
2628
+ await this.keyDown(m, modifierBitmask(activeMods));
2629
+ }
2338
2630
  await this.session.send("Input.dispatchKeyEvent", {
2339
- type: def.text ? "keyDown" : "rawKeyDown",
2631
+ type: def.text && !hasAccel ? "keyDown" : "rawKeyDown",
2340
2632
  key: def.key,
2341
2633
  code: def.code,
2342
2634
  windowsVirtualKeyCode: def.keyCode,
2343
2635
  nativeVirtualKeyCode: def.keyCode,
2344
- text: def.text,
2636
+ text: hasAccel ? void 0 : def.text,
2345
2637
  unmodifiedText: def.text,
2346
- modifiers: mask
2638
+ modifiers: mask,
2639
+ ...commands.length ? { commands } : {}
2347
2640
  });
2348
2641
  await this.session.send("Input.dispatchKeyEvent", {
2349
2642
  type: "keyUp",
@@ -2353,10 +2646,192 @@ var PageController = class {
2353
2646
  nativeVirtualKeyCode: def.keyCode,
2354
2647
  modifiers: mask
2355
2648
  });
2356
- for (const m of [...mods].reverse())
2357
- await this.keyUp(m);
2649
+ for (let i = mods.length - 1; i >= 0; i--) {
2650
+ activeMods.pop();
2651
+ await this.keyUp(mods[i], modifierBitmask(activeMods));
2652
+ }
2358
2653
  }
2359
- async keyDown(keyName) {
2654
+ /**
2655
+ * Fills multiple form fields (text, select, checkbox, radio) in a single structured call.
2656
+ */
2657
+ async fillForm(fields) {
2658
+ const filled = [];
2659
+ for (const field of fields) {
2660
+ const kind = field.type ?? "auto";
2661
+ let detectedType = kind;
2662
+ if (kind === "auto") {
2663
+ const el = await this.resolveElement(field.target);
2664
+ const meta = await this.session.send("Runtime.callFunctionOn", {
2665
+ objectId: el.objectId,
2666
+ functionDeclaration: `function() { return { tag: (this.tagName || '').toLowerCase(), inputType: (this.type || '').toLowerCase() }; }`,
2667
+ returnByValue: true
2668
+ }, { sessionId: el.sessionId }).catch(() => null);
2669
+ const tag = meta?.result?.value?.tag ?? "";
2670
+ const inputType = meta?.result?.value?.inputType ?? "";
2671
+ if (tag === "select")
2672
+ detectedType = "select";
2673
+ else if (inputType === "checkbox")
2674
+ detectedType = "checkbox";
2675
+ else if (inputType === "radio")
2676
+ detectedType = "radio";
2677
+ else
2678
+ detectedType = "text";
2679
+ }
2680
+ if (detectedType === "select") {
2681
+ const selected = await this.selectOption(field.target, String(field.value));
2682
+ filled.push({ target: field.target, type: "select", value: selected });
2683
+ } else if (detectedType === "checkbox") {
2684
+ const desired = field.value === true || String(field.value).toLowerCase() === "true";
2685
+ const el = await this.resolveElement(field.target);
2686
+ const current = await this.session.send("Runtime.callFunctionOn", {
2687
+ objectId: el.objectId,
2688
+ functionDeclaration: `function() { return Boolean(this.checked || this.getAttribute?.('aria-checked') === 'true'); }`,
2689
+ returnByValue: true
2690
+ }, { sessionId: el.sessionId }).catch(() => null);
2691
+ if (Boolean(current?.result?.value) !== desired) {
2692
+ await this.click(field.target);
2693
+ }
2694
+ filled.push({ target: field.target, type: "checkbox", value: desired });
2695
+ } else if (detectedType === "radio") {
2696
+ await this.click(field.target);
2697
+ filled.push({ target: field.target, type: "radio", value: field.value });
2698
+ } else {
2699
+ await this.fill(field.target, String(field.value));
2700
+ filled.push({ target: field.target, type: "text", value: String(field.value) });
2701
+ }
2702
+ }
2703
+ return { filled };
2704
+ }
2705
+ /**
2706
+ * Displays an interactive in-page Human Handoff card ("Your Turn") and pauses until
2707
+ * the user clicks "Done, Continue AI" or "Cancel" inside the browser tab.
2708
+ * Works identically in both Chrome Extension mode and Direct CDP mode.
2709
+ */
2710
+ async requestHumanHandoff(message, options = {}) {
2711
+ const timeoutMs = options.timeoutMs ?? 3e5;
2712
+ const start = Date.now();
2713
+ const bindingName = "__browserpilotHandoffDone";
2714
+ await this.session.ensureBaseDomains();
2715
+ await this.session.send("Runtime.addBinding", { name: bindingName }).catch(() => {
2716
+ });
2717
+ await this.session.transport.setControlBanner?.(this.tabId, { active: true, status: "Waiting for you...", mode: "handoff" }).catch(() => {
2718
+ });
2719
+ let resolveAction;
2720
+ const decisionPromise = new Promise((resolve) => {
2721
+ resolveAction = resolve;
2722
+ });
2723
+ const offBinding = this.session.on("Runtime.bindingCalled", (params) => {
2724
+ if (params.name !== bindingName)
2725
+ return;
2726
+ const payload = String(params.payload ?? "");
2727
+ resolveAction(payload === "cancel" ? "cancel" : "resume");
2728
+ });
2729
+ const injectCard = async () => {
2730
+ await this.evaluate(`(() => {
2731
+ const old = document.getElementById('__browserpilot_handoff_host');
2732
+ if (old) old.remove();
2733
+ const host = document.createElement('div');
2734
+ host.id = '__browserpilot_handoff_host';
2735
+ host.style.cssText = 'position:fixed;inset:0;pointer-events:none;z-index:2147483647;';
2736
+ const shadow = host.attachShadow({ mode: 'closed' });
2737
+ const style = document.createElement('style');
2738
+ style.textContent = \`
2739
+ .bp-edge {
2740
+ position: fixed; inset: 0; pointer-events: none;
2741
+ box-shadow: inset 0 0 0 3px rgba(245, 158, 11, 0.72), inset 0 0 26px rgba(245, 158, 11, 0.22);
2742
+ }
2743
+ .bp-card {
2744
+ position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%);
2745
+ pointer-events: auto;
2746
+ display: flex; align-items: center; gap: 14px; max-width: 560px;
2747
+ background: rgba(15, 23, 42, 0.94); color: #f8fafc;
2748
+ border: 1px solid rgba(251, 191, 36, 0.55);
2749
+ backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
2750
+ border-radius: 14px; padding: 12px 16px;
2751
+ box-shadow: 0 14px 36px rgba(2, 6, 23, 0.45);
2752
+ font: 500 13px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
2753
+ }
2754
+ .bp-dot {
2755
+ width: 10px; height: 10px; border-radius: 999px; flex: none;
2756
+ background: #fbbf24; box-shadow: 0 0 10px #f59e0b;
2757
+ }
2758
+ .bp-msg { flex: 1; color: #f1f5f9; }
2759
+ .bp-title { font-weight: 700; font-size: 12px; color: #fcd34d; margin-bottom: 2px; }
2760
+ .bp-actions { display: flex; gap: 8px; flex: none; }
2761
+ button {
2762
+ cursor: pointer; border-radius: 8px; border: 1px solid transparent;
2763
+ padding: 7px 12px; font: 600 12px/1 -apple-system, BlinkMacSystemFont, sans-serif;
2764
+ }
2765
+ .bp-resume { background: linear-gradient(135deg, #2dd4bf, #06b6d4); color: #042f2e; }
2766
+ .bp-resume:hover { filter: brightness(1.06); }
2767
+ .bp-cancel { background: rgba(148, 163, 184, 0.16); color: #cbd5e1; border-color: rgba(148, 163, 184, 0.3); }
2768
+ .bp-cancel:hover { background: rgba(148, 163, 184, 0.28); }
2769
+ \`;
2770
+ shadow.appendChild(style);
2771
+ const edge = document.createElement('div');
2772
+ edge.className = 'bp-edge';
2773
+ const card = document.createElement('div');
2774
+ card.className = 'bp-card';
2775
+ const dot = document.createElement('div');
2776
+ dot.className = 'bp-dot';
2777
+ const msgWrap = document.createElement('div');
2778
+ msgWrap.className = 'bp-msg';
2779
+ const title = document.createElement('div');
2780
+ title.className = 'bp-title';
2781
+ title.textContent = 'BrowserPilot \xB7 Your Turn';
2782
+ const body = document.createElement('div');
2783
+ body.textContent = ${JSON.stringify(message)};
2784
+ msgWrap.append(title, body);
2785
+ const actions = document.createElement('div');
2786
+ actions.className = 'bp-actions';
2787
+ const btnResume = document.createElement('button');
2788
+ btnResume.className = 'bp-resume';
2789
+ btnResume.textContent = 'Done, Continue AI';
2790
+ btnResume.onclick = () => { globalThis.${bindingName}?.('resume'); host.remove(); };
2791
+ const btnCancel = document.createElement('button');
2792
+ btnCancel.className = 'bp-cancel';
2793
+ btnCancel.textContent = 'Cancel';
2794
+ btnCancel.onclick = () => { globalThis.${bindingName}?.('cancel'); host.remove(); };
2795
+ actions.append(btnResume, btnCancel);
2796
+ card.append(dot, msgWrap, actions);
2797
+ shadow.append(edge, card);
2798
+ (document.documentElement || document.body).appendChild(host);
2799
+ })()`).catch(() => {
2800
+ });
2801
+ };
2802
+ await injectCard();
2803
+ const offLoad = this.session.on("Page.loadEventFired", () => {
2804
+ void injectCard();
2805
+ });
2806
+ let timer = null;
2807
+ try {
2808
+ const outcome = await Promise.race([
2809
+ decisionPromise,
2810
+ new Promise((resolve) => {
2811
+ timer = setTimeout(() => resolve("timeout"), timeoutMs);
2812
+ })
2813
+ ]);
2814
+ const meta = await this.getUrlAndTitle().catch(() => ({ url: "", title: "" }));
2815
+ return {
2816
+ resumed: outcome === "resume",
2817
+ cancelled: outcome === "cancel",
2818
+ timedOut: outcome === "timeout",
2819
+ elapsedMs: Date.now() - start,
2820
+ url: meta.url,
2821
+ title: meta.title
2822
+ };
2823
+ } finally {
2824
+ if (timer)
2825
+ clearTimeout(timer);
2826
+ offBinding();
2827
+ offLoad();
2828
+ await this.evaluate(`document.getElementById('__browserpilot_handoff_host')?.remove()`).catch(() => {
2829
+ });
2830
+ await this.session.transport.setControlBanner?.(this.tabId, { active: true, status: "Active", mode: "working" }).catch(() => {
2831
+ });
2832
+ }
2833
+ }
2834
+ async keyDown(keyName, modifiers = 0) {
2360
2835
  const def = resolveKeyDef(keyName);
2361
2836
  await this.session.send("Input.dispatchKeyEvent", {
2362
2837
  type: def.text ? "keyDown" : "rawKeyDown",
@@ -2364,17 +2839,19 @@ var PageController = class {
2364
2839
  code: def.code,
2365
2840
  windowsVirtualKeyCode: def.keyCode,
2366
2841
  nativeVirtualKeyCode: def.keyCode,
2367
- text: def.text
2842
+ text: def.text,
2843
+ modifiers
2368
2844
  });
2369
2845
  }
2370
- async keyUp(keyName) {
2846
+ async keyUp(keyName, modifiers = 0) {
2371
2847
  const def = resolveKeyDef(keyName);
2372
2848
  await this.session.send("Input.dispatchKeyEvent", {
2373
2849
  type: "keyUp",
2374
2850
  key: def.key,
2375
2851
  code: def.code,
2376
2852
  windowsVirtualKeyCode: def.keyCode,
2377
- nativeVirtualKeyCode: def.keyCode
2853
+ nativeVirtualKeyCode: def.keyCode,
2854
+ modifiers
2378
2855
  });
2379
2856
  }
2380
2857
  async selectOption(target, valueOrLabel) {
@@ -2426,46 +2903,122 @@ var PageController = class {
2426
2903
  if (format !== "png" && options.quality !== void 0) {
2427
2904
  params.quality = options.quality;
2428
2905
  }
2429
- if (options.clip) {
2430
- params.clip = { ...options.clip, scale: 1 };
2431
- } else if (options.fullPage) {
2432
- const metrics = await this.session.send("Page.getLayoutMetrics");
2433
- const size = metrics.cssContentSize ?? metrics.contentSize ?? { width: 1280, height: 720 };
2434
- params.clip = {
2435
- x: 0,
2436
- y: 0,
2437
- width: size.width,
2438
- height: Math.min(size.height, 16384),
2439
- scale: 1
2440
- };
2441
- params.captureBeyondViewport = true;
2442
- } else {
2906
+ let region;
2907
+ await this.session.transport.setOverlayVisible?.(this.tabId, false).catch(() => {
2908
+ });
2909
+ await this.evaluate(`(() => {
2910
+ const el = document.getElementById('__browserpilot_ui_host');
2911
+ if (el) el.style.visibility = 'hidden';
2912
+ })()`).catch(() => {
2913
+ });
2914
+ try {
2443
2915
  const metrics = await this.session.send("Page.getLayoutMetrics");
2444
- if (metrics.cssVisualViewport) {
2916
+ const vp = metrics.cssVisualViewport ?? { pageX: 0, pageY: 0, clientWidth: 1280, clientHeight: 720 };
2917
+ if (options.grid) {
2918
+ const step = options.gridStep ?? (options.zoom ? 50 : 200);
2919
+ const originX = options.zoom ? options.zoom.x : 0;
2920
+ const originY = options.zoom ? options.zoom.y : 0;
2921
+ const spanW = options.zoom ? options.zoom.width : vp.clientWidth;
2922
+ const spanH = options.zoom ? options.zoom.height : vp.clientHeight;
2923
+ await this.evaluate(`(() => {
2924
+ document.getElementById('__browserpilot_grid_overlay')?.remove();
2925
+ const host = document.createElement('div');
2926
+ host.id = '__browserpilot_grid_overlay';
2927
+ host.style.cssText = 'position:fixed;inset:0;pointer-events:none;z-index:2147483646;';
2928
+ const shadow = host.attachShadow({ mode: 'closed' });
2929
+ const step = ${step};
2930
+ const startX = Math.floor(${originX} / step) * step;
2931
+ const endX = ${originX + spanW};
2932
+ const startY = Math.floor(${originY} / step) * step;
2933
+ const endY = ${originY + spanH};
2934
+ for (let x = startX; x <= endX; x += step) {
2935
+ const line = document.createElement('div');
2936
+ line.style.cssText = 'position:fixed;top:0;bottom:0;left:' + x + 'px;width:1px;background:rgba(6,182,212,0.38);';
2937
+ shadow.appendChild(line);
2938
+ const lbl = document.createElement('div');
2939
+ lbl.textContent = String(x);
2940
+ lbl.style.cssText = 'position:fixed;top:' + (${originY} + 2) + 'px;left:' + (x + 3) + 'px;background:rgba(15,23,42,0.82);color:#67e8f9;font:700 10px/1 ui-monospace,monospace;padding:1px 3px;border-radius:3px;';
2941
+ shadow.appendChild(lbl);
2942
+ }
2943
+ for (let y = startY; y <= endY; y += step) {
2944
+ const line = document.createElement('div');
2945
+ line.style.cssText = 'position:fixed;left:0;right:0;top:' + y + 'px;height:1px;background:rgba(6,182,212,0.38);';
2946
+ shadow.appendChild(line);
2947
+ const lbl = document.createElement('div');
2948
+ lbl.textContent = String(y);
2949
+ lbl.style.cssText = 'position:fixed;left:' + (${originX} + 2) + 'px;top:' + (y + 3) + 'px;background:rgba(15,23,42,0.82);color:#67e8f9;font:700 10px/1 ui-monospace,monospace;padding:1px 3px;border-radius:3px;';
2950
+ shadow.appendChild(lbl);
2951
+ }
2952
+ (document.documentElement || document.body).appendChild(host);
2953
+ })()`).catch(() => {
2954
+ });
2955
+ }
2956
+ if (options.zoom) {
2957
+ const scale = Math.max(1, Math.min(4, options.zoom.scale ?? 2));
2445
2958
  params.clip = {
2446
- x: metrics.cssVisualViewport.pageX,
2447
- y: metrics.cssVisualViewport.pageY,
2448
- width: metrics.cssVisualViewport.clientWidth,
2449
- height: metrics.cssVisualViewport.clientHeight,
2959
+ x: vp.pageX + options.zoom.x,
2960
+ y: vp.pageY + options.zoom.y,
2961
+ width: options.zoom.width,
2962
+ height: options.zoom.height,
2963
+ scale
2964
+ };
2965
+ region = {
2966
+ x: options.zoom.x,
2967
+ y: options.zoom.y,
2968
+ width: options.zoom.width,
2969
+ height: options.zoom.height,
2970
+ scale
2971
+ };
2972
+ } else if (options.clip) {
2973
+ params.clip = { ...options.clip, scale: 1 };
2974
+ region = { ...options.clip, scale: 1 };
2975
+ } else if (options.fullPage) {
2976
+ const size = metrics.cssContentSize ?? metrics.contentSize ?? { width: 1280, height: 720 };
2977
+ params.clip = {
2978
+ x: 0,
2979
+ y: 0,
2980
+ width: size.width,
2981
+ height: Math.min(size.height, 16384),
2982
+ scale: 1
2983
+ };
2984
+ params.captureBeyondViewport = true;
2985
+ } else if (metrics.cssVisualViewport) {
2986
+ params.clip = {
2987
+ x: vp.pageX,
2988
+ y: vp.pageY,
2989
+ width: vp.clientWidth,
2990
+ height: vp.clientHeight,
2450
2991
  scale: 1
2451
2992
  };
2452
2993
  }
2994
+ const res = await this.session.send("Page.captureScreenshot", params);
2995
+ let base64 = res.data;
2996
+ const mimeType = format === "jpeg" ? "image/jpeg" : format === "webp" ? "image/webp" : "image/png";
2997
+ if (options.maxDimension && options.maxDimension > 0) {
2998
+ const resized = await this.resizeBase64InPage(base64, mimeType, options.maxDimension, options.quality);
2999
+ if (resized)
3000
+ base64 = resized;
3001
+ }
3002
+ if (options.path) {
3003
+ const absPath = path3.resolve(options.path);
3004
+ await fs2.mkdir(path3.dirname(absPath), { recursive: true });
3005
+ await fs2.writeFile(absPath, Buffer.from(base64, "base64"));
3006
+ return { base64, mimeType, path: absPath, ...region ? { region } : {} };
3007
+ }
3008
+ return { base64, mimeType, ...region ? { region } : {} };
3009
+ } finally {
3010
+ if (options.grid) {
3011
+ await this.evaluate(`document.getElementById('__browserpilot_grid_overlay')?.remove()`).catch(() => {
3012
+ });
3013
+ }
3014
+ await this.evaluate(`(() => {
3015
+ const el = document.getElementById('__browserpilot_ui_host');
3016
+ if (el) el.style.visibility = '';
3017
+ })()`).catch(() => {
3018
+ });
3019
+ await this.session.transport.setOverlayVisible?.(this.tabId, true).catch(() => {
3020
+ });
2453
3021
  }
2454
- const res = await this.session.send("Page.captureScreenshot", params);
2455
- let base64 = res.data;
2456
- const mimeType = format === "jpeg" ? "image/jpeg" : format === "webp" ? "image/webp" : "image/png";
2457
- if (options.maxDimension && options.maxDimension > 0) {
2458
- const resized = await this.resizeBase64InPage(base64, mimeType, options.maxDimension, options.quality);
2459
- if (resized)
2460
- base64 = resized;
2461
- }
2462
- if (options.path) {
2463
- const absPath = path3.resolve(options.path);
2464
- await fs2.mkdir(path3.dirname(absPath), { recursive: true });
2465
- await fs2.writeFile(absPath, Buffer.from(base64, "base64"));
2466
- return { base64, mimeType, path: absPath };
2467
- }
2468
- return { base64, mimeType };
2469
3022
  }
2470
3023
  async resizeBase64InPage(base64, mimeType, maxDimension, quality) {
2471
3024
  try {
@@ -5080,6 +5633,14 @@ var SessionManager = class {
5080
5633
  const t = await getTab(opts?.tab);
5081
5634
  return await t.page.screenshot(opts);
5082
5635
  },
5636
+ handoff: async (message, opts) => {
5637
+ const t = await getTab(opts?.tab);
5638
+ return await t.page.requestHumanHandoff(message, { timeoutMs: opts?.timeoutMs });
5639
+ },
5640
+ fillForm: async (fields, opts) => {
5641
+ const t = await getTab(opts?.tab);
5642
+ return await t.page.fillForm(fields);
5643
+ },
5083
5644
  screenshotWithLabels: async (opts) => {
5084
5645
  const t = await getTab(opts?.tab);
5085
5646
  return await t.captureLabeledScreenshot(opts);
@@ -5301,7 +5862,7 @@ var TOOL_DEFINITIONS = [
5301
5862
  },
5302
5863
  {
5303
5864
  name: "browser_screenshot",
5304
- description: "Capture a CSS-scaled screenshot (viewport, fullPage, or clip region) returned directly as an image.",
5865
+ description: "Capture a clean CSS-scaled screenshot (viewport, fullPage, clip, or 2x zoomed region) with optional coordinate grid overlay for Canvas/Figma/PDF targeting.",
5305
5866
  inputSchema: {
5306
5867
  type: "object",
5307
5868
  properties: {
@@ -5312,9 +5873,23 @@ var TOOL_DEFINITIONS = [
5312
5873
  quality: { type: "number" },
5313
5874
  maxDimension: { type: "number", description: "Downscale longest edge to save vision tokens (default 1440)" },
5314
5875
  path: { type: "string", description: "Optional local file path to save the screenshot" },
5876
+ grid: { type: "boolean", description: "Overlay a translucent pixel coordinate grid with axis labels (useful for Canvas/PDF)" },
5877
+ gridStep: { type: "number", description: "Grid spacing in CSS pixels (default 200, or 50 when zoomed)" },
5315
5878
  clip: {
5316
5879
  type: "object",
5317
5880
  properties: { x: { type: "number" }, y: { type: "number" }, width: { type: "number" }, height: { type: "number" } }
5881
+ },
5882
+ zoom: {
5883
+ type: "object",
5884
+ description: "Crop & upscale a viewport region (e.g. 2x zoom into tiny icons/charts)",
5885
+ properties: {
5886
+ x: { type: "number" },
5887
+ y: { type: "number" },
5888
+ width: { type: "number" },
5889
+ height: { type: "number" },
5890
+ scale: { type: "number" }
5891
+ },
5892
+ required: ["x", "y", "width", "height"]
5318
5893
  }
5319
5894
  }
5320
5895
  }
@@ -5377,16 +5952,17 @@ var TOOL_DEFINITIONS = [
5377
5952
  },
5378
5953
  {
5379
5954
  name: "browser_click",
5380
- description: "Perform a browser-trusted CDP mouse click on a snapshot ref, CSS selector, text=..., or (x,y) coordinates.",
5955
+ description: "Perform a browser-trusted CDP mouse click on a snapshot ref, CSS selector, rich locator, or (x,y) coordinates. Checks pre-click stability & occlusion automatically unless force=true.",
5381
5956
  inputSchema: {
5382
5957
  type: "object",
5383
5958
  properties: {
5384
- target: { type: "string", description: "Ref (e5), CSS selector, or text=..." },
5959
+ target: { type: "string", description: "Ref (e5), CSS selector, role=..., label=..., or text=..." },
5385
5960
  x: { type: "number" },
5386
5961
  y: { type: "number" },
5387
5962
  button: { type: "string", enum: ["left", "right", "middle"] },
5388
5963
  clickCount: { type: "number" },
5389
5964
  modifiers: { type: "array", items: { type: "string", enum: ["Alt", "Control", "Meta", "Shift"] } },
5965
+ force: { type: "boolean", description: "Bypass pre-click occlusion & stability checks" },
5390
5966
  tabId: { type: "number" },
5391
5967
  sessionId: { type: "string" }
5392
5968
  }
@@ -5896,6 +6472,44 @@ var TOOL_DEFINITIONS = [
5896
6472
  sessionId: { type: "string" }
5897
6473
  }
5898
6474
  }
6475
+ },
6476
+ {
6477
+ name: "browser_fill_form",
6478
+ description: "Fill multiple form fields (text inputs, textareas, selects, checkboxes, radios) in a single round-trip with automatic field-type detection.",
6479
+ inputSchema: {
6480
+ type: "object",
6481
+ properties: {
6482
+ fields: {
6483
+ type: "array",
6484
+ items: {
6485
+ type: "object",
6486
+ properties: {
6487
+ target: { type: "string", description: "Ref (e4), CSS selector, label=..., or placeholder=..." },
6488
+ value: { description: "Text value, select option, or boolean for checkboxes" },
6489
+ type: { type: "string", enum: ["auto", "text", "select", "checkbox", "radio"] }
6490
+ },
6491
+ required: ["target", "value"]
6492
+ }
6493
+ },
6494
+ tabId: { type: "number" },
6495
+ sessionId: { type: "string" }
6496
+ },
6497
+ required: ["fields"]
6498
+ }
6499
+ },
6500
+ {
6501
+ name: "browser_handoff",
6502
+ description: 'Display an interactive in-page Human Handoff card ("BrowserPilot \xB7 Your Turn") asking the user to perform a manual step (login, 2FA, CAPTCHA, review) and wait until they click "Done, Continue AI" or "Cancel".',
6503
+ inputSchema: {
6504
+ type: "object",
6505
+ properties: {
6506
+ message: { type: "string", description: "Clear instruction shown to the user inside Chrome" },
6507
+ timeoutMs: { type: "number", description: "Max wait time in ms (default 300000 = 5 min)" },
6508
+ tabId: { type: "number" },
6509
+ sessionId: { type: "string" }
6510
+ },
6511
+ required: ["message"]
6512
+ }
5899
6513
  }
5900
6514
  ];
5901
6515
  async function executeTool(ctx, name, args = {}) {
@@ -5993,14 +6607,21 @@ ${formatFeedbackSuffix(feedback)}`);
5993
6607
  quality: args.quality,
5994
6608
  maxDimension: args.maxDimension ?? 1440,
5995
6609
  path: args.path,
5996
- clip: args.clip
6610
+ grid: args.grid,
6611
+ gridStep: args.gridStep,
6612
+ clip: args.clip,
6613
+ zoom: args.zoom
5997
6614
  });
6615
+ const regionNote = shot.region ? ` [region: x=${shot.region.x}, y=${shot.region.y}, ${shot.region.width}x${shot.region.height}, scale=${shot.region.scale}x]` : "";
5998
6616
  return {
5999
6617
  content: [
6000
- { type: "text", text: shot.path ? `Screenshot saved to ${shot.path}` : `Captured screenshot of tab [${tab.tabId}]` },
6618
+ {
6619
+ type: "text",
6620
+ text: `${shot.path ? `Screenshot saved to ${shot.path}` : `Captured screenshot of tab [${tab.tabId}]`}${regionNote}`
6621
+ },
6001
6622
  { type: "image", data: shot.base64, mimeType: shot.mimeType }
6002
6623
  ],
6003
- meta: { path: shot.path, tabId: tab.tabId }
6624
+ meta: { path: shot.path, tabId: tab.tabId, region: shot.region }
6004
6625
  };
6005
6626
  }
6006
6627
  case "browser_labeled_screenshot": {
@@ -6056,7 +6677,8 @@ ${som.snapshot.text}` },
6056
6677
  () => tab.page.click(target, {
6057
6678
  button: args.button,
6058
6679
  clickCount: args.clickCount,
6059
- modifiers: args.modifiers
6680
+ modifiers: args.modifiers,
6681
+ force: Boolean(args.force)
6060
6682
  })
6061
6683
  );
6062
6684
  return textResult(`Clicked ${typeof target === "string" ? target : `(${target.x}, ${target.y})`}
@@ -6095,14 +6717,17 @@ ${formatFeedbackSuffix(feedback)}`);
6095
6717
  }
6096
6718
  case "browser_scroll": {
6097
6719
  const tab = await resolveTab();
6098
- await tab.page.scroll({
6720
+ const res = await tab.page.scroll({
6099
6721
  target: args.target,
6100
6722
  direction: args.direction,
6101
6723
  amount: args.amount,
6102
6724
  deltaX: args.deltaX,
6103
6725
  deltaY: args.deltaY
6104
6726
  });
6105
- return textResult("Scrolled successfully");
6727
+ return textResult(
6728
+ `Scrolled ${res.container} (moved=${res.scrolled}): scrollY=${res.scrollY}/${res.maxScrollY}px (${res.percentY}%)${res.atTop ? " [at top]" : ""}${res.atBottom ? " [at bottom]" : ""}`,
6729
+ { ...res }
6730
+ );
6106
6731
  }
6107
6732
  case "browser_drag": {
6108
6733
  const tab = await resolveTab();
@@ -6608,6 +7233,30 @@ React: ${JSON.stringify(reactInfo, null, 2)}` : ""
6608
7233
  ].filter(Boolean).join("\n")
6609
7234
  );
6610
7235
  }
7236
+ case "browser_fill_form": {
7237
+ const tab = await resolveTab();
7238
+ const fields = args.fields ?? [];
7239
+ if (!fields.length) throw new Error("Provide non-empty fields array");
7240
+ const { result, feedback } = await tab.runWithFeedback(() => tab.page.fillForm(fields));
7241
+ const summary = result.filled.map((f, i) => `${i + 1}. [${f.type}] ${f.target} = ${JSON.stringify(f.value)}`).join("\n");
7242
+ return textResult(`Filled ${result.filled.length} form field(s):
7243
+ ${summary}
7244
+ ${formatFeedbackSuffix(feedback)}`, {
7245
+ filled: result.filled
7246
+ });
7247
+ }
7248
+ case "browser_handoff": {
7249
+ const tab = await resolveTab();
7250
+ const msg = String(args.message ?? 'Please complete the manual step in Chrome, then click "Done, Continue AI".');
7251
+ const res = await tab.page.requestHumanHandoff(msg, {
7252
+ timeoutMs: typeof args.timeoutMs === "number" ? args.timeoutMs : void 0
7253
+ });
7254
+ const status = res.resumed ? "Resumed by user" : res.cancelled ? "Cancelled by user" : "Timed out";
7255
+ return textResult(
7256
+ `${status} after ${Math.round(res.elapsedMs / 1e3)}s \u2014 URL: ${res.url}${res.title ? ` ("${res.title}")` : ""}`,
7257
+ { ...res }
7258
+ );
7259
+ }
6611
7260
  default:
6612
7261
  return { content: [{ type: "text", text: `Unknown tool: ${name}` }], isError: true };
6613
7262
  }
@@ -6649,7 +7298,7 @@ var BrowserPilotDaemon = class {
6649
7298
  const headerToken = (req.headers.authorization || "").replace(/^Bearer\s+/i, "");
6650
7299
  const provided = queryToken || headerToken;
6651
7300
  if (cfg.token && provided !== cfg.token) {
6652
- socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
7301
+ socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
6653
7302
  socket.destroy();
6654
7303
  return;
6655
7304
  }
@@ -7225,7 +7874,7 @@ BrowserPilot controls the user's running Chrome browser (existing logins, cookie
7225
7874
  - First call returns full AXTree with \`e1\`, \`e2\`... refs + viewport/scroll info; subsequent calls return diffs (pass \`--full\` / \`showDiffSinceLastCall: false\` for full output).
7226
7875
  - Use \`browser_labeled_screenshot\` / \`browserpilot labeled-screenshot <path>\` when spatial layout or icon-only buttons matter.
7227
7876
  3. **Act (trusted CDP input)**:
7228
- - \`click\`, \`fill\`, \`type\`, \`press_key\`, \`hover\`, \`scroll\`, \`drag\`, \`select_option\`, \`upload_file\`, \`batch\`.
7877
+ - \`click\` (checks occlusion & stability; pass \`force: true\` to override), \`fill\`, \`fill_form\`, \`type\`, \`press_key\` (supports macOS/Chrome \`Cmd+a/c/v/z\` editing commands), \`hover\`, \`scroll\` (smart inner SPA container detection + position telemetry), \`drag\`, \`select_option\`, \`upload_file\`, \`batch\`, \`handoff\` (in-page "Your Turn" card until user clicks Continue).
7229
7878
  - Targets accept refs (\`e5\`), CSS selectors (\`#submit\`), \`role=button[name="Save"]\`, \`label=...\`, \`placeholder=...\`, \`text=...\`, \`>> nth=N\`, or \`pinned\`.
7230
7879
  4. **DevTools Debugging**:
7231
7880
  - \`browser_console\` / \`browserpilot console --level error --since-last\`
@@ -7399,12 +8048,14 @@ Direct Quick Commands:
7399
8048
  browserpilot snapshot [--tab <id>] [--search <regex>] [--scope <css>] [--full]
7400
8049
  browserpilot markdown [--search <regex>] [--full] [--tab <id>]
7401
8050
  browserpilot html [--selector <css>] [--search <regex>] [--full] [--tab <id>]
7402
- browserpilot click <ref|selector> [--tab <id>]
8051
+ browserpilot click <ref|selector> [--force] [--tab <id>]
7403
8052
  browserpilot fill <ref|selector> <value> [--tab <id>]
8053
+ browserpilot fill-form '<json-fields>' [--tab <id>]
7404
8054
  browserpilot hover <ref|selector> [--tab <id>]
7405
8055
  browserpilot scroll [down|up|left|right] [--amount <px>] [--target <ref|sel>] [--tab <id>]
7406
8056
  browserpilot wait [--selector <css>] [--text <str>] [--ms <N>] [--timeout <ms>] [--tab <id>]
7407
- browserpilot screenshot [outputPath] [--full-page] [--tab <id>]
8057
+ browserpilot handoff "<message>" [--timeout <ms>] [--tab <id>]
8058
+ browserpilot screenshot [outputPath] [--full-page] [--grid] [--zoom x,y,w,h] [--clip x,y,w,h] [--tab <id>]
7408
8059
  browserpilot labeled-screenshot [outputPath] [--tab <id>]
7409
8060
  browserpilot console [--level error] [--search <str>] [--since-last] [--tab <id>]
7410
8061
  browserpilot network [--failed] [--search <str>] [--request-id <id>] [--tab <id>]
@@ -7703,8 +8354,17 @@ BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
7703
8354
  return;
7704
8355
  }
7705
8356
  const client = await DaemonClient.connectOrStart();
8357
+ const clientId = typeof flags.client === "string" ? flags.client : void 0;
7706
8358
  const tabId = typeof flags.tab === "string" ? Number(flags.tab) : void 0;
7707
8359
  const sessionId = typeof flags.s === "string" ? flags.s : typeof flags.session === "string" ? flags.session : void 0;
8360
+ const parseRect = (raw) => {
8361
+ if (typeof raw !== "string") return void 0;
8362
+ const nums = raw.split(",").map((s) => Number(s.trim()));
8363
+ if (nums.length !== 4 || nums.some((n) => !Number.isFinite(n))) {
8364
+ throw new Error(`Expected x,y,width,height numeric tuple, got "${raw}"`);
8365
+ }
8366
+ return { x: nums[0], y: nums[1], width: nums[2], height: nums[3] };
8367
+ };
7708
8368
  if (cmd === "connect-cdp") {
7709
8369
  const endpoint = positional[1] || "http://127.0.0.1:9222";
7710
8370
  const info = await client.connectDirectCDP(endpoint);
@@ -7766,14 +8426,15 @@ BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
7766
8426
  printToolOutput(await client.callTool("browser_status"));
7767
8427
  return;
7768
8428
  case "tabs":
7769
- printToolOutput(await client.callTool("browser_tabs"));
8429
+ printToolOutput(await client.callTool("browser_tabs", { clientId }));
7770
8430
  return;
7771
8431
  case "open":
7772
8432
  printToolOutput(
7773
8433
  await client.callTool("browser_open_tab", {
7774
8434
  url: positional[1] || "about:blank",
7775
8435
  tabGroup: typeof flags["tab-group"] === "string" ? flags["tab-group"] : void 0,
7776
- sessionId
8436
+ sessionId,
8437
+ clientId
7777
8438
  })
7778
8439
  );
7779
8440
  return;
@@ -7834,7 +8495,33 @@ BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
7834
8495
  );
7835
8496
  return;
7836
8497
  case "click":
7837
- printToolOutput(await client.callTool("browser_click", { target: positional[1], tabId, sessionId }));
8498
+ printToolOutput(
8499
+ await client.callTool("browser_click", {
8500
+ target: positional[1],
8501
+ force: Boolean(flags.force),
8502
+ tabId,
8503
+ sessionId,
8504
+ clientId
8505
+ })
8506
+ );
8507
+ return;
8508
+ case "fill-form": {
8509
+ const rawFields = positional[1];
8510
+ if (!rawFields) throw new Error(`Provide JSON array of fields: browserpilot fill-form '[{"target":"#name","value":"Alice"}]'`);
8511
+ const fields = JSON.parse(rawFields);
8512
+ printToolOutput(await client.callTool("browser_fill_form", { fields, tabId, sessionId, clientId }));
8513
+ return;
8514
+ }
8515
+ case "handoff":
8516
+ printToolOutput(
8517
+ await client.callTool("browser_handoff", {
8518
+ message: positional[1] || 'Please complete this step in Chrome, then click "Done, Continue AI".',
8519
+ timeoutMs: typeof flags.timeout === "string" ? Number(flags.timeout) : void 0,
8520
+ tabId,
8521
+ sessionId,
8522
+ clientId
8523
+ })
8524
+ );
7838
8525
  return;
7839
8526
  case "hover":
7840
8527
  printToolOutput(await client.callTool("browser_hover", { target: positional[1], tabId, sessionId }));
@@ -7874,16 +8561,24 @@ BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
7874
8561
  case "key":
7875
8562
  printToolOutput(await client.callTool("browser_press_key", { key: positional[1], tabId, sessionId }));
7876
8563
  return;
7877
- case "screenshot":
8564
+ case "screenshot": {
8565
+ const zoomRect = parseRect(flags.zoom);
8566
+ const clipRect = parseRect(flags.clip);
7878
8567
  printToolOutput(
7879
8568
  await client.callTool("browser_screenshot", {
7880
8569
  path: positional[1] || `browserpilot-shot-${Date.now()}.png`,
7881
8570
  fullPage: Boolean(flags["full-page"]),
8571
+ grid: Boolean(flags.grid),
8572
+ gridStep: typeof flags["grid-step"] === "string" ? Number(flags["grid-step"]) : void 0,
8573
+ clip: clipRect,
8574
+ zoom: zoomRect ? { ...zoomRect, scale: typeof flags.scale === "string" ? Number(flags.scale) : 2 } : void 0,
7882
8575
  tabId,
7883
- sessionId
8576
+ sessionId,
8577
+ clientId
7884
8578
  })
7885
8579
  );
7886
8580
  return;
8581
+ }
7887
8582
  case "labeled-screenshot":
7888
8583
  printToolOutput(
7889
8584
  await client.callTool("browser_labeled_screenshot", {