leapfrog-mcp 0.6.8 → 0.7.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/index.js CHANGED
@@ -62,6 +62,47 @@ const LEAP_HUD = process.env.LEAP_HUD === "true";
62
62
  const LEAP_AUTO_CONSENT = process.env.LEAP_AUTO_CONSENT !== "false"; // default ON
63
63
  const LEAP_TRACE = process.env.LEAP_TRACE === "true";
64
64
  const LEAP_RECORD = process.env.LEAP_RECORD === "true";
65
+ const LEAP_AD_BLOCK = process.env.LEAP_AD_BLOCK !== "false"; // default ON
66
+ // ── Ad/Tracker Blocking ──────────────────────────────────────────────────
67
+ const AD_BLOCK_DOMAINS = new Set([
68
+ "doubleclick.net", "googlesyndication.com", "googleadservices.com",
69
+ "google-analytics.com", "googletagmanager.com", "googletagservices.com",
70
+ "adservice.google.com", "pagead2.googlesyndication.com",
71
+ "facebook.net", "connect.facebook.net", "fbcdn.net",
72
+ "amazon-adsystem.com", "ads-api.twitter.com",
73
+ "ads.yahoo.com", "analytics.yahoo.com",
74
+ "scorecardresearch.com", "quantserve.com", "outbrain.com",
75
+ "taboola.com", "criteo.com", "criteo.net",
76
+ "moatads.com", "adsrvr.org", "adnxs.com", "rubiconproject.com",
77
+ "pubmatic.com", "openx.net", "casalemedia.com",
78
+ "chartbeat.com", "hotjar.com", "mixpanel.com", "segment.io",
79
+ "newrelic.com", "nr-data.net", "optimizely.com",
80
+ "demdex.net", "omtrdc.net", "2o7.net",
81
+ "tealiumiq.com", "tags.tiqcdn.com",
82
+ ]);
83
+ function shouldBlockUrl(url) {
84
+ try {
85
+ const hostname = new URL(url).hostname;
86
+ for (const domain of AD_BLOCK_DOMAINS) {
87
+ if (hostname === domain || hostname.endsWith("." + domain))
88
+ return true;
89
+ }
90
+ }
91
+ catch { }
92
+ return false;
93
+ }
94
+ function attachAdBlocker(context) {
95
+ if (!LEAP_AD_BLOCK)
96
+ return;
97
+ context.route("**/*", (route) => {
98
+ if (shouldBlockUrl(route.request().url())) {
99
+ route.abort("blockedbyclient").catch(() => { });
100
+ }
101
+ else {
102
+ route.fallback().catch(() => { });
103
+ }
104
+ });
105
+ }
65
106
  const sessions = new SessionManager({
66
107
  maxSessions: MAX_SESSIONS,
67
108
  idleTimeoutMs: IDLE_TIMEOUT_MS,
@@ -88,6 +129,9 @@ if (LEAP_TILE && LEAP_TILE !== "false") {
88
129
  const defaultW = LEAP_SCREEN_WIDTH > 0 ? LEAP_SCREEN_WIDTH : detectedScreen?.width ?? 1920;
89
130
  const defaultH = LEAP_SCREEN_HEIGHT > 0 ? LEAP_SCREEN_HEIGHT : detectedScreen?.height ?? 1080;
90
131
  tilesCoord = new TilesCoordinator(defaultW, defaultH);
132
+ // Purge ALL slots not owned by this process — handles zombie PIDs
133
+ // from /mcp reconnects where old node process lingers alive.
134
+ tilesCoord.purgeOtherPids().catch(() => { });
91
135
  // File watcher only needed for multi-terminal mode (multiple Leapfrog instances).
92
136
  // In single-instance mode, the watcher causes spurious reflows that fight
93
137
  // with external monitor positioning. Only enable when explicitly requested.
@@ -325,6 +369,7 @@ server.registerTool("session_create", {
325
369
  }
326
370
  // Always inject intervention detection (lightweight MutationObserver)
327
371
  await session.context.addInitScript(getDetectionInitScript());
372
+ attachAdBlocker(session.context);
328
373
  // Start tracing if enabled
329
374
  if (LEAP_TRACE) {
330
375
  await session.context.tracing.start({ screenshots: true, snapshots: true });
@@ -382,6 +427,7 @@ server.registerTool("session_create_batch", {
382
427
  if (LEAP_AUTO_CONSENT)
383
428
  await session.context.addInitScript(getConsentDismissScript());
384
429
  await session.context.addInitScript(getDetectionInitScript());
430
+ attachAdBlocker(session.context);
385
431
  if (LEAP_TRACE)
386
432
  await session.context.tracing.start({ screenshots: true, snapshots: true });
387
433
  // Claim tile slot (without triggering reflow yet — watcher handles it)
@@ -418,7 +464,7 @@ server.registerTool("session_create_batch", {
418
464
  return;
419
465
  }
420
466
  await session.page.goto(spec.url, {
421
- waitUntil: spec.waitUntil || "load",
467
+ waitUntil: spec.waitUntil || "domcontentloaded",
422
468
  timeout: 30000,
423
469
  });
424
470
  results.push({ id: session.id, url: spec.url });
@@ -627,7 +673,7 @@ server.registerTool("navigate", {
627
673
  url: z.string().describe("Full URL including https://"),
628
674
  waitUntil: z
629
675
  .enum(["load", "domcontentloaded", "networkidle"])
630
- .default("load")
676
+ .default("domcontentloaded")
631
677
  .describe("Wait strategy. Use networkidle for SPAs."),
632
678
  autoRetry: z
633
679
  .boolean()
@@ -8,7 +8,7 @@ import { generateFingerprint } from "./humanize-fingerprint.js";
8
8
  import { isHumanizeEnabled } from "./humanize-utils.js";
9
9
  import { CdpConnector } from "./cdp-connector.js";
10
10
  import { installSSRFRouteGuard } from "./ssrf.js";
11
- import { tileManager } from "./tile-manager.js";
11
+ import { tileManager, TileManager } from "./tile-manager.js";
12
12
  import * as fs from "fs/promises";
13
13
  import * as path from "path";
14
14
  import * as os from "os";
@@ -565,13 +565,27 @@ export class SessionManager {
565
565
  // Record the screen assignment so reflowAll keeps it on this screen.
566
566
  if (isHeaded && !cdpConnected && detectedScreen) {
567
567
  tileManager.assignSessionScreen(id, detectedScreen);
568
+ // Lock viewport for sessions with explicitly-set viewport so reflow
569
+ // doesn't override it. Unlocked sessions get dynamic viewport sync.
570
+ if (opts?.viewport) {
571
+ tileManager.lockViewport(id);
572
+ }
573
+ const initialBounds = {
574
+ x: detectedScreen.x,
575
+ y: detectedScreen.y,
576
+ width: Math.min(1280, detectedScreen.width),
577
+ height: Math.min(720, detectedScreen.height),
578
+ };
568
579
  try {
569
- await tileManager.positionWindowWithBounds(page, id, {
570
- x: detectedScreen.x,
571
- y: detectedScreen.y,
572
- width: Math.min(1280, detectedScreen.width),
573
- height: Math.min(720, detectedScreen.height),
574
- });
580
+ await tileManager.positionWindowWithBounds(page, id, initialBounds);
581
+ // Dynamic viewport sync on initial placement
582
+ if (!opts?.viewport) {
583
+ const viewport = TileManager.calculateViewportFromBounds(initialBounds);
584
+ try {
585
+ await page.setViewportSize(viewport);
586
+ }
587
+ catch { }
588
+ }
575
589
  }
576
590
  catch (e) {
577
591
  logger.warn("tile.position_failed", { error: e.message });
@@ -30,6 +30,10 @@ declare class TileManager {
30
30
  private windowIds;
31
31
  /** Per-session screen assignment — windows stay on the screen where they were created. */
32
32
  private sessionScreens;
33
+ /** Sessions with explicitly-set viewports — reflow won't override these. */
34
+ private viewportLocked;
35
+ /** Chrome UI height (tabs, address bar, bookmarks). Subtracted from tile height to get content area. */
36
+ static CHROME_HEIGHT: number;
33
37
  configure(opts: {
34
38
  layout: TileLayout;
35
39
  padding: number;
@@ -79,6 +83,15 @@ declare class TileManager {
79
83
  globalIndex: number;
80
84
  }): string[];
81
85
  positionWindow(page: Page, sessionId: string): Promise<void>;
86
+ /** Calculate the page viewport that fits inside a window of the given bounds. */
87
+ static calculateViewportFromBounds(bounds: TileBounds): {
88
+ width: number;
89
+ height: number;
90
+ };
91
+ /** Lock a session's viewport so reflow won't override an explicitly-set viewport. */
92
+ lockViewport(sessionId: string): void;
93
+ /** Check if a session's viewport is locked. */
94
+ isViewportLocked(sessionId: string): boolean;
82
95
  /** Record which screen a session was placed on so reflows keep it there. */
83
96
  assignSessionScreen(sessionId: string, screen: ScreenWorkArea): void;
84
97
  /** Get the screen assigned to a session, or the current global screen. */
@@ -4,7 +4,7 @@
4
4
  // Opt-in via LEAP_TILE=true|grid|master env var.
5
5
  //
6
6
  // Key design:
7
- // - Viewport (screenshot resolution) stays at 1280x720 regardless of tile size
7
+ // - Viewport auto-syncs to tile size during reflow (dynamic viewport)
8
8
  // - Screen detection via page.evaluate() on first headed session, cached
9
9
  // - Accounts for macOS menu bar, Dock, and work area offset
10
10
  // - Launch-time positioning via --window-position/--window-size Chrome args
@@ -23,6 +23,10 @@ class TileManager {
23
23
  windowIds = new Map();
24
24
  /** Per-session screen assignment — windows stay on the screen where they were created. */
25
25
  sessionScreens = new Map();
26
+ /** Sessions with explicitly-set viewports — reflow won't override these. */
27
+ viewportLocked = new Set();
28
+ /** Chrome UI height (tabs, address bar, bookmarks). Subtracted from tile height to get content area. */
29
+ static CHROME_HEIGHT = process.platform === "darwin" ? 72 : 85;
26
30
  // ── Configuration ──────────────────────────────────────────────────
27
31
  configure(opts) {
28
32
  this.enabled = true;
@@ -317,6 +321,21 @@ if (found) { found; } else {
317
321
  // This is a low-level primitive; reflowAll calls it with correct bounds.
318
322
  logger.debug("tile.position_window", { sessionId });
319
323
  }
324
+ /** Calculate the page viewport that fits inside a window of the given bounds. */
325
+ static calculateViewportFromBounds(bounds) {
326
+ return {
327
+ width: Math.max(bounds.width, 400),
328
+ height: Math.max(bounds.height - TileManager.CHROME_HEIGHT, 200),
329
+ };
330
+ }
331
+ /** Lock a session's viewport so reflow won't override an explicitly-set viewport. */
332
+ lockViewport(sessionId) {
333
+ this.viewportLocked.add(sessionId);
334
+ }
335
+ /** Check if a session's viewport is locked. */
336
+ isViewportLocked(sessionId) {
337
+ return this.viewportLocked.has(sessionId);
338
+ }
320
339
  /** Record which screen a session was placed on so reflows keep it there. */
321
340
  assignSessionScreen(sessionId, screen) {
322
341
  this.sessionScreens.set(sessionId, screen);
@@ -386,6 +405,18 @@ if (found) { found; } else {
386
405
  if (!page || page.isClosed())
387
406
  return;
388
407
  await this.positionWindowWithBounds(page, id, bounds);
408
+ // Dynamic viewport sync — resize page viewport to match tile content area.
409
+ // Skip sessions where user explicitly set a viewport (viewport-locked).
410
+ if (!this.viewportLocked.has(id)) {
411
+ const viewport = TileManager.calculateViewportFromBounds(bounds);
412
+ try {
413
+ await page.setViewportSize(viewport);
414
+ logger.debug("tile.viewport_synced", { id, ...viewport });
415
+ }
416
+ catch {
417
+ // Viewport sync is non-fatal
418
+ }
419
+ }
389
420
  });
390
421
  }));
391
422
  // Bring all windows to front after positioning
@@ -416,6 +447,7 @@ if (found) { found; } else {
416
447
  removeSession(sessionId) {
417
448
  this.windowIds.delete(sessionId);
418
449
  this.sessionScreens.delete(sessionId);
450
+ this.viewportLocked.delete(sessionId);
419
451
  }
420
452
  }
421
453
  export const tileManager = new TileManager();
@@ -87,6 +87,12 @@ export declare class TilesCoordinator {
87
87
  * @returns Session IDs of the reaped (dead) slots.
88
88
  */
89
89
  reapDeadSlots(): Promise<string[]>;
90
+ /**
91
+ * Purge all slots NOT owned by the current process.pid.
92
+ * Called on startup to clear ghost slots from previous instances
93
+ * that may still be alive (e.g., after /mcp reconnect).
94
+ */
95
+ purgeOtherPids(): Promise<number>;
90
96
  /**
91
97
  * Watch `tiles.json` for changes made by other instances.
92
98
  * The callback fires with the new state whenever the file changes.
@@ -283,6 +283,23 @@ export class TilesCoordinator {
283
283
  return deadIds;
284
284
  });
285
285
  }
286
+ /**
287
+ * Purge all slots NOT owned by the current process.pid.
288
+ * Called on startup to clear ghost slots from previous instances
289
+ * that may still be alive (e.g., after /mcp reconnect).
290
+ */
291
+ async purgeOtherPids() {
292
+ return withLock(async () => {
293
+ const state = readState(this.screenWidth, this.screenHeight);
294
+ const before = state.slots.length;
295
+ state.slots = state.slots.filter((s) => s.instancePid === process.pid);
296
+ if (state.slots.length !== before) {
297
+ recalculatePositions(state);
298
+ writeState(state);
299
+ }
300
+ return before - state.slots.length;
301
+ });
302
+ }
286
303
  /**
287
304
  * Watch `tiles.json` for changes made by other instances.
288
305
  * The callback fires with the new state whenever the file changes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "leapfrog-mcp",
3
- "version": "0.6.8",
3
+ "version": "0.7.0",
4
4
  "description": "Multi-session browser MCP for AI agents — 36 tools, stealth, persistent auth, code-first scripts, API sniffer, agent intelligence",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",