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/index.js CHANGED
@@ -5,7 +5,7 @@ import os from "node:os";
5
5
  import path from "node:path";
6
6
 
7
7
  // ../protocol/dist/constants.js
8
- var BROWSERPILOT_VERSION = "1.2.0";
8
+ var BROWSERPILOT_VERSION = "1.2.2";
9
9
  var DEFAULT_DAEMON_HOST = "127.0.0.1";
10
10
  var DEFAULT_DAEMON_PORT = 19888;
11
11
  var NATIVE_HOST_NAME = "com.browserpilot.bridge";
@@ -29,6 +29,23 @@ var BLOCKED_PROFILE_WIDE_CDP_COMMANDS = /* @__PURE__ */ new Set([
29
29
  "Network.clearBrowserCookies",
30
30
  "Network.clearBrowserCache"
31
31
  ]);
32
+ var RESTRICTED_URL_PREFIXES = [
33
+ "chrome://",
34
+ "chrome-extension://",
35
+ "chrome-untrusted://",
36
+ "devtools://",
37
+ "edge://",
38
+ "brave://",
39
+ "about:blank#blocked",
40
+ "https://chrome.google.com/webstore",
41
+ "https://chromewebstore.google.com"
42
+ ];
43
+ function isRestrictedUrl(url) {
44
+ if (!url)
45
+ return false;
46
+ const lower = url.toLowerCase();
47
+ return RESTRICTED_URL_PREFIXES.some((prefix) => lower.startsWith(prefix));
48
+ }
32
49
  function isBlockedProfileWideCommand(method) {
33
50
  return BLOCKED_PROFILE_WIDE_CDP_COMMANDS.has(method);
34
51
  }
@@ -789,16 +806,19 @@ async function waitForPageLoad(session, options = {}) {
789
806
  await sleep(Math.min(minWaitMs, timeoutMs));
790
807
  }
791
808
  while (Date.now() - start < timeoutMs) {
809
+ let href = "";
792
810
  try {
793
811
  const res = await session.send("Runtime.evaluate", {
794
- expression: "document.readyState",
812
+ expression: "({ readyState: document.readyState, href: location.href })",
795
813
  returnByValue: true
796
814
  });
797
- readyState = res.result?.value ?? "loading";
815
+ readyState = res.result?.value?.readyState ?? "loading";
816
+ href = res.result?.value?.href ?? "";
798
817
  } catch {
799
818
  readyState = "loading";
800
819
  }
801
- if ((readyState === "complete" || readyState === "interactive") && inflight.size === 0) {
820
+ const stillOnBlank = Boolean(options.ignoreAboutBlank) && (!href || href === "about:blank");
821
+ if (!stillOnBlank && (readyState === "complete" || readyState === "interactive") && inflight.size === 0) {
802
822
  if (idleSince === null)
803
823
  idleSince = Date.now();
804
824
  if (Date.now() - idleSince >= idleMs || readyState === "complete") {
@@ -2447,6 +2467,7 @@ var ROLE_COLORS = {
2447
2467
  };
2448
2468
  async function captureLabeledScreenshot(page, options = {}) {
2449
2469
  const maxLabels = options.maxLabels ?? 120;
2470
+ await page.session.enableDomain("DOM");
2450
2471
  const snapshot = await page.snapshotEngine.capture(page.session, { showDiffSinceLastCall: false });
2451
2472
  const viewport = await page.evaluate("({ width: window.innerWidth, height: window.innerHeight })");
2452
2473
  const labels = [];
@@ -2976,9 +2997,12 @@ var StylesInspector = class {
2976
2997
  const extractDecls = (props) => {
2977
2998
  if (!props)
2978
2999
  return [];
3000
+ const hasAuthoredRanges = props.some((p) => Boolean(p.range || p.text));
2979
3001
  const out = [];
2980
3002
  for (const p of props) {
2981
- if (p.disabled || !p.name || p.name.startsWith("-webkit-") || !p.value)
3003
+ if (p.disabled || p.implicit || !p.name || p.name.startsWith("-webkit-") || !p.value)
3004
+ continue;
3005
+ if (hasAuthoredRanges && !p.range && !p.text)
2982
3006
  continue;
2983
3007
  const overridden = seenProps.has(p.name);
2984
3008
  seenProps.add(p.name);
@@ -4698,6 +4722,9 @@ var SessionManager = class {
4698
4722
  getTransport() {
4699
4723
  return this.transport;
4700
4724
  }
4725
+ getAttachedTabCount() {
4726
+ return this.tabs.size;
4727
+ }
4701
4728
  async getOrAttachTab(tabId, options) {
4702
4729
  await this.transport.attachTab(tabId, options);
4703
4730
  let tab = this.tabs.get(tabId);
@@ -4751,7 +4778,8 @@ var SessionManager = class {
4751
4778
  session.activeTabId = void 0;
4752
4779
  }
4753
4780
  const allTabs = await this.listTabs();
4754
- const candidate = allTabs.find((t) => t.active && !t.url.startsWith("chrome://")) ?? allTabs.find((t) => !t.url.startsWith("chrome://"));
4781
+ const attachable = allTabs.filter((t) => !isRestrictedUrl(t.url));
4782
+ 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];
4755
4783
  if (candidate) {
4756
4784
  const tab = await this.getOrAttachTab(candidate.tabId, groupOpts);
4757
4785
  if (session)
@@ -4994,6 +5022,16 @@ ${code}
4994
5022
  function textResult(text, meta) {
4995
5023
  return { content: [{ type: "text", text }], meta };
4996
5024
  }
5025
+ function normalizeNavigationUrl(raw) {
5026
+ const trimmed = (raw ?? "").trim();
5027
+ if (!trimmed) return "about:blank";
5028
+ if (/^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/|$)/i.test(trimmed)) {
5029
+ return `http://${trimmed}`;
5030
+ }
5031
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(trimmed)) return trimmed;
5032
+ if (/^(about|data|file|javascript|mailto|blob|view-source):/i.test(trimmed)) return trimmed;
5033
+ return `https://${trimmed}`;
5034
+ }
4997
5035
  function formatFeedbackSuffix(fb) {
4998
5036
  const parts = [`URL: ${fb.url}`];
4999
5037
  if (fb.newConsoleErrors.length > 0) {
@@ -5721,15 +5759,23 @@ async function executeTool(ctx, name, args = {}) {
5721
5759
  return textResult(formatted || "(no tabs open)", { tabs });
5722
5760
  }
5723
5761
  case "browser_open_tab": {
5762
+ const targetUrl = normalizeNavigationUrl(args.url);
5724
5763
  const tab = await manager.openTab({
5725
- url: args.url,
5764
+ url: targetUrl,
5726
5765
  active: args.active,
5727
5766
  tabGroup: args.tabGroup,
5728
5767
  tabGroupColor: args.tabGroupColor
5729
5768
  });
5730
5769
  if (sessionId) manager.getOrCreateSession(sessionId).activeTabId = tab.tabId;
5731
- const meta = await tab.page.getUrlAndTitle().catch(() => ({ url: String(args.url ?? "about:blank"), title: "" }));
5732
- return textResult(`Opened and attached tab [${tab.tabId}]: ${meta.url}`, { tabId: tab.tabId, ...meta });
5770
+ if (/^https?:\/\//i.test(targetUrl)) {
5771
+ await waitForPageLoad(tab.session, { timeoutMs: 1e4, idleMs: 250, ignoreAboutBlank: true }).catch(() => {
5772
+ });
5773
+ }
5774
+ const meta = await tab.page.getUrlAndTitle().catch(() => ({ url: targetUrl, title: "" }));
5775
+ return textResult(`Opened and attached tab [${tab.tabId}]: ${meta.url}${meta.title ? ` ("${meta.title}")` : ""}`, {
5776
+ tabId: tab.tabId,
5777
+ ...meta
5778
+ });
5733
5779
  }
5734
5780
  case "browser_close_tab": {
5735
5781
  await manager.closeTab(Number(args.tabId));
@@ -5752,8 +5798,9 @@ async function executeTool(ctx, name, args = {}) {
5752
5798
  }
5753
5799
  case "browser_navigate": {
5754
5800
  const tab = await resolveTab();
5801
+ const targetUrl = normalizeNavigationUrl(String(args.url));
5755
5802
  const { result, feedback } = await tab.runWithFeedback(
5756
- () => tab.page.navigate(String(args.url), {
5803
+ () => tab.page.navigate(targetUrl, {
5757
5804
  waitUntil: args.waitUntil ?? "domcontentloaded",
5758
5805
  timeoutMs: args.timeoutMs
5759
5806
  })
@@ -6517,6 +6564,15 @@ var BrowserPilotDaemon = class {
6517
6564
  };
6518
6565
  this.backends.set(clientId, { info, transport, manager });
6519
6566
  this.primaryClientId = clientId;
6567
+ if (ws.readyState === ws.OPEN) {
6568
+ ws.send(
6569
+ JSON.stringify({
6570
+ type: "event",
6571
+ event: "bridge.ready",
6572
+ params: { version: BROWSERPILOT_VERSION, clientId }
6573
+ })
6574
+ );
6575
+ }
6520
6576
  ws.on("close", () => {
6521
6577
  manager.dispose();
6522
6578
  this.backends.delete(clientId);
@@ -6559,7 +6615,10 @@ var BrowserPilotDaemon = class {
6559
6615
  return info;
6560
6616
  }
6561
6617
  listClients() {
6562
- return Array.from(this.backends.values()).map((b) => b.info);
6618
+ return Array.from(this.backends.values()).map((b) => ({
6619
+ ...b.info,
6620
+ attachedTabCount: b.manager.getAttachedTabCount()
6621
+ }));
6563
6622
  }
6564
6623
  getManager(clientId) {
6565
6624
  const targetId = clientId ?? this.primaryClientId;
@@ -6592,6 +6651,7 @@ var BrowserPilotDaemon = class {
6592
6651
  this.sendJson(res, 200, {
6593
6652
  ok: true,
6594
6653
  version: BROWSERPILOT_VERSION,
6654
+ pid: process.pid,
6595
6655
  uptimeMs: Date.now() - this.startedAt,
6596
6656
  clients: this.listClients()
6597
6657
  });
@@ -6805,14 +6865,27 @@ async function startMcpServer(options = {}) {
6805
6865
  };
6806
6866
  result = await executeTool(ctx, name, args);
6807
6867
  } else {
6808
- if (!daemonClient) {
6809
- daemonClient = await DaemonClient.connectOrStart({
6810
- host: options.daemonHost,
6811
- port: options.daemonPort,
6812
- token: options.daemonToken
6813
- });
6868
+ const ensureDaemon = async () => {
6869
+ if (!daemonClient) {
6870
+ daemonClient = await DaemonClient.connectOrStart({
6871
+ host: options.daemonHost,
6872
+ port: options.daemonPort,
6873
+ token: options.daemonToken
6874
+ });
6875
+ }
6876
+ return daemonClient;
6877
+ };
6878
+ try {
6879
+ result = await (await ensureDaemon()).callTool(name, args);
6880
+ } catch (err) {
6881
+ const msg = err instanceof Error ? err.message : String(err);
6882
+ if (/fetch failed|ECONNREFUSED|ECONNRESET|socket|Unauthorized/i.test(msg)) {
6883
+ daemonClient = null;
6884
+ result = await (await ensureDaemon()).callTool(name, args);
6885
+ } else {
6886
+ throw err;
6887
+ }
6814
6888
  }
6815
- result = await daemonClient.callTool(name, args);
6816
6889
  }
6817
6890
  return {
6818
6891
  isError: result.isError,
@@ -6829,6 +6902,7 @@ async function startMcpServer(options = {}) {
6829
6902
  }
6830
6903
 
6831
6904
  // src/native-install.ts
6905
+ import crypto3 from "node:crypto";
6832
6906
  import fs5 from "node:fs/promises";
6833
6907
  import os4 from "node:os";
6834
6908
  import path6 from "node:path";
@@ -6839,31 +6913,178 @@ function getNativeMessagingHostDirs(platform = process.platform) {
6839
6913
  if (platform === "darwin") {
6840
6914
  const appSupport = path6.join(home, "Library", "Application Support");
6841
6915
  return [
6842
- { name: "Google Chrome", dir: path6.join(appSupport, "Google", "Chrome", "NativeMessagingHosts") },
6843
- { name: "Google Chrome Canary", dir: path6.join(appSupport, "Google", "Chrome Canary", "NativeMessagingHosts") },
6844
- { name: "Google Chrome for Testing", dir: path6.join(appSupport, "Google", "Chrome for Testing", "NativeMessagingHosts") },
6845
- { name: "Chromium", dir: path6.join(appSupport, "Chromium", "NativeMessagingHosts") },
6846
- { name: "Brave", dir: path6.join(appSupport, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts") },
6847
- { name: "Microsoft Edge", dir: path6.join(appSupport, "Microsoft Edge", "NativeMessagingHosts") },
6848
- { name: "Arc", dir: path6.join(appSupport, "Arc", "User Data", "NativeMessagingHosts") }
6916
+ {
6917
+ name: "Google Chrome",
6918
+ userDataDir: path6.join(appSupport, "Google", "Chrome"),
6919
+ dir: path6.join(appSupport, "Google", "Chrome", "NativeMessagingHosts")
6920
+ },
6921
+ {
6922
+ name: "Google Chrome Canary",
6923
+ userDataDir: path6.join(appSupport, "Google", "Chrome Canary"),
6924
+ dir: path6.join(appSupport, "Google", "Chrome Canary", "NativeMessagingHosts")
6925
+ },
6926
+ {
6927
+ name: "Google Chrome for Testing",
6928
+ userDataDir: path6.join(appSupport, "Google", "Chrome for Testing"),
6929
+ dir: path6.join(appSupport, "Google", "Chrome for Testing", "NativeMessagingHosts")
6930
+ },
6931
+ {
6932
+ name: "Chromium",
6933
+ userDataDir: path6.join(appSupport, "Chromium"),
6934
+ dir: path6.join(appSupport, "Chromium", "NativeMessagingHosts")
6935
+ },
6936
+ {
6937
+ name: "Brave",
6938
+ userDataDir: path6.join(appSupport, "BraveSoftware", "Brave-Browser"),
6939
+ dir: path6.join(appSupport, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts")
6940
+ },
6941
+ {
6942
+ name: "Microsoft Edge",
6943
+ userDataDir: path6.join(appSupport, "Microsoft Edge"),
6944
+ dir: path6.join(appSupport, "Microsoft Edge", "NativeMessagingHosts")
6945
+ },
6946
+ {
6947
+ name: "Arc",
6948
+ userDataDir: path6.join(appSupport, "Arc", "User Data"),
6949
+ dir: path6.join(appSupport, "Arc", "User Data", "NativeMessagingHosts")
6950
+ }
6849
6951
  ];
6850
6952
  }
6851
6953
  if (platform === "linux") {
6852
6954
  const config = path6.join(home, ".config");
6853
6955
  return [
6854
- { name: "Google Chrome", dir: path6.join(config, "google-chrome", "NativeMessagingHosts") },
6855
- { name: "Chromium", dir: path6.join(config, "chromium", "NativeMessagingHosts") },
6856
- { name: "Brave", dir: path6.join(config, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts") },
6857
- { name: "Microsoft Edge", dir: path6.join(config, "microsoft-edge", "NativeMessagingHosts") }
6956
+ {
6957
+ name: "Google Chrome",
6958
+ userDataDir: path6.join(config, "google-chrome"),
6959
+ dir: path6.join(config, "google-chrome", "NativeMessagingHosts")
6960
+ },
6961
+ {
6962
+ name: "Chromium",
6963
+ userDataDir: path6.join(config, "chromium"),
6964
+ dir: path6.join(config, "chromium", "NativeMessagingHosts")
6965
+ },
6966
+ {
6967
+ name: "Brave",
6968
+ userDataDir: path6.join(config, "BraveSoftware", "Brave-Browser"),
6969
+ dir: path6.join(config, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts")
6970
+ },
6971
+ {
6972
+ name: "Microsoft Edge",
6973
+ userDataDir: path6.join(config, "microsoft-edge"),
6974
+ dir: path6.join(config, "microsoft-edge", "NativeMessagingHosts")
6975
+ }
6858
6976
  ];
6859
6977
  }
6860
6978
  return [];
6861
6979
  }
6980
+ function computeChromeExtensionId(unpackedDir) {
6981
+ const normalized = path6.resolve(unpackedDir);
6982
+ const hash = crypto3.createHash("sha256").update(normalized, "utf8").digest("hex").slice(0, 32);
6983
+ return hash.replace(/[0-9a-f]/g, (ch) => String.fromCharCode(97 + Number.parseInt(ch, 16)));
6984
+ }
6985
+ function getStableExtensionDir() {
6986
+ return path6.join(getBrowserPilotHomeDir(), "extension");
6987
+ }
6988
+ async function syncExtensionToHome(sourceExtDir, options = {}) {
6989
+ const destDir = getStableExtensionDir();
6990
+ let version = null;
6991
+ try {
6992
+ const manifestRaw = await fs5.readFile(path6.join(sourceExtDir, "manifest.json"), "utf8");
6993
+ const manifest = JSON.parse(manifestRaw);
6994
+ version = manifest.version ?? null;
6995
+ } catch {
6996
+ }
6997
+ let synced = false;
6998
+ if (!options.dryRun) {
6999
+ await ensureBrowserPilotHome();
7000
+ const resolvedSrc = await fs5.realpath(sourceExtDir).catch(() => path6.resolve(sourceExtDir));
7001
+ const resolvedDest = await fs5.realpath(destDir).catch(() => path6.resolve(destDir));
7002
+ if (resolvedSrc !== resolvedDest) {
7003
+ await fs5.rm(destDir, { recursive: true, force: true });
7004
+ await fs5.cp(sourceExtDir, destDir, { recursive: true });
7005
+ synced = true;
7006
+ }
7007
+ }
7008
+ const realDest = await fs5.realpath(destDir).catch(() => path6.resolve(destDir));
7009
+ return {
7010
+ extensionDir: realDest,
7011
+ extensionId: computeChromeExtensionId(realDest),
7012
+ version,
7013
+ synced
7014
+ };
7015
+ }
7016
+ async function discoverInstalledExtensionIds(platform = process.platform) {
7017
+ const found = [];
7018
+ const seen = /* @__PURE__ */ new Set();
7019
+ for (const target of getNativeMessagingHostDirs(platform)) {
7020
+ let entries;
7021
+ try {
7022
+ entries = await fs5.readdir(target.userDataDir);
7023
+ } catch {
7024
+ continue;
7025
+ }
7026
+ const profiles = entries.filter((e) => e === "Default" || e.startsWith("Profile "));
7027
+ for (const profile of profiles) {
7028
+ for (const fileName of ["Secure Preferences", "Preferences"]) {
7029
+ const prefPath = path6.join(target.userDataDir, profile, fileName);
7030
+ let parsed;
7031
+ try {
7032
+ parsed = JSON.parse(await fs5.readFile(prefPath, "utf8"));
7033
+ } catch {
7034
+ continue;
7035
+ }
7036
+ const settings = parsed.extensions?.settings;
7037
+ if (!settings || typeof settings !== "object") continue;
7038
+ for (const [extId, meta] of Object.entries(settings)) {
7039
+ if (!meta || !/^[a-p]{32}$/.test(extId)) continue;
7040
+ const manifestName = meta.manifest?.name || "";
7041
+ const extPath = meta.path || "";
7042
+ let isBrowserPilot = /^browserpilot$/i.test(manifestName) || /browserpilot/i.test(extPath);
7043
+ if (!isBrowserPilot && meta.location === 4 && extPath) {
7044
+ try {
7045
+ const m = JSON.parse(await fs5.readFile(path6.join(extPath, "manifest.json"), "utf8"));
7046
+ if (/^browserpilot$/i.test(m.name || "")) isBrowserPilot = true;
7047
+ } catch {
7048
+ }
7049
+ }
7050
+ if (isBrowserPilot && !seen.has(extId)) {
7051
+ seen.add(extId);
7052
+ found.push({ browser: target.name, profile, extensionId: extId, path: extPath || void 0 });
7053
+ }
7054
+ }
7055
+ }
7056
+ }
7057
+ }
7058
+ return found;
7059
+ }
7060
+ async function readInstalledNativeHosts(platform = process.platform) {
7061
+ const results = [];
7062
+ for (const target of getNativeMessagingHostDirs(platform)) {
7063
+ const mp = path6.join(target.dir, `${NATIVE_HOST_NAME}.json`);
7064
+ try {
7065
+ const parsed = JSON.parse(await fs5.readFile(mp, "utf8"));
7066
+ results.push({
7067
+ browser: target.name,
7068
+ installed: true,
7069
+ path: mp,
7070
+ allowedOrigins: Array.isArray(parsed.allowed_origins) ? parsed.allowed_origins : [],
7071
+ wrapperPath: parsed.path
7072
+ });
7073
+ } catch {
7074
+ results.push({ browser: target.name, installed: false, path: mp, allowedOrigins: [] });
7075
+ }
7076
+ }
7077
+ return results;
7078
+ }
6862
7079
  async function installNativeHost(options) {
6863
7080
  const nativeHostJs = path6.resolve(__dirname2, "native-host.js");
6864
7081
  const binDir = path6.join(getBrowserPilotHomeDir(), "bin");
6865
7082
  const wrapperPath = path6.join(binDir, "browserpilot-native-host");
6866
- const allowedOrigins = options.extensionIds.map((id) => id.trim()).filter(Boolean).map((id) => id.startsWith("chrome-extension://") ? id : `chrome-extension://${id}/`);
7083
+ const allowedOrigins = Array.from(
7084
+ new Set(
7085
+ options.extensionIds.map((id) => id.trim()).filter(Boolean).map((id) => id.startsWith("chrome-extension://") ? id.endsWith("/") ? id : `${id}/` : `chrome-extension://${id}/`)
7086
+ )
7087
+ );
6867
7088
  const manifestJson = {
6868
7089
  name: NATIVE_HOST_NAME,
6869
7090
  description: "BrowserPilot Zero-Click Browser Control & DevTools Bridge",
@@ -6951,17 +7172,23 @@ export {
6951
7172
  BrowserPilotDaemon,
6952
7173
  DaemonClient,
6953
7174
  TOOL_DEFINITIONS,
7175
+ computeChromeExtensionId,
7176
+ discoverInstalledExtensionIds,
6954
7177
  ensureBrowserPilotHome,
6955
7178
  executeTool,
6956
7179
  getBrowserPilotHomeDir,
6957
7180
  getDaemonConfigPath,
6958
7181
  getDaemonLogPath,
6959
7182
  getNativeMessagingHostDirs,
7183
+ getStableExtensionDir,
6960
7184
  installNativeHost,
6961
7185
  isDaemonReachable,
6962
7186
  loadOrCreateDaemonConfig,
7187
+ normalizeNavigationUrl,
6963
7188
  readDaemonConfig,
7189
+ readInstalledNativeHosts,
6964
7190
  startMcpServer,
7191
+ syncExtensionToHome,
6965
7192
  writeDaemonRuntimeInfo
6966
7193
  };
6967
7194
  //# sourceMappingURL=index.js.map