browserpilot-cdp 1.2.0 → 1.2.1

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.1";
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
  }
@@ -4785,6 +4802,9 @@ var SessionManager = class {
4785
4802
  getTransport() {
4786
4803
  return this.transport;
4787
4804
  }
4805
+ getAttachedTabCount() {
4806
+ return this.tabs.size;
4807
+ }
4788
4808
  async getOrAttachTab(tabId, options) {
4789
4809
  await this.transport.attachTab(tabId, options);
4790
4810
  let tab = this.tabs.get(tabId);
@@ -4838,7 +4858,8 @@ var SessionManager = class {
4838
4858
  session.activeTabId = void 0;
4839
4859
  }
4840
4860
  const allTabs = await this.listTabs();
4841
- const candidate = allTabs.find((t) => t.active && !t.url.startsWith("chrome://")) ?? allTabs.find((t) => !t.url.startsWith("chrome://"));
4861
+ const attachable = allTabs.filter((t) => !isRestrictedUrl(t.url));
4862
+ 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
4863
  if (candidate) {
4843
4864
  const tab = await this.getOrAttachTab(candidate.tabId, groupOpts);
4844
4865
  if (session)
@@ -5081,6 +5102,16 @@ ${code}
5081
5102
  function textResult(text, meta) {
5082
5103
  return { content: [{ type: "text", text }], meta };
5083
5104
  }
5105
+ function normalizeNavigationUrl(raw) {
5106
+ const trimmed = (raw ?? "").trim();
5107
+ if (!trimmed) return "about:blank";
5108
+ if (/^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/|$)/i.test(trimmed)) {
5109
+ return `http://${trimmed}`;
5110
+ }
5111
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(trimmed)) return trimmed;
5112
+ if (/^(about|data|file|javascript|mailto|blob|view-source):/i.test(trimmed)) return trimmed;
5113
+ return `https://${trimmed}`;
5114
+ }
5084
5115
  function formatFeedbackSuffix(fb) {
5085
5116
  const parts = [`URL: ${fb.url}`];
5086
5117
  if (fb.newConsoleErrors.length > 0) {
@@ -5808,15 +5839,23 @@ async function executeTool(ctx, name, args = {}) {
5808
5839
  return textResult(formatted || "(no tabs open)", { tabs });
5809
5840
  }
5810
5841
  case "browser_open_tab": {
5842
+ const targetUrl = normalizeNavigationUrl(args.url);
5811
5843
  const tab = await manager.openTab({
5812
- url: args.url,
5844
+ url: targetUrl,
5813
5845
  active: args.active,
5814
5846
  tabGroup: args.tabGroup,
5815
5847
  tabGroupColor: args.tabGroupColor
5816
5848
  });
5817
5849
  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 });
5850
+ if (/^https?:\/\//i.test(targetUrl)) {
5851
+ await waitForPageLoad(tab.session, { timeoutMs: 6e3, idleMs: 200 }).catch(() => {
5852
+ });
5853
+ }
5854
+ const meta = await tab.page.getUrlAndTitle().catch(() => ({ url: targetUrl, title: "" }));
5855
+ return textResult(`Opened and attached tab [${tab.tabId}]: ${meta.url}${meta.title ? ` ("${meta.title}")` : ""}`, {
5856
+ tabId: tab.tabId,
5857
+ ...meta
5858
+ });
5820
5859
  }
5821
5860
  case "browser_close_tab": {
5822
5861
  await manager.closeTab(Number(args.tabId));
@@ -5839,8 +5878,9 @@ async function executeTool(ctx, name, args = {}) {
5839
5878
  }
5840
5879
  case "browser_navigate": {
5841
5880
  const tab = await resolveTab();
5881
+ const targetUrl = normalizeNavigationUrl(String(args.url));
5842
5882
  const { result, feedback } = await tab.runWithFeedback(
5843
- () => tab.page.navigate(String(args.url), {
5883
+ () => tab.page.navigate(targetUrl, {
5844
5884
  waitUntil: args.waitUntil ?? "domcontentloaded",
5845
5885
  timeoutMs: args.timeoutMs
5846
5886
  })
@@ -6604,6 +6644,15 @@ var BrowserPilotDaemon = class {
6604
6644
  };
6605
6645
  this.backends.set(clientId, { info, transport, manager });
6606
6646
  this.primaryClientId = clientId;
6647
+ if (ws.readyState === ws.OPEN) {
6648
+ ws.send(
6649
+ JSON.stringify({
6650
+ type: "event",
6651
+ event: "bridge.ready",
6652
+ params: { version: BROWSERPILOT_VERSION, clientId }
6653
+ })
6654
+ );
6655
+ }
6607
6656
  ws.on("close", () => {
6608
6657
  manager.dispose();
6609
6658
  this.backends.delete(clientId);
@@ -6646,7 +6695,10 @@ var BrowserPilotDaemon = class {
6646
6695
  return info;
6647
6696
  }
6648
6697
  listClients() {
6649
- return Array.from(this.backends.values()).map((b) => b.info);
6698
+ return Array.from(this.backends.values()).map((b) => ({
6699
+ ...b.info,
6700
+ attachedTabCount: b.manager.getAttachedTabCount()
6701
+ }));
6650
6702
  }
6651
6703
  getManager(clientId) {
6652
6704
  const targetId = clientId ?? this.primaryClientId;
@@ -6679,6 +6731,7 @@ var BrowserPilotDaemon = class {
6679
6731
  this.sendJson(res, 200, {
6680
6732
  ok: true,
6681
6733
  version: BROWSERPILOT_VERSION,
6734
+ pid: process.pid,
6682
6735
  uptimeMs: Date.now() - this.startedAt,
6683
6736
  clients: this.listClients()
6684
6737
  });
@@ -6811,14 +6864,27 @@ async function startMcpServer(options = {}) {
6811
6864
  };
6812
6865
  result = await executeTool(ctx, name, args);
6813
6866
  } else {
6814
- if (!daemonClient) {
6815
- daemonClient = await DaemonClient.connectOrStart({
6816
- host: options.daemonHost,
6817
- port: options.daemonPort,
6818
- token: options.daemonToken
6819
- });
6867
+ const ensureDaemon = async () => {
6868
+ if (!daemonClient) {
6869
+ daemonClient = await DaemonClient.connectOrStart({
6870
+ host: options.daemonHost,
6871
+ port: options.daemonPort,
6872
+ token: options.daemonToken
6873
+ });
6874
+ }
6875
+ return daemonClient;
6876
+ };
6877
+ try {
6878
+ result = await (await ensureDaemon()).callTool(name, args);
6879
+ } catch (err) {
6880
+ const msg = err instanceof Error ? err.message : String(err);
6881
+ if (/fetch failed|ECONNREFUSED|ECONNRESET|socket|Unauthorized/i.test(msg)) {
6882
+ daemonClient = null;
6883
+ result = await (await ensureDaemon()).callTool(name, args);
6884
+ } else {
6885
+ throw err;
6886
+ }
6820
6887
  }
6821
- result = await daemonClient.callTool(name, args);
6822
6888
  }
6823
6889
  return {
6824
6890
  isError: result.isError,
@@ -6835,6 +6901,7 @@ async function startMcpServer(options = {}) {
6835
6901
  }
6836
6902
 
6837
6903
  // src/native-install.ts
6904
+ import crypto3 from "node:crypto";
6838
6905
  import fs5 from "node:fs/promises";
6839
6906
  import os4 from "node:os";
6840
6907
  import path6 from "node:path";
@@ -6845,31 +6912,178 @@ function getNativeMessagingHostDirs(platform = process.platform) {
6845
6912
  if (platform === "darwin") {
6846
6913
  const appSupport = path6.join(home, "Library", "Application Support");
6847
6914
  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") }
6915
+ {
6916
+ name: "Google Chrome",
6917
+ userDataDir: path6.join(appSupport, "Google", "Chrome"),
6918
+ dir: path6.join(appSupport, "Google", "Chrome", "NativeMessagingHosts")
6919
+ },
6920
+ {
6921
+ name: "Google Chrome Canary",
6922
+ userDataDir: path6.join(appSupport, "Google", "Chrome Canary"),
6923
+ dir: path6.join(appSupport, "Google", "Chrome Canary", "NativeMessagingHosts")
6924
+ },
6925
+ {
6926
+ name: "Google Chrome for Testing",
6927
+ userDataDir: path6.join(appSupport, "Google", "Chrome for Testing"),
6928
+ dir: path6.join(appSupport, "Google", "Chrome for Testing", "NativeMessagingHosts")
6929
+ },
6930
+ {
6931
+ name: "Chromium",
6932
+ userDataDir: path6.join(appSupport, "Chromium"),
6933
+ dir: path6.join(appSupport, "Chromium", "NativeMessagingHosts")
6934
+ },
6935
+ {
6936
+ name: "Brave",
6937
+ userDataDir: path6.join(appSupport, "BraveSoftware", "Brave-Browser"),
6938
+ dir: path6.join(appSupport, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts")
6939
+ },
6940
+ {
6941
+ name: "Microsoft Edge",
6942
+ userDataDir: path6.join(appSupport, "Microsoft Edge"),
6943
+ dir: path6.join(appSupport, "Microsoft Edge", "NativeMessagingHosts")
6944
+ },
6945
+ {
6946
+ name: "Arc",
6947
+ userDataDir: path6.join(appSupport, "Arc", "User Data"),
6948
+ dir: path6.join(appSupport, "Arc", "User Data", "NativeMessagingHosts")
6949
+ }
6855
6950
  ];
6856
6951
  }
6857
6952
  if (platform === "linux") {
6858
6953
  const config = path6.join(home, ".config");
6859
6954
  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") }
6955
+ {
6956
+ name: "Google Chrome",
6957
+ userDataDir: path6.join(config, "google-chrome"),
6958
+ dir: path6.join(config, "google-chrome", "NativeMessagingHosts")
6959
+ },
6960
+ {
6961
+ name: "Chromium",
6962
+ userDataDir: path6.join(config, "chromium"),
6963
+ dir: path6.join(config, "chromium", "NativeMessagingHosts")
6964
+ },
6965
+ {
6966
+ name: "Brave",
6967
+ userDataDir: path6.join(config, "BraveSoftware", "Brave-Browser"),
6968
+ dir: path6.join(config, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts")
6969
+ },
6970
+ {
6971
+ name: "Microsoft Edge",
6972
+ userDataDir: path6.join(config, "microsoft-edge"),
6973
+ dir: path6.join(config, "microsoft-edge", "NativeMessagingHosts")
6974
+ }
6864
6975
  ];
6865
6976
  }
6866
6977
  return [];
6867
6978
  }
6979
+ function computeChromeExtensionId(unpackedDir) {
6980
+ const normalized = path6.resolve(unpackedDir);
6981
+ const hash = crypto3.createHash("sha256").update(normalized, "utf8").digest("hex").slice(0, 32);
6982
+ return hash.replace(/[0-9a-f]/g, (ch) => String.fromCharCode(97 + Number.parseInt(ch, 16)));
6983
+ }
6984
+ function getStableExtensionDir() {
6985
+ return path6.join(getBrowserPilotHomeDir(), "extension");
6986
+ }
6987
+ async function syncExtensionToHome(sourceExtDir, options = {}) {
6988
+ const destDir = getStableExtensionDir();
6989
+ let version = null;
6990
+ try {
6991
+ const manifestRaw = await fs5.readFile(path6.join(sourceExtDir, "manifest.json"), "utf8");
6992
+ const manifest = JSON.parse(manifestRaw);
6993
+ version = manifest.version ?? null;
6994
+ } catch {
6995
+ }
6996
+ let synced = false;
6997
+ if (!options.dryRun) {
6998
+ await ensureBrowserPilotHome();
6999
+ const resolvedSrc = await fs5.realpath(sourceExtDir).catch(() => path6.resolve(sourceExtDir));
7000
+ const resolvedDest = await fs5.realpath(destDir).catch(() => path6.resolve(destDir));
7001
+ if (resolvedSrc !== resolvedDest) {
7002
+ await fs5.rm(destDir, { recursive: true, force: true });
7003
+ await fs5.cp(sourceExtDir, destDir, { recursive: true });
7004
+ synced = true;
7005
+ }
7006
+ }
7007
+ const realDest = await fs5.realpath(destDir).catch(() => path6.resolve(destDir));
7008
+ return {
7009
+ extensionDir: realDest,
7010
+ extensionId: computeChromeExtensionId(realDest),
7011
+ version,
7012
+ synced
7013
+ };
7014
+ }
7015
+ async function discoverInstalledExtensionIds(platform = process.platform) {
7016
+ const found = [];
7017
+ const seen = /* @__PURE__ */ new Set();
7018
+ for (const target of getNativeMessagingHostDirs(platform)) {
7019
+ let entries;
7020
+ try {
7021
+ entries = await fs5.readdir(target.userDataDir);
7022
+ } catch {
7023
+ continue;
7024
+ }
7025
+ const profiles = entries.filter((e) => e === "Default" || e.startsWith("Profile "));
7026
+ for (const profile of profiles) {
7027
+ for (const fileName of ["Secure Preferences", "Preferences"]) {
7028
+ const prefPath = path6.join(target.userDataDir, profile, fileName);
7029
+ let parsed;
7030
+ try {
7031
+ parsed = JSON.parse(await fs5.readFile(prefPath, "utf8"));
7032
+ } catch {
7033
+ continue;
7034
+ }
7035
+ const settings = parsed.extensions?.settings;
7036
+ if (!settings || typeof settings !== "object") continue;
7037
+ for (const [extId, meta] of Object.entries(settings)) {
7038
+ if (!meta || !/^[a-p]{32}$/.test(extId)) continue;
7039
+ const manifestName = meta.manifest?.name || "";
7040
+ const extPath = meta.path || "";
7041
+ let isBrowserPilot = /^browserpilot$/i.test(manifestName) || /browserpilot/i.test(extPath);
7042
+ if (!isBrowserPilot && meta.location === 4 && extPath) {
7043
+ try {
7044
+ const m = JSON.parse(await fs5.readFile(path6.join(extPath, "manifest.json"), "utf8"));
7045
+ if (/^browserpilot$/i.test(m.name || "")) isBrowserPilot = true;
7046
+ } catch {
7047
+ }
7048
+ }
7049
+ if (isBrowserPilot && !seen.has(extId)) {
7050
+ seen.add(extId);
7051
+ found.push({ browser: target.name, profile, extensionId: extId, path: extPath || void 0 });
7052
+ }
7053
+ }
7054
+ }
7055
+ }
7056
+ }
7057
+ return found;
7058
+ }
7059
+ async function readInstalledNativeHosts(platform = process.platform) {
7060
+ const results = [];
7061
+ for (const target of getNativeMessagingHostDirs(platform)) {
7062
+ const mp = path6.join(target.dir, `${NATIVE_HOST_NAME}.json`);
7063
+ try {
7064
+ const parsed = JSON.parse(await fs5.readFile(mp, "utf8"));
7065
+ results.push({
7066
+ browser: target.name,
7067
+ installed: true,
7068
+ path: mp,
7069
+ allowedOrigins: Array.isArray(parsed.allowed_origins) ? parsed.allowed_origins : [],
7070
+ wrapperPath: parsed.path
7071
+ });
7072
+ } catch {
7073
+ results.push({ browser: target.name, installed: false, path: mp, allowedOrigins: [] });
7074
+ }
7075
+ }
7076
+ return results;
7077
+ }
6868
7078
  async function installNativeHost(options) {
6869
7079
  const nativeHostJs = path6.resolve(__dirname2, "native-host.js");
6870
7080
  const binDir = path6.join(getBrowserPilotHomeDir(), "bin");
6871
7081
  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}/`);
7082
+ const allowedOrigins = Array.from(
7083
+ new Set(
7084
+ options.extensionIds.map((id) => id.trim()).filter(Boolean).map((id) => id.startsWith("chrome-extension://") ? id.endsWith("/") ? id : `${id}/` : `chrome-extension://${id}/`)
7085
+ )
7086
+ );
6873
7087
  const manifestJson = {
6874
7088
  name: NATIVE_HOST_NAME,
6875
7089
  description: "BrowserPilot Zero-Click Browser Control & DevTools Bridge",
@@ -7009,34 +7223,69 @@ async function getExtensionDistPath() {
7009
7223
  return path7.resolve(__dirname3, "..", "..", "extension", "dist");
7010
7224
  }
7011
7225
  }
7226
+ async function findDynamicCachedChrome() {
7227
+ const found = [];
7228
+ const home = os5.homedir();
7229
+ const searchRoots = [
7230
+ path7.join(home, ".cache", "browserpilot-chrome", "chrome"),
7231
+ path7.join(home, "Library", "Caches", "ms-playwright"),
7232
+ path7.join(home, ".cache", "ms-playwright")
7233
+ ];
7234
+ for (const root of searchRoots) {
7235
+ let entries;
7236
+ try {
7237
+ entries = (await fs6.readdir(root)).sort().reverse();
7238
+ } catch {
7239
+ continue;
7240
+ }
7241
+ for (const entry of entries) {
7242
+ if (!entry.startsWith("chromium-") && !entry.startsWith("mac") && !entry.startsWith("linux")) continue;
7243
+ const candidates = [
7244
+ path7.join(root, entry, "chrome-mac-arm64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"),
7245
+ path7.join(root, entry, "chrome-mac-x64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"),
7246
+ path7.join(root, entry, "chrome-linux64", "chrome"),
7247
+ path7.join(root, entry, "chrome-linux", "chrome")
7248
+ ];
7249
+ for (const c of candidates) {
7250
+ try {
7251
+ await fs6.access(c);
7252
+ found.push(c);
7253
+ } catch {
7254
+ }
7255
+ }
7256
+ }
7257
+ }
7258
+ return found;
7259
+ }
7012
7260
  async function findChromeBinary() {
7013
- const candidates = [
7261
+ const staticCandidates = [
7014
7262
  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
7263
  "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
7264
+ "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
7020
7265
  "/Applications/Chromium.app/Contents/MacOS/Chromium",
7266
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
7021
7267
  "/usr/bin/google-chrome",
7022
- "/usr/bin/chromium"
7268
+ "/usr/bin/google-chrome-stable",
7269
+ "/usr/bin/chromium",
7270
+ "/usr/bin/chromium-browser"
7023
7271
  ].filter(Boolean);
7024
- for (const bin of candidates) {
7272
+ for (const bin of staticCandidates) {
7025
7273
  try {
7026
7274
  await fs6.access(bin);
7027
7275
  return bin;
7028
7276
  } catch {
7029
7277
  }
7030
7278
  }
7031
- return null;
7279
+ const cached = await findDynamicCachedChrome();
7280
+ return cached[0] ?? null;
7032
7281
  }
7033
7282
  function printHelp() {
7034
7283
  console.log(`BrowserPilot v${BROWSERPILOT_VERSION} \u2014 Zero-Click Pure-CDP Browser Control & DevTools CLI
7035
7284
 
7036
7285
  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
7286
+ browserpilot setup [--extension-id <id>] [--dry-run] Sync extension, auto-install Native Messaging & print MCP config
7287
+ browserpilot doctor [--json] Diagnose extension, Native Messaging, Chrome, ffmpeg & daemon
7288
+ browserpilot daemon start | stop | restart | status | run Manage local authenticated bridge daemon
7040
7289
  browserpilot mcp [--cdp <url>] Start MCP stdio server (for Claude/Cursor/Codex/Antigravity)
7041
7290
  browserpilot connect-cdp <url> Attach daemon directly to a --remote-debugging-port Chrome
7042
7291
  browserpilot browser start [--headless] [--cdp-port N] Launch Chrome/Chrome for Testing with BrowserPilot ready
@@ -7047,9 +7296,11 @@ Stateful Sessions (Playwriter replacement):
7047
7296
  browserpilot exec -s <id> -e '<js>' | -f <script.js> [--timeout <ms>]
7048
7297
 
7049
7298
  Direct Quick Commands:
7299
+ browserpilot status
7050
7300
  browserpilot tabs
7051
7301
  browserpilot open <url> [--tab-group <name>]
7052
7302
  browserpilot close <tabId>
7303
+ browserpilot navigate <url> [--tab <id>]
7053
7304
  browserpilot snapshot [--tab <id>] [--search <regex>] [--scope <css>] [--full]
7054
7305
  browserpilot click <ref|selector> [--tab <id>]
7055
7306
  browserpilot fill <ref|selector> <value> [--tab <id>]
@@ -7090,6 +7341,14 @@ async function main() {
7090
7341
  extBuilt = true;
7091
7342
  } catch {
7092
7343
  }
7344
+ const stableExtDir = getStableExtensionDir();
7345
+ let stableExtVersion = null;
7346
+ try {
7347
+ const m = JSON.parse(await fs6.readFile(path7.join(stableExtDir, "manifest.json"), "utf8"));
7348
+ stableExtVersion = m.version ?? null;
7349
+ } catch {
7350
+ }
7351
+ const expectedStableExtId = computeChromeExtensionId(await fs6.realpath(stableExtDir).catch(() => stableExtDir));
7093
7352
  const chromeBin = await findChromeBinary();
7094
7353
  let hasFfmpeg = false;
7095
7354
  for (const dir of (process.env.PATH || "").split(path7.delimiter)) {
@@ -7101,49 +7360,69 @@ async function main() {
7101
7360
  } catch {
7102
7361
  }
7103
7362
  }
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
- }
7363
+ const nativeHosts = await readInstalledNativeHosts();
7364
+ const discoveredExts = await discoverInstalledExtensionIds();
7115
7365
  const cfg = await readDaemonConfig();
7116
7366
  const daemonRunning = cfg ? await isDaemonReachable(cfg) : false;
7117
- let connectedClients = 0;
7367
+ let health = null;
7118
7368
  if (daemonRunning && cfg) {
7119
- const h = await new DaemonClient(cfg).health().catch(() => null);
7120
- connectedClients = h?.clients.length ?? 0;
7369
+ health = await new DaemonClient(cfg).health().catch(() => null);
7121
7370
  }
7371
+ const connectedClients = health?.clients ?? [];
7372
+ const versionMismatch = Boolean(health?.version && health.version !== BROWSERPILOT_VERSION);
7122
7373
  const report = {
7123
7374
  version: BROWSERPILOT_VERSION,
7124
7375
  node: process.version,
7125
7376
  extensionBuilt: extBuilt,
7126
7377
  extensionDistPath: extDist,
7378
+ stableExtensionDir: stableExtDir,
7379
+ stableExtensionVersion: stableExtVersion,
7380
+ expectedExtensionId: expectedStableExtId,
7381
+ discoveredChromeExtensions: discoveredExts,
7127
7382
  chromeBinary: chromeBin,
7128
7383
  ffmpegAvailable: hasFfmpeg,
7129
7384
  daemonConfigPresent: Boolean(cfg),
7130
7385
  daemonRunning,
7131
- connectedBrowsers: connectedClients,
7132
- nativeMessagingInstalled: nativeHosts.filter((n) => n.installed).map((n) => n.browser)
7386
+ daemonVersion: health?.version ?? null,
7387
+ daemonPid: health?.pid ?? cfg?.pid ?? null,
7388
+ daemonAddress: cfg ? `${cfg.host}:${cfg.port}` : null,
7389
+ daemonVersionMismatch: versionMismatch,
7390
+ connectedBrowsers: connectedClients.length,
7391
+ clients: connectedClients,
7392
+ nativeMessagingInstalled: nativeHosts.filter((n) => n.installed).map((n) => n.browser),
7393
+ nativeMessagingHosts: nativeHosts.filter((n) => n.installed)
7133
7394
  };
7134
7395
  if (flags.json) {
7135
7396
  console.log(JSON.stringify(report, null, 2));
7136
7397
  return;
7137
7398
  }
7138
7399
  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`);
7400
+ 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
7401
  console.log(`Node.js : ${report.node}`);
7141
7402
  console.log(`Extension dist/ : ${extBuilt ? "OK" : "MISSING (run pnpm build)"} (${extDist})`);
7403
+ console.log(
7404
+ `Stable ext copy : ${stableExtVersion ? `v${stableExtVersion} (${stableExtDir}, id: ${expectedStableExtId})` : `Not synced yet (run: browserpilot setup)`}`
7405
+ );
7406
+ console.log(
7407
+ `Chrome loaded : ${discoveredExts.length ? discoveredExts.map((e) => `${e.browser}/${e.profile} (${e.extensionId})`).join(", ") : "Not detected yet (load ~/.browserpilot/extension in chrome://extensions)"}`
7408
+ );
7142
7409
  console.log(`Chrome binary : ${chromeBin ?? "Not found (set BROWSERPILOT_CHROME_BIN)"}`);
7143
7410
  console.log(`ffmpeg : ${hasFfmpeg ? "OK (video recording ready)" : "Not found (optional for recording)"}`);
7144
- console.log(`Daemon status : ${daemonRunning ? `RUNNING (browsers: ${connectedClients})` : "STOPPED"}`);
7145
7411
  console.log(
7146
- `Native Messaging : ${report.nativeMessagingInstalled.length ? `Installed (${report.nativeMessagingInstalled.join(", ")})` : "Not installed (run: browserpilot setup --extension-id <id>)"}`
7412
+ `Daemon status : ${daemonRunning ? `RUNNING v${health?.version ?? "?"} @ ${cfg?.host}:${cfg?.port} (pid: ${health?.pid ?? cfg?.pid ?? "?"}, browsers: ${connectedClients.length})` : "STOPPED"}`
7413
+ );
7414
+ if (versionMismatch) {
7415
+ console.log(
7416
+ ` \u26A0 Version mismatch: CLI is v${BROWSERPILOT_VERSION}, running daemon is v${health?.version}. Run: browserpilot daemon restart`
7417
+ );
7418
+ }
7419
+ for (const c of connectedClients) {
7420
+ console.log(
7421
+ ` \u2022 ${c.browser} [${c.transport}]${c.extensionVersion ? ` ext v${c.extensionVersion}` : ""}${c.extensionId ? ` (${c.extensionId})` : ""} \u2014 attached tabs: ${c.attachedTabCount}`
7422
+ );
7423
+ }
7424
+ console.log(
7425
+ `Native Messaging : ${report.nativeMessagingInstalled.length ? `Installed (${report.nativeMessagingInstalled.join(", ")})` : "Not installed (run: browserpilot setup)"}`
7147
7426
  );
7148
7427
  return;
7149
7428
  }
@@ -7159,31 +7438,50 @@ async function main() {
7159
7438
  if (cmd === "setup") {
7160
7439
  const cfg = await loadOrCreateDaemonConfig();
7161
7440
  const extDist = await getExtensionDistPath();
7162
- const extId = typeof flags["extension-id"] === "string" ? flags["extension-id"] : "";
7441
+ const explicitExtId = typeof flags["extension-id"] === "string" ? flags["extension-id"] : "";
7163
7442
  const dryRun = Boolean(flags["dry-run"]);
7443
+ const skipNative = Boolean(flags["no-native-host"]);
7444
+ const synced = await syncExtensionToHome(extDist, { dryRun });
7445
+ const discovered = await discoverInstalledExtensionIds();
7446
+ const bundledReal = await fs6.realpath(extDist).catch(() => path7.resolve(extDist));
7447
+ const bundledExtId = computeChromeExtensionId(bundledReal);
7448
+ const allExtIds = Array.from(
7449
+ new Set(
7450
+ [
7451
+ synced.extensionId,
7452
+ bundledExtId,
7453
+ ...discovered.map((d) => d.extensionId),
7454
+ ...explicitExtId.split(",").map((s) => s.trim())
7455
+ ].filter(Boolean)
7456
+ )
7457
+ );
7164
7458
  console.log(`
7165
7459
  BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
7166
7460
  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.`);
7461
+ console.log(`1. Stable Unpacked Extension Path (upgrade-safe):`);
7462
+ console.log(` ${synced.extensionDir}`);
7463
+ console.log(` Expected Chrome Extension ID : ${synced.extensionId}`);
7464
+ if (discovered.length > 0) {
7465
+ console.log(
7466
+ ` Already detected in Chrome : ${discovered.map((d) => `${d.browser}/${d.profile} (${d.extensionId})`).join(", ")}`
7467
+ );
7468
+ } else {
7469
+ console.log(` -> Open chrome://extensions -> Enable "Developer mode" -> "Load unpacked" -> select the path above.`);
7470
+ }
7170
7471
  console.log(`
7171
7472
  2. Local Daemon Config (~/.browserpilot/daemon.json):`);
7172
7473
  console.log(` WebSocket URL : ws://${cfg.host}:${cfg.port}/extension`);
7173
7474
  console.log(` Auth Token : ${cfg.token}`);
7174
- if (extId) {
7175
- const res = await installNativeHost({ extensionIds: [extId], dryRun });
7475
+ if (!skipNative) {
7476
+ const res = await installNativeHost({ extensionIds: allExtIds, dryRun });
7176
7477
  console.log(`
7177
- 3. Chrome Native Messaging Host (${dryRun ? "dry-run" : "installed"}):`);
7178
- console.log(` Wrapper: ${res.wrapperPath}`);
7478
+ 3. Chrome Native Messaging Host (${dryRun ? "dry-run" : "installed automatically"}):`);
7479
+ console.log(` Wrapper : ${res.wrapperPath}`);
7480
+ console.log(` Allowed : ${allExtIds.join(", ")}`);
7179
7481
  for (const m of res.installedManifests) {
7180
7482
  console.log(` - ${m.browser}: ${m.manifestPath}`);
7181
7483
  }
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>`);
7484
+ console.log(` -> Zero manual token entry or --extension-id needed! Extension connects automatically once loaded.`);
7187
7485
  }
7188
7486
  const cliBin = path7.resolve(__dirname3, "cli.js");
7189
7487
  console.log(`
@@ -7224,7 +7522,7 @@ BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
7224
7522
  if (sub === "start") {
7225
7523
  const client2 = await DaemonClient.connectOrStart();
7226
7524
  const h = await client2.health();
7227
- console.log(`BrowserPilot daemon running on http://${client2.config.host}:${client2.config.port} (clients: ${h.clients.length})`);
7525
+ console.log(`BrowserPilot daemon v${h.version} running on http://${client2.config.host}:${client2.config.port} (clients: ${h.clients.length})`);
7228
7526
  return;
7229
7527
  }
7230
7528
  if (sub === "stop") {
@@ -7237,6 +7535,20 @@ BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
7237
7535
  console.log("BrowserPilot daemon stopped.");
7238
7536
  return;
7239
7537
  }
7538
+ if (sub === "restart") {
7539
+ const cfg = await readDaemonConfig();
7540
+ if (cfg && await isDaemonReachable(cfg)) {
7541
+ await new DaemonClient(cfg).shutdown();
7542
+ for (let i = 0; i < 20; i++) {
7543
+ await new Promise((r) => setTimeout(r, 100));
7544
+ if (!await isDaemonReachable(cfg)) break;
7545
+ }
7546
+ }
7547
+ const client2 = await DaemonClient.connectOrStart();
7548
+ const h = await client2.health();
7549
+ console.log(`BrowserPilot daemon restarted (v${h.version}) on http://${client2.config.host}:${client2.config.port} (clients: ${h.clients.length})`);
7550
+ return;
7551
+ }
7240
7552
  if (sub === "status") {
7241
7553
  const cfg = await readDaemonConfig();
7242
7554
  if (!cfg || !await isDaemonReachable(cfg)) {
@@ -7343,6 +7655,9 @@ BrowserPilot Setup (v${BROWSERPILOT_VERSION})`);
7343
7655
  return;
7344
7656
  }
7345
7657
  switch (cmd) {
7658
+ case "status":
7659
+ printToolOutput(await client.callTool("browser_status"));
7660
+ return;
7346
7661
  case "tabs":
7347
7662
  printToolOutput(await client.callTool("browser_tabs"));
7348
7663
  return;