browserpilot-cdp 1.2.0 → 1.2.2

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.0";
11
+ var BROWSERPILOT_VERSION = "1.2.2";
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";
@@ -32,6 +32,23 @@ var BLOCKED_PROFILE_WIDE_CDP_COMMANDS = /* @__PURE__ */ new Set([
32
32
  "Network.clearBrowserCookies",
33
33
  "Network.clearBrowserCache"
34
34
  ]);
35
+ var RESTRICTED_URL_PREFIXES = [
36
+ "chrome://",
37
+ "chrome-extension://",
38
+ "chrome-untrusted://",
39
+ "devtools://",
40
+ "edge://",
41
+ "brave://",
42
+ "about:blank#blocked",
43
+ "https://chrome.google.com/webstore",
44
+ "https://chromewebstore.google.com"
45
+ ];
46
+ function isRestrictedUrl(url) {
47
+ if (!url)
48
+ return false;
49
+ const lower = url.toLowerCase();
50
+ return RESTRICTED_URL_PREFIXES.some((prefix) => lower.startsWith(prefix));
51
+ }
35
52
  function isBlockedProfileWideCommand(method) {
36
53
  return BLOCKED_PROFILE_WIDE_CDP_COMMANDS.has(method);
37
54
  }
@@ -876,16 +893,19 @@ async function waitForPageLoad(session, options = {}) {
876
893
  await sleep(Math.min(minWaitMs, timeoutMs));
877
894
  }
878
895
  while (Date.now() - start < timeoutMs) {
896
+ let href = "";
879
897
  try {
880
898
  const res = await session.send("Runtime.evaluate", {
881
- expression: "document.readyState",
899
+ expression: "({ readyState: document.readyState, href: location.href })",
882
900
  returnByValue: true
883
901
  });
884
- readyState = res.result?.value ?? "loading";
902
+ readyState = res.result?.value?.readyState ?? "loading";
903
+ href = res.result?.value?.href ?? "";
885
904
  } catch {
886
905
  readyState = "loading";
887
906
  }
888
- if ((readyState === "complete" || readyState === "interactive") && inflight.size === 0) {
907
+ const stillOnBlank = Boolean(options.ignoreAboutBlank) && (!href || href === "about:blank");
908
+ if (!stillOnBlank && (readyState === "complete" || readyState === "interactive") && inflight.size === 0) {
889
909
  if (idleSince === null)
890
910
  idleSince = Date.now();
891
911
  if (Date.now() - idleSince >= idleMs || readyState === "complete") {
@@ -2534,6 +2554,7 @@ var ROLE_COLORS = {
2534
2554
  };
2535
2555
  async function captureLabeledScreenshot(page, options = {}) {
2536
2556
  const maxLabels = options.maxLabels ?? 120;
2557
+ await page.session.enableDomain("DOM");
2537
2558
  const snapshot = await page.snapshotEngine.capture(page.session, { showDiffSinceLastCall: false });
2538
2559
  const viewport = await page.evaluate("({ width: window.innerWidth, height: window.innerHeight })");
2539
2560
  const labels = [];
@@ -3063,9 +3084,12 @@ var StylesInspector = class {
3063
3084
  const extractDecls = (props) => {
3064
3085
  if (!props)
3065
3086
  return [];
3087
+ const hasAuthoredRanges = props.some((p) => Boolean(p.range || p.text));
3066
3088
  const out = [];
3067
3089
  for (const p of props) {
3068
- if (p.disabled || !p.name || p.name.startsWith("-webkit-") || !p.value)
3090
+ if (p.disabled || p.implicit || !p.name || p.name.startsWith("-webkit-") || !p.value)
3091
+ continue;
3092
+ if (hasAuthoredRanges && !p.range && !p.text)
3069
3093
  continue;
3070
3094
  const overridden = seenProps.has(p.name);
3071
3095
  seenProps.add(p.name);
@@ -4785,6 +4809,9 @@ var SessionManager = class {
4785
4809
  getTransport() {
4786
4810
  return this.transport;
4787
4811
  }
4812
+ getAttachedTabCount() {
4813
+ return this.tabs.size;
4814
+ }
4788
4815
  async getOrAttachTab(tabId, options) {
4789
4816
  await this.transport.attachTab(tabId, options);
4790
4817
  let tab = this.tabs.get(tabId);
@@ -4838,7 +4865,8 @@ var SessionManager = class {
4838
4865
  session.activeTabId = void 0;
4839
4866
  }
4840
4867
  const allTabs = await this.listTabs();
4841
- const candidate = allTabs.find((t) => t.active && !t.url.startsWith("chrome://")) ?? allTabs.find((t) => !t.url.startsWith("chrome://"));
4868
+ const attachable = allTabs.filter((t) => !isRestrictedUrl(t.url));
4869
+ const candidate = attachable.find((t) => t.active && /^https?:\/\//i.test(t.url)) ?? attachable.find((t) => t.active) ?? attachable.find((t) => /^https?:\/\//i.test(t.url)) ?? attachable[0];
4842
4870
  if (candidate) {
4843
4871
  const tab = await this.getOrAttachTab(candidate.tabId, groupOpts);
4844
4872
  if (session)
@@ -5081,6 +5109,16 @@ ${code}
5081
5109
  function textResult(text, meta) {
5082
5110
  return { content: [{ type: "text", text }], meta };
5083
5111
  }
5112
+ function normalizeNavigationUrl(raw) {
5113
+ const trimmed = (raw ?? "").trim();
5114
+ if (!trimmed) return "about:blank";
5115
+ if (/^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/|$)/i.test(trimmed)) {
5116
+ return `http://${trimmed}`;
5117
+ }
5118
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(trimmed)) return trimmed;
5119
+ if (/^(about|data|file|javascript|mailto|blob|view-source):/i.test(trimmed)) return trimmed;
5120
+ return `https://${trimmed}`;
5121
+ }
5084
5122
  function formatFeedbackSuffix(fb) {
5085
5123
  const parts = [`URL: ${fb.url}`];
5086
5124
  if (fb.newConsoleErrors.length > 0) {
@@ -5808,15 +5846,23 @@ async function executeTool(ctx, name, args = {}) {
5808
5846
  return textResult(formatted || "(no tabs open)", { tabs });
5809
5847
  }
5810
5848
  case "browser_open_tab": {
5849
+ const targetUrl = normalizeNavigationUrl(args.url);
5811
5850
  const tab = await manager.openTab({
5812
- url: args.url,
5851
+ url: targetUrl,
5813
5852
  active: args.active,
5814
5853
  tabGroup: args.tabGroup,
5815
5854
  tabGroupColor: args.tabGroupColor
5816
5855
  });
5817
5856
  if (sessionId) manager.getOrCreateSession(sessionId).activeTabId = tab.tabId;
5818
- const meta = await tab.page.getUrlAndTitle().catch(() => ({ url: String(args.url ?? "about:blank"), title: "" }));
5819
- return textResult(`Opened and attached tab [${tab.tabId}]: ${meta.url}`, { tabId: tab.tabId, ...meta });
5857
+ if (/^https?:\/\//i.test(targetUrl)) {
5858
+ await waitForPageLoad(tab.session, { timeoutMs: 1e4, idleMs: 250, ignoreAboutBlank: true }).catch(() => {
5859
+ });
5860
+ }
5861
+ const meta = await tab.page.getUrlAndTitle().catch(() => ({ url: targetUrl, title: "" }));
5862
+ return textResult(`Opened and attached tab [${tab.tabId}]: ${meta.url}${meta.title ? ` ("${meta.title}")` : ""}`, {
5863
+ tabId: tab.tabId,
5864
+ ...meta
5865
+ });
5820
5866
  }
5821
5867
  case "browser_close_tab": {
5822
5868
  await manager.closeTab(Number(args.tabId));
@@ -5839,8 +5885,9 @@ async function executeTool(ctx, name, args = {}) {
5839
5885
  }
5840
5886
  case "browser_navigate": {
5841
5887
  const tab = await resolveTab();
5888
+ const targetUrl = normalizeNavigationUrl(String(args.url));
5842
5889
  const { result, feedback } = await tab.runWithFeedback(
5843
- () => tab.page.navigate(String(args.url), {
5890
+ () => tab.page.navigate(targetUrl, {
5844
5891
  waitUntil: args.waitUntil ?? "domcontentloaded",
5845
5892
  timeoutMs: args.timeoutMs
5846
5893
  })
@@ -6604,6 +6651,15 @@ var BrowserPilotDaemon = class {
6604
6651
  };
6605
6652
  this.backends.set(clientId, { info, transport, manager });
6606
6653
  this.primaryClientId = clientId;
6654
+ if (ws.readyState === ws.OPEN) {
6655
+ ws.send(
6656
+ JSON.stringify({
6657
+ type: "event",
6658
+ event: "bridge.ready",
6659
+ params: { version: BROWSERPILOT_VERSION, clientId }
6660
+ })
6661
+ );
6662
+ }
6607
6663
  ws.on("close", () => {
6608
6664
  manager.dispose();
6609
6665
  this.backends.delete(clientId);
@@ -6646,7 +6702,10 @@ var BrowserPilotDaemon = class {
6646
6702
  return info;
6647
6703
  }
6648
6704
  listClients() {
6649
- return Array.from(this.backends.values()).map((b) => b.info);
6705
+ return Array.from(this.backends.values()).map((b) => ({
6706
+ ...b.info,
6707
+ attachedTabCount: b.manager.getAttachedTabCount()
6708
+ }));
6650
6709
  }
6651
6710
  getManager(clientId) {
6652
6711
  const targetId = clientId ?? this.primaryClientId;
@@ -6679,6 +6738,7 @@ var BrowserPilotDaemon = class {
6679
6738
  this.sendJson(res, 200, {
6680
6739
  ok: true,
6681
6740
  version: BROWSERPILOT_VERSION,
6741
+ pid: process.pid,
6682
6742
  uptimeMs: Date.now() - this.startedAt,
6683
6743
  clients: this.listClients()
6684
6744
  });
@@ -6811,14 +6871,27 @@ async function startMcpServer(options = {}) {
6811
6871
  };
6812
6872
  result = await executeTool(ctx, name, args);
6813
6873
  } else {
6814
- if (!daemonClient) {
6815
- daemonClient = await DaemonClient.connectOrStart({
6816
- host: options.daemonHost,
6817
- port: options.daemonPort,
6818
- token: options.daemonToken
6819
- });
6874
+ const ensureDaemon = async () => {
6875
+ if (!daemonClient) {
6876
+ daemonClient = await DaemonClient.connectOrStart({
6877
+ host: options.daemonHost,
6878
+ port: options.daemonPort,
6879
+ token: options.daemonToken
6880
+ });
6881
+ }
6882
+ return daemonClient;
6883
+ };
6884
+ try {
6885
+ result = await (await ensureDaemon()).callTool(name, args);
6886
+ } catch (err) {
6887
+ const msg = err instanceof Error ? err.message : String(err);
6888
+ if (/fetch failed|ECONNREFUSED|ECONNRESET|socket|Unauthorized/i.test(msg)) {
6889
+ daemonClient = null;
6890
+ result = await (await ensureDaemon()).callTool(name, args);
6891
+ } else {
6892
+ throw err;
6893
+ }
6820
6894
  }
6821
- result = await daemonClient.callTool(name, args);
6822
6895
  }
6823
6896
  return {
6824
6897
  isError: result.isError,
@@ -6835,6 +6908,7 @@ async function startMcpServer(options = {}) {
6835
6908
  }
6836
6909
 
6837
6910
  // src/native-install.ts
6911
+ import crypto3 from "node:crypto";
6838
6912
  import fs5 from "node:fs/promises";
6839
6913
  import os4 from "node:os";
6840
6914
  import path6 from "node:path";
@@ -6845,31 +6919,178 @@ function getNativeMessagingHostDirs(platform = process.platform) {
6845
6919
  if (platform === "darwin") {
6846
6920
  const appSupport = path6.join(home, "Library", "Application Support");
6847
6921
  return [
6848
- { name: "Google Chrome", dir: path6.join(appSupport, "Google", "Chrome", "NativeMessagingHosts") },
6849
- { name: "Google Chrome Canary", dir: path6.join(appSupport, "Google", "Chrome Canary", "NativeMessagingHosts") },
6850
- { name: "Google Chrome for Testing", dir: path6.join(appSupport, "Google", "Chrome for Testing", "NativeMessagingHosts") },
6851
- { name: "Chromium", dir: path6.join(appSupport, "Chromium", "NativeMessagingHosts") },
6852
- { name: "Brave", dir: path6.join(appSupport, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts") },
6853
- { name: "Microsoft Edge", dir: path6.join(appSupport, "Microsoft Edge", "NativeMessagingHosts") },
6854
- { name: "Arc", dir: path6.join(appSupport, "Arc", "User Data", "NativeMessagingHosts") }
6922
+ {
6923
+ name: "Google Chrome",
6924
+ userDataDir: path6.join(appSupport, "Google", "Chrome"),
6925
+ dir: path6.join(appSupport, "Google", "Chrome", "NativeMessagingHosts")
6926
+ },
6927
+ {
6928
+ name: "Google Chrome Canary",
6929
+ userDataDir: path6.join(appSupport, "Google", "Chrome Canary"),
6930
+ dir: path6.join(appSupport, "Google", "Chrome Canary", "NativeMessagingHosts")
6931
+ },
6932
+ {
6933
+ name: "Google Chrome for Testing",
6934
+ userDataDir: path6.join(appSupport, "Google", "Chrome for Testing"),
6935
+ dir: path6.join(appSupport, "Google", "Chrome for Testing", "NativeMessagingHosts")
6936
+ },
6937
+ {
6938
+ name: "Chromium",
6939
+ userDataDir: path6.join(appSupport, "Chromium"),
6940
+ dir: path6.join(appSupport, "Chromium", "NativeMessagingHosts")
6941
+ },
6942
+ {
6943
+ name: "Brave",
6944
+ userDataDir: path6.join(appSupport, "BraveSoftware", "Brave-Browser"),
6945
+ dir: path6.join(appSupport, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts")
6946
+ },
6947
+ {
6948
+ name: "Microsoft Edge",
6949
+ userDataDir: path6.join(appSupport, "Microsoft Edge"),
6950
+ dir: path6.join(appSupport, "Microsoft Edge", "NativeMessagingHosts")
6951
+ },
6952
+ {
6953
+ name: "Arc",
6954
+ userDataDir: path6.join(appSupport, "Arc", "User Data"),
6955
+ dir: path6.join(appSupport, "Arc", "User Data", "NativeMessagingHosts")
6956
+ }
6855
6957
  ];
6856
6958
  }
6857
6959
  if (platform === "linux") {
6858
6960
  const config = path6.join(home, ".config");
6859
6961
  return [
6860
- { name: "Google Chrome", dir: path6.join(config, "google-chrome", "NativeMessagingHosts") },
6861
- { name: "Chromium", dir: path6.join(config, "chromium", "NativeMessagingHosts") },
6862
- { name: "Brave", dir: path6.join(config, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts") },
6863
- { name: "Microsoft Edge", dir: path6.join(config, "microsoft-edge", "NativeMessagingHosts") }
6962
+ {
6963
+ name: "Google Chrome",
6964
+ userDataDir: path6.join(config, "google-chrome"),
6965
+ dir: path6.join(config, "google-chrome", "NativeMessagingHosts")
6966
+ },
6967
+ {
6968
+ name: "Chromium",
6969
+ userDataDir: path6.join(config, "chromium"),
6970
+ dir: path6.join(config, "chromium", "NativeMessagingHosts")
6971
+ },
6972
+ {
6973
+ name: "Brave",
6974
+ userDataDir: path6.join(config, "BraveSoftware", "Brave-Browser"),
6975
+ dir: path6.join(config, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts")
6976
+ },
6977
+ {
6978
+ name: "Microsoft Edge",
6979
+ userDataDir: path6.join(config, "microsoft-edge"),
6980
+ dir: path6.join(config, "microsoft-edge", "NativeMessagingHosts")
6981
+ }
6864
6982
  ];
6865
6983
  }
6866
6984
  return [];
6867
6985
  }
6986
+ function computeChromeExtensionId(unpackedDir) {
6987
+ const normalized = path6.resolve(unpackedDir);
6988
+ const hash = crypto3.createHash("sha256").update(normalized, "utf8").digest("hex").slice(0, 32);
6989
+ return hash.replace(/[0-9a-f]/g, (ch) => String.fromCharCode(97 + Number.parseInt(ch, 16)));
6990
+ }
6991
+ function getStableExtensionDir() {
6992
+ return path6.join(getBrowserPilotHomeDir(), "extension");
6993
+ }
6994
+ async function syncExtensionToHome(sourceExtDir, options = {}) {
6995
+ const destDir = getStableExtensionDir();
6996
+ let version = null;
6997
+ try {
6998
+ const manifestRaw = await fs5.readFile(path6.join(sourceExtDir, "manifest.json"), "utf8");
6999
+ const manifest = JSON.parse(manifestRaw);
7000
+ version = manifest.version ?? null;
7001
+ } catch {
7002
+ }
7003
+ let synced = false;
7004
+ if (!options.dryRun) {
7005
+ await ensureBrowserPilotHome();
7006
+ const resolvedSrc = await fs5.realpath(sourceExtDir).catch(() => path6.resolve(sourceExtDir));
7007
+ const resolvedDest = await fs5.realpath(destDir).catch(() => path6.resolve(destDir));
7008
+ if (resolvedSrc !== resolvedDest) {
7009
+ await fs5.rm(destDir, { recursive: true, force: true });
7010
+ await fs5.cp(sourceExtDir, destDir, { recursive: true });
7011
+ synced = true;
7012
+ }
7013
+ }
7014
+ const realDest = await fs5.realpath(destDir).catch(() => path6.resolve(destDir));
7015
+ return {
7016
+ extensionDir: realDest,
7017
+ extensionId: computeChromeExtensionId(realDest),
7018
+ version,
7019
+ synced
7020
+ };
7021
+ }
7022
+ async function discoverInstalledExtensionIds(platform = process.platform) {
7023
+ const found = [];
7024
+ const seen = /* @__PURE__ */ new Set();
7025
+ for (const target of getNativeMessagingHostDirs(platform)) {
7026
+ let entries;
7027
+ try {
7028
+ entries = await fs5.readdir(target.userDataDir);
7029
+ } catch {
7030
+ continue;
7031
+ }
7032
+ const profiles = entries.filter((e) => e === "Default" || e.startsWith("Profile "));
7033
+ for (const profile of profiles) {
7034
+ for (const fileName of ["Secure Preferences", "Preferences"]) {
7035
+ const prefPath = path6.join(target.userDataDir, profile, fileName);
7036
+ let parsed;
7037
+ try {
7038
+ parsed = JSON.parse(await fs5.readFile(prefPath, "utf8"));
7039
+ } catch {
7040
+ continue;
7041
+ }
7042
+ const settings = parsed.extensions?.settings;
7043
+ if (!settings || typeof settings !== "object") continue;
7044
+ for (const [extId, meta] of Object.entries(settings)) {
7045
+ if (!meta || !/^[a-p]{32}$/.test(extId)) continue;
7046
+ const manifestName = meta.manifest?.name || "";
7047
+ const extPath = meta.path || "";
7048
+ let isBrowserPilot = /^browserpilot$/i.test(manifestName) || /browserpilot/i.test(extPath);
7049
+ if (!isBrowserPilot && meta.location === 4 && extPath) {
7050
+ try {
7051
+ const m = JSON.parse(await fs5.readFile(path6.join(extPath, "manifest.json"), "utf8"));
7052
+ if (/^browserpilot$/i.test(m.name || "")) isBrowserPilot = true;
7053
+ } catch {
7054
+ }
7055
+ }
7056
+ if (isBrowserPilot && !seen.has(extId)) {
7057
+ seen.add(extId);
7058
+ found.push({ browser: target.name, profile, extensionId: extId, path: extPath || void 0 });
7059
+ }
7060
+ }
7061
+ }
7062
+ }
7063
+ }
7064
+ return found;
7065
+ }
7066
+ async function readInstalledNativeHosts(platform = process.platform) {
7067
+ const results = [];
7068
+ for (const target of getNativeMessagingHostDirs(platform)) {
7069
+ const mp = path6.join(target.dir, `${NATIVE_HOST_NAME}.json`);
7070
+ try {
7071
+ const parsed = JSON.parse(await fs5.readFile(mp, "utf8"));
7072
+ results.push({
7073
+ browser: target.name,
7074
+ installed: true,
7075
+ path: mp,
7076
+ allowedOrigins: Array.isArray(parsed.allowed_origins) ? parsed.allowed_origins : [],
7077
+ wrapperPath: parsed.path
7078
+ });
7079
+ } catch {
7080
+ results.push({ browser: target.name, installed: false, path: mp, allowedOrigins: [] });
7081
+ }
7082
+ }
7083
+ return results;
7084
+ }
6868
7085
  async function installNativeHost(options) {
6869
7086
  const nativeHostJs = path6.resolve(__dirname2, "native-host.js");
6870
7087
  const binDir = path6.join(getBrowserPilotHomeDir(), "bin");
6871
7088
  const wrapperPath = path6.join(binDir, "browserpilot-native-host");
6872
- const allowedOrigins = options.extensionIds.map((id) => id.trim()).filter(Boolean).map((id) => id.startsWith("chrome-extension://") ? id : `chrome-extension://${id}/`);
7089
+ const allowedOrigins = Array.from(
7090
+ new Set(
7091
+ options.extensionIds.map((id) => id.trim()).filter(Boolean).map((id) => id.startsWith("chrome-extension://") ? id.endsWith("/") ? id : `${id}/` : `chrome-extension://${id}/`)
7092
+ )
7093
+ );
6873
7094
  const manifestJson = {
6874
7095
  name: NATIVE_HOST_NAME,
6875
7096
  description: "BrowserPilot Zero-Click Browser Control & DevTools Bridge",
@@ -7009,34 +7230,69 @@ async function getExtensionDistPath() {
7009
7230
  return path7.resolve(__dirname3, "..", "..", "extension", "dist");
7010
7231
  }
7011
7232
  }
7233
+ async function findDynamicCachedChrome() {
7234
+ const found = [];
7235
+ const home = os5.homedir();
7236
+ const searchRoots = [
7237
+ path7.join(home, ".cache", "browserpilot-chrome", "chrome"),
7238
+ path7.join(home, "Library", "Caches", "ms-playwright"),
7239
+ path7.join(home, ".cache", "ms-playwright")
7240
+ ];
7241
+ for (const root of searchRoots) {
7242
+ let entries;
7243
+ try {
7244
+ entries = (await fs6.readdir(root)).sort().reverse();
7245
+ } catch {
7246
+ continue;
7247
+ }
7248
+ for (const entry of entries) {
7249
+ if (!entry.startsWith("chromium-") && !entry.startsWith("mac") && !entry.startsWith("linux")) continue;
7250
+ const candidates = [
7251
+ path7.join(root, entry, "chrome-mac-arm64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"),
7252
+ path7.join(root, entry, "chrome-mac-x64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"),
7253
+ path7.join(root, entry, "chrome-linux64", "chrome"),
7254
+ path7.join(root, entry, "chrome-linux", "chrome")
7255
+ ];
7256
+ for (const c of candidates) {
7257
+ try {
7258
+ await fs6.access(c);
7259
+ found.push(c);
7260
+ } catch {
7261
+ }
7262
+ }
7263
+ }
7264
+ }
7265
+ return found;
7266
+ }
7012
7267
  async function findChromeBinary() {
7013
- const candidates = [
7268
+ const staticCandidates = [
7014
7269
  process.env.BROWSERPILOT_CHROME_BIN,
7015
- path7.join(
7016
- os5.homedir(),
7017
- "Library/Caches/ms-playwright/chromium-1248/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
7018
- ),
7019
7270
  "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
7271
+ "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
7020
7272
  "/Applications/Chromium.app/Contents/MacOS/Chromium",
7273
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
7021
7274
  "/usr/bin/google-chrome",
7022
- "/usr/bin/chromium"
7275
+ "/usr/bin/google-chrome-stable",
7276
+ "/usr/bin/chromium",
7277
+ "/usr/bin/chromium-browser"
7023
7278
  ].filter(Boolean);
7024
- for (const bin of candidates) {
7279
+ for (const bin of staticCandidates) {
7025
7280
  try {
7026
7281
  await fs6.access(bin);
7027
7282
  return bin;
7028
7283
  } catch {
7029
7284
  }
7030
7285
  }
7031
- return null;
7286
+ const cached = await findDynamicCachedChrome();
7287
+ return cached[0] ?? null;
7032
7288
  }
7033
7289
  function printHelp() {
7034
7290
  console.log(`BrowserPilot v${BROWSERPILOT_VERSION} \u2014 Zero-Click Pure-CDP Browser Control & DevTools CLI
7035
7291
 
7036
7292
  Usage:
7037
- browserpilot setup [--extension-id <id>] [--dry-run] Install Native Messaging host & print MCP setup
7038
- browserpilot doctor Diagnose extension, Native Messaging, Chrome, ffmpeg & daemon
7039
- browserpilot daemon start | stop | status | run Manage local authenticated bridge daemon
7293
+ browserpilot setup [--extension-id <id>] [--dry-run] Sync extension, auto-install Native Messaging & print MCP config
7294
+ browserpilot doctor [--json] Diagnose extension, Native Messaging, Chrome, ffmpeg & daemon
7295
+ browserpilot daemon start | stop | restart | status | run Manage local authenticated bridge daemon
7040
7296
  browserpilot mcp [--cdp <url>] Start MCP stdio server (for Claude/Cursor/Codex/Antigravity)
7041
7297
  browserpilot connect-cdp <url> Attach daemon directly to a --remote-debugging-port Chrome
7042
7298
  browserpilot browser start [--headless] [--cdp-port N] Launch Chrome/Chrome for Testing with BrowserPilot ready
@@ -7047,9 +7303,11 @@ Stateful Sessions (Playwriter replacement):
7047
7303
  browserpilot exec -s <id> -e '<js>' | -f <script.js> [--timeout <ms>]
7048
7304
 
7049
7305
  Direct Quick Commands:
7306
+ browserpilot status
7050
7307
  browserpilot tabs
7051
7308
  browserpilot open <url> [--tab-group <name>]
7052
7309
  browserpilot close <tabId>
7310
+ browserpilot navigate <url> [--tab <id>]
7053
7311
  browserpilot snapshot [--tab <id>] [--search <regex>] [--scope <css>] [--full]
7054
7312
  browserpilot click <ref|selector> [--tab <id>]
7055
7313
  browserpilot fill <ref|selector> <value> [--tab <id>]
@@ -7090,6 +7348,14 @@ async function main() {
7090
7348
  extBuilt = true;
7091
7349
  } catch {
7092
7350
  }
7351
+ const stableExtDir = getStableExtensionDir();
7352
+ let stableExtVersion = null;
7353
+ try {
7354
+ const m = JSON.parse(await fs6.readFile(path7.join(stableExtDir, "manifest.json"), "utf8"));
7355
+ stableExtVersion = m.version ?? null;
7356
+ } catch {
7357
+ }
7358
+ const expectedStableExtId = computeChromeExtensionId(await fs6.realpath(stableExtDir).catch(() => stableExtDir));
7093
7359
  const chromeBin = await findChromeBinary();
7094
7360
  let hasFfmpeg = false;
7095
7361
  for (const dir of (process.env.PATH || "").split(path7.delimiter)) {
@@ -7101,49 +7367,69 @@ async function main() {
7101
7367
  } catch {
7102
7368
  }
7103
7369
  }
7104
- const nativeHosts = [];
7105
- for (const target of getNativeMessagingHostDirs()) {
7106
- const mp = path7.join(target.dir, `${NATIVE_HOST_NAME}.json`);
7107
- let installed = false;
7108
- try {
7109
- await fs6.access(mp);
7110
- installed = true;
7111
- } catch {
7112
- }
7113
- nativeHosts.push({ browser: target.name, installed, path: mp });
7114
- }
7370
+ const nativeHosts = await readInstalledNativeHosts();
7371
+ const discoveredExts = await discoverInstalledExtensionIds();
7115
7372
  const cfg = await readDaemonConfig();
7116
7373
  const daemonRunning = cfg ? await isDaemonReachable(cfg) : false;
7117
- let connectedClients = 0;
7374
+ let health = null;
7118
7375
  if (daemonRunning && cfg) {
7119
- const h = await new DaemonClient(cfg).health().catch(() => null);
7120
- connectedClients = h?.clients.length ?? 0;
7376
+ health = await new DaemonClient(cfg).health().catch(() => null);
7121
7377
  }
7378
+ const connectedClients = health?.clients ?? [];
7379
+ const versionMismatch = Boolean(health?.version && health.version !== BROWSERPILOT_VERSION);
7122
7380
  const report = {
7123
7381
  version: BROWSERPILOT_VERSION,
7124
7382
  node: process.version,
7125
7383
  extensionBuilt: extBuilt,
7126
7384
  extensionDistPath: extDist,
7385
+ stableExtensionDir: stableExtDir,
7386
+ stableExtensionVersion: stableExtVersion,
7387
+ expectedExtensionId: expectedStableExtId,
7388
+ discoveredChromeExtensions: discoveredExts,
7127
7389
  chromeBinary: chromeBin,
7128
7390
  ffmpegAvailable: hasFfmpeg,
7129
7391
  daemonConfigPresent: Boolean(cfg),
7130
7392
  daemonRunning,
7131
- connectedBrowsers: connectedClients,
7132
- nativeMessagingInstalled: nativeHosts.filter((n) => n.installed).map((n) => n.browser)
7393
+ daemonVersion: health?.version ?? null,
7394
+ daemonPid: health?.pid ?? cfg?.pid ?? null,
7395
+ daemonAddress: cfg ? `${cfg.host}:${cfg.port}` : null,
7396
+ daemonVersionMismatch: versionMismatch,
7397
+ connectedBrowsers: connectedClients.length,
7398
+ clients: connectedClients,
7399
+ nativeMessagingInstalled: nativeHosts.filter((n) => n.installed).map((n) => n.browser),
7400
+ nativeMessagingHosts: nativeHosts.filter((n) => n.installed)
7133
7401
  };
7134
7402
  if (flags.json) {
7135
7403
  console.log(JSON.stringify(report, null, 2));
7136
7404
  return;
7137
7405
  }
7138
7406
  console.log(`BrowserPilot Doctor (v${BROWSERPILOT_VERSION})`);
7139
- console.log(`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`);
7407
+ console.log(`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`);
7140
7408
  console.log(`Node.js : ${report.node}`);
7141
7409
  console.log(`Extension dist/ : ${extBuilt ? "OK" : "MISSING (run pnpm build)"} (${extDist})`);
7410
+ console.log(
7411
+ `Stable ext copy : ${stableExtVersion ? `v${stableExtVersion} (${stableExtDir}, id: ${expectedStableExtId})` : `Not synced yet (run: browserpilot setup)`}`
7412
+ );
7413
+ console.log(
7414
+ `Chrome loaded : ${discoveredExts.length ? discoveredExts.map((e) => `${e.browser}/${e.profile} (${e.extensionId})`).join(", ") : "Not detected yet (load ~/.browserpilot/extension in chrome://extensions)"}`
7415
+ );
7142
7416
  console.log(`Chrome binary : ${chromeBin ?? "Not found (set BROWSERPILOT_CHROME_BIN)"}`);
7143
7417
  console.log(`ffmpeg : ${hasFfmpeg ? "OK (video recording ready)" : "Not found (optional for recording)"}`);
7144
- console.log(`Daemon status : ${daemonRunning ? `RUNNING (browsers: ${connectedClients})` : "STOPPED"}`);
7145
7418
  console.log(
7146
- `Native Messaging : ${report.nativeMessagingInstalled.length ? `Installed (${report.nativeMessagingInstalled.join(", ")})` : "Not installed (run: browserpilot setup --extension-id <id>)"}`
7419
+ `Daemon status : ${daemonRunning ? `RUNNING v${health?.version ?? "?"} @ ${cfg?.host}:${cfg?.port} (pid: ${health?.pid ?? cfg?.pid ?? "?"}, browsers: ${connectedClients.length})` : "STOPPED"}`
7420
+ );
7421
+ if (versionMismatch) {
7422
+ console.log(
7423
+ ` \u26A0 Version mismatch: CLI is v${BROWSERPILOT_VERSION}, running daemon is v${health?.version}. Run: browserpilot daemon restart`
7424
+ );
7425
+ }
7426
+ for (const c of connectedClients) {
7427
+ console.log(
7428
+ ` \u2022 ${c.browser} [${c.transport}]${c.extensionVersion ? ` ext v${c.extensionVersion}` : ""}${c.extensionId ? ` (${c.extensionId})` : ""} \u2014 attached tabs: ${c.attachedTabCount}`
7429
+ );
7430
+ }
7431
+ console.log(
7432
+ `Native Messaging : ${report.nativeMessagingInstalled.length ? `Installed (${report.nativeMessagingInstalled.join(", ")})` : "Not installed (run: browserpilot setup)"}`
7147
7433
  );
7148
7434
  return;
7149
7435
  }
@@ -7159,31 +7445,50 @@ async function main() {
7159
7445
  if (cmd === "setup") {
7160
7446
  const cfg = await loadOrCreateDaemonConfig();
7161
7447
  const extDist = await getExtensionDistPath();
7162
- const extId = typeof flags["extension-id"] === "string" ? flags["extension-id"] : "";
7448
+ const explicitExtId = typeof flags["extension-id"] === "string" ? flags["extension-id"] : "";
7163
7449
  const dryRun = Boolean(flags["dry-run"]);
7450
+ const skipNative = Boolean(flags["no-native-host"]);
7451
+ const synced = await syncExtensionToHome(extDist, { dryRun });
7452
+ const discovered = await discoverInstalledExtensionIds();
7453
+ const bundledReal = await fs6.realpath(extDist).catch(() => path7.resolve(extDist));
7454
+ const bundledExtId = computeChromeExtensionId(bundledReal);
7455
+ const allExtIds = Array.from(
7456
+ new Set(
7457
+ [
7458
+ synced.extensionId,
7459
+ bundledExtId,
7460
+ ...discovered.map((d) => d.extensionId),
7461
+ ...explicitExtId.split(",").map((s) => s.trim())
7462
+ ].filter(Boolean)
7463
+ )
7464
+ );
7164
7465
  console.log(`
7165
7466
  BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
7166
7467
  console.log(`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`);
7167
- console.log(`1. Unpacked Extension Path:
7168
- ${extDist}`);
7169
- console.log(` -> Open chrome://extensions -> Enable "Developer mode" -> "Load unpacked" -> select the path above.`);
7468
+ console.log(`1. Stable Unpacked Extension Path (upgrade-safe):`);
7469
+ console.log(` ${synced.extensionDir}`);
7470
+ console.log(` Expected Chrome Extension ID : ${synced.extensionId}`);
7471
+ if (discovered.length > 0) {
7472
+ console.log(
7473
+ ` Already detected in Chrome : ${discovered.map((d) => `${d.browser}/${d.profile} (${d.extensionId})`).join(", ")}`
7474
+ );
7475
+ } else {
7476
+ console.log(` -> Open chrome://extensions -> Enable "Developer mode" -> "Load unpacked" -> select the path above.`);
7477
+ }
7170
7478
  console.log(`
7171
7479
  2. Local Daemon Config (~/.browserpilot/daemon.json):`);
7172
7480
  console.log(` WebSocket URL : ws://${cfg.host}:${cfg.port}/extension`);
7173
7481
  console.log(` Auth Token : ${cfg.token}`);
7174
- if (extId) {
7175
- const res = await installNativeHost({ extensionIds: [extId], dryRun });
7482
+ if (!skipNative) {
7483
+ const res = await installNativeHost({ extensionIds: allExtIds, dryRun });
7176
7484
  console.log(`
7177
- 3. Chrome Native Messaging Host (${dryRun ? "dry-run" : "installed"}):`);
7178
- console.log(` Wrapper: ${res.wrapperPath}`);
7485
+ 3. Chrome Native Messaging Host (${dryRun ? "dry-run" : "installed automatically"}):`);
7486
+ console.log(` Wrapper : ${res.wrapperPath}`);
7487
+ console.log(` Allowed : ${allExtIds.join(", ")}`);
7179
7488
  for (const m of res.installedManifests) {
7180
7489
  console.log(` - ${m.browser}: ${m.manifestPath}`);
7181
7490
  }
7182
- } else {
7183
- console.log(`
7184
- 3. Optional (Recommended) Native Messaging Auto-Auth:`);
7185
- console.log(` After loading the unpacked extension, copy its Extension ID from chrome://extensions and run:`);
7186
- console.log(` browserpilot setup --extension-id <YOUR_EXTENSION_ID>`);
7491
+ console.log(` -> Zero manual token entry or --extension-id needed! Extension connects automatically once loaded.`);
7187
7492
  }
7188
7493
  const cliBin = path7.resolve(__dirname3, "cli.js");
7189
7494
  console.log(`
@@ -7224,7 +7529,7 @@ BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
7224
7529
  if (sub === "start") {
7225
7530
  const client2 = await DaemonClient.connectOrStart();
7226
7531
  const h = await client2.health();
7227
- console.log(`BrowserPilot daemon running on http://${client2.config.host}:${client2.config.port} (clients: ${h.clients.length})`);
7532
+ console.log(`BrowserPilot daemon v${h.version} running on http://${client2.config.host}:${client2.config.port} (clients: ${h.clients.length})`);
7228
7533
  return;
7229
7534
  }
7230
7535
  if (sub === "stop") {
@@ -7237,6 +7542,20 @@ BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
7237
7542
  console.log("BrowserPilot daemon stopped.");
7238
7543
  return;
7239
7544
  }
7545
+ if (sub === "restart") {
7546
+ const cfg = await readDaemonConfig();
7547
+ if (cfg && await isDaemonReachable(cfg)) {
7548
+ await new DaemonClient(cfg).shutdown();
7549
+ for (let i = 0; i < 20; i++) {
7550
+ await new Promise((r) => setTimeout(r, 100));
7551
+ if (!await isDaemonReachable(cfg)) break;
7552
+ }
7553
+ }
7554
+ const client2 = await DaemonClient.connectOrStart();
7555
+ const h = await client2.health();
7556
+ console.log(`BrowserPilot daemon restarted (v${h.version}) on http://${client2.config.host}:${client2.config.port} (clients: ${h.clients.length})`);
7557
+ return;
7558
+ }
7240
7559
  if (sub === "status") {
7241
7560
  const cfg = await readDaemonConfig();
7242
7561
  if (!cfg || !await isDaemonReachable(cfg)) {
@@ -7258,6 +7577,7 @@ BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
7258
7577
  const args = [
7259
7578
  "--no-first-run",
7260
7579
  "--no-default-browser-check",
7580
+ "--window-size=1280,800",
7261
7581
  `--remote-debugging-port=${cdpPort}`,
7262
7582
  `--user-data-dir=${profileDir}`
7263
7583
  ];
@@ -7343,6 +7663,9 @@ BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
7343
7663
  return;
7344
7664
  }
7345
7665
  switch (cmd) {
7666
+ case "status":
7667
+ printToolOutput(await client.callTool("browser_status"));
7668
+ return;
7346
7669
  case "tabs":
7347
7670
  printToolOutput(await client.callTool("browser_tabs"));
7348
7671
  return;