browserpilot-cdp 1.2.2 → 1.2.4

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,11 +5,12 @@ 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.2";
8
+ var BROWSERPILOT_VERSION = "1.2.4";
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";
12
12
  var NATIVE_MESSAGE_MAX_BYTES = 1024 * 1024;
13
+ var NATIVE_INCOMING_MAX_BYTES = 64 * 1024 * 1024;
13
14
  var DEFAULT_CDP_TIMEOUT_MS = 15e3;
14
15
  var MAX_CONSOLE_BUFFER = 5e3;
15
16
  var MAX_NETWORK_BUFFER = 2e3;
@@ -771,7 +772,13 @@ var IGNORED_ANALYTICS_PATTERNS = [
771
772
  /posthog\.com/i,
772
773
  /datadoghq\.com/i,
773
774
  /hm\.baidu\.com/i,
774
- /\/collect\b|\/analytics\b|\/telemetry\b|\/beacon\b/i
775
+ /\/collect\b|\/analytics\b|\/telemetry\b|\/beacon\b/i,
776
+ // Long-polling & real-time push endpoints (Discourse message-bus, Socket.IO, SignalR, SSE)
777
+ /\/message-bus\//i,
778
+ /\/(long-?poll|polling|heartbeat|keepalive)\b/i,
779
+ /socket\.io/i,
780
+ /[?&]EIO=\d/i,
781
+ /\/signalr\//i
775
782
  ];
776
783
  function isIgnoredAnalyticsUrl(url) {
777
784
  return IGNORED_ANALYTICS_PATTERNS.some((re) => re.test(url));
@@ -791,7 +798,7 @@ async function waitForPageLoad(session, options = {}) {
791
798
  return;
792
799
  if (isIgnoredAnalyticsUrl(url))
793
800
  return;
794
- inflight.set(id, url);
801
+ inflight.set(id, { url, startedAt: Date.now() });
795
802
  });
796
803
  const offFin = session.on("Network.loadingFinished", (params) => {
797
804
  inflight.delete(String(params.requestId ?? ""));
@@ -799,6 +806,16 @@ async function waitForPageLoad(session, options = {}) {
799
806
  const offFail = session.on("Network.loadingFailed", (params) => {
800
807
  inflight.delete(String(params.requestId ?? ""));
801
808
  });
809
+ const countActiveInflight = (now, docComplete) => {
810
+ if (!docComplete)
811
+ return inflight.size;
812
+ let active = 0;
813
+ for (const item of inflight.values()) {
814
+ if (now - item.startedAt < 2500)
815
+ active++;
816
+ }
817
+ return active;
818
+ };
802
819
  let readyState = "loading";
803
820
  let idleSince = null;
804
821
  try {
@@ -817,17 +834,19 @@ async function waitForPageLoad(session, options = {}) {
817
834
  } catch {
818
835
  readyState = "loading";
819
836
  }
837
+ const now = Date.now();
820
838
  const stillOnBlank = Boolean(options.ignoreAboutBlank) && (!href || href === "about:blank");
821
- if (!stillOnBlank && (readyState === "complete" || readyState === "interactive") && inflight.size === 0) {
839
+ const activePending = countActiveInflight(now, readyState === "complete");
840
+ if (!stillOnBlank && (readyState === "complete" || readyState === "interactive") && activePending === 0) {
822
841
  if (idleSince === null)
823
- idleSince = Date.now();
824
- if (Date.now() - idleSince >= idleMs || readyState === "complete") {
825
- if (Date.now() - idleSince >= Math.min(idleMs, 150)) {
842
+ idleSince = now;
843
+ if (now - idleSince >= idleMs || readyState === "complete") {
844
+ if (now - idleSince >= Math.min(idleMs, 150)) {
826
845
  return {
827
846
  success: true,
828
847
  readyState,
829
848
  pendingRequests: 0,
830
- waitTimeMs: Date.now() - start,
849
+ waitTimeMs: now - start,
831
850
  timedOut: false
832
851
  };
833
852
  }
@@ -970,14 +989,35 @@ var LANDMARK_AND_STRUCTURE_ROLES = /* @__PURE__ */ new Set([
970
989
  "iframe"
971
990
  ]);
972
991
  var SKIPPED_ROLES = /* @__PURE__ */ new Set(["InlineTextBox", "LineBreak", "LayoutTable", "LayoutTableRow", "LayoutTableCell"]);
992
+ var LEAF_LABELED_ROLES = /* @__PURE__ */ new Set([
993
+ "link",
994
+ "button",
995
+ "heading",
996
+ "tab",
997
+ "menuitem",
998
+ "menuitemcheckbox",
999
+ "menuitemradio",
1000
+ "option",
1001
+ "checkbox",
1002
+ "radio",
1003
+ "switch",
1004
+ "textbox",
1005
+ "searchbox",
1006
+ "combobox"
1007
+ ]);
973
1008
  function getProp(node, name) {
974
1009
  const prop = node.properties?.find((p) => p.name === name);
975
1010
  return prop?.value?.value;
976
1011
  }
977
- function cleanText(raw, maxLen = 140) {
1012
+ function normalizeWs(raw) {
978
1013
  if (raw === void 0 || raw === null)
979
1014
  return "";
980
- const s = String(raw).replace(/\s+/g, " ").trim();
1015
+ return String(raw).replace(/\s+/g, " ").trim();
1016
+ }
1017
+ function cleanText(raw, maxLen = 140) {
1018
+ const s = normalizeWs(raw);
1019
+ if (!s)
1020
+ return "";
981
1021
  if (s.length <= maxLen)
982
1022
  return s;
983
1023
  return `${s.slice(0, maxLen - 1)}\u2026`;
@@ -1003,7 +1043,7 @@ function formatAXTree(nodes, options = {}) {
1003
1043
  }
1004
1044
  }
1005
1045
  const visited = /* @__PURE__ */ new Set();
1006
- function renderNode(node, depth, parentName) {
1046
+ function renderNode(node, depth, parentName, parentLeafText) {
1007
1047
  if (depth > maxDepth || visited.has(node.nodeId))
1008
1048
  return;
1009
1049
  visited.add(node.nodeId);
@@ -1013,27 +1053,30 @@ function formatAXTree(nodes, options = {}) {
1013
1053
  const children = (node.childIds ?? []).map((id) => nodeMap.get(id)).filter((c) => Boolean(c));
1014
1054
  if (node.ignored) {
1015
1055
  for (const child of children)
1016
- renderNode(child, depth, parentName);
1056
+ renderNode(child, depth, parentName, parentLeafText);
1017
1057
  return;
1018
1058
  }
1019
- const name = cleanText(node.name?.value);
1059
+ const fullRawName = normalizeWs(node.name?.value);
1060
+ const name = cleanText(fullRawName);
1020
1061
  const value = cleanText(node.value?.value, 100);
1021
1062
  const isInteractive = INTERACTIVE_ROLES.has(role) || getProp(node, "focusable") === true;
1022
1063
  if (role === "RootWebArea" || role === "WebArea") {
1023
1064
  for (const child of children)
1024
- renderNode(child, depth, name);
1065
+ renderNode(child, depth, name, "");
1025
1066
  return;
1026
1067
  }
1027
1068
  if (role === "StaticText") {
1028
- if (includeText && name && name !== parentName) {
1029
- lines.push(`${" ".repeat(depth)}- text: "${name}"`);
1030
- }
1069
+ if (!includeText || !name || name === parentName)
1070
+ return;
1071
+ if (parentLeafText && parentLeafText.includes(fullRawName))
1072
+ return;
1073
+ lines.push(`${" ".repeat(depth)}- text: "${name}"`);
1031
1074
  return;
1032
1075
  }
1033
1076
  const isMeaningful = isInteractive || LANDMARK_AND_STRUCTURE_ROLES.has(role);
1034
1077
  if (!isMeaningful) {
1035
1078
  for (const child of children)
1036
- renderNode(child, depth, parentName);
1079
+ renderNode(child, depth, parentName, parentLeafText);
1037
1080
  return;
1038
1081
  }
1039
1082
  const lineStartIndex = lines.length;
@@ -1083,21 +1126,31 @@ function formatAXTree(nodes, options = {}) {
1083
1126
  const namePart = name ? ` "${name}"` : "";
1084
1127
  const attrPart = attrs.length > 0 ? ` (${attrs.join(", ")})` : "";
1085
1128
  lines.push(`${indent}- ${refPrefix}${role}${namePart}${attrPart}`);
1129
+ const nextLeafText = fullRawName && LEAF_LABELED_ROLES.has(role) ? fullRawName : parentLeafText;
1086
1130
  for (const child of children) {
1087
- renderNode(child, depth + 1, name || parentName);
1131
+ renderNode(child, depth + 1, name || parentName, nextLeafText);
1088
1132
  }
1089
1133
  if (!isInteractive && !name && attrs.length === 0 && lines.length === lineStartIndex + 1) {
1090
1134
  lines.pop();
1091
1135
  }
1092
1136
  }
1093
- renderNode(rootNode, 0, "");
1137
+ renderNode(rootNode, 0, "", "");
1094
1138
  return { lines, refs, nextRefIndex: refCounter };
1095
1139
  }
1096
- function filterSnapshotLines(fullText, search, maxMatches = 25) {
1140
+ function filterSnapshotLines(fullText, search, maxMatches = 40) {
1097
1141
  const allLines = fullText.split("\n");
1098
1142
  const header = allLines[0]?.startsWith("URL:") ? allLines[0] : "";
1099
1143
  const body = header ? allLines.slice(1) : allLines;
1100
- const regex = search instanceof RegExp ? search : new RegExp(escapeRegex(search), "i");
1144
+ let regex;
1145
+ if (search instanceof RegExp) {
1146
+ regex = search;
1147
+ } else {
1148
+ try {
1149
+ regex = new RegExp(search, "i");
1150
+ } catch {
1151
+ regex = new RegExp(escapeRegex(search), "i");
1152
+ }
1153
+ }
1101
1154
  const matchedIndices = /* @__PURE__ */ new Set();
1102
1155
  let count = 0;
1103
1156
  for (let i = 0; i < body.length; i++) {
@@ -2669,7 +2722,16 @@ var ConsoleCollector = class {
2669
2722
  }
2670
2723
  }
2671
2724
  if (options.search !== void 0) {
2672
- const regex = options.search instanceof RegExp ? options.search : new RegExp(options.search.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
2725
+ let regex;
2726
+ if (options.search instanceof RegExp) {
2727
+ regex = options.search;
2728
+ } else {
2729
+ try {
2730
+ regex = new RegExp(options.search, "i");
2731
+ } catch {
2732
+ regex = new RegExp(options.search.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
2733
+ }
2734
+ }
2673
2735
  list = list.filter((e) => regex.test(e.text) || e.url && regex.test(e.url) || e.stackTrace && regex.test(e.stackTrace));
2674
2736
  }
2675
2737
  this.cursors.set(cursorKey, this.getLatestId());
@@ -2860,7 +2922,16 @@ var NetworkInspector = class {
2860
2922
  list = list.filter((e) => e.resourceType?.toLowerCase() === rt);
2861
2923
  }
2862
2924
  if (options.search !== void 0) {
2863
- const regex = options.search instanceof RegExp ? options.search : new RegExp(options.search.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
2925
+ let regex;
2926
+ if (options.search instanceof RegExp) {
2927
+ regex = options.search;
2928
+ } else {
2929
+ try {
2930
+ regex = new RegExp(options.search, "i");
2931
+ } catch {
2932
+ regex = new RegExp(options.search.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
2933
+ }
2934
+ }
2864
2935
  list = list.filter((e) => regex.test(e.url) || e.errorText && regex.test(e.errorText));
2865
2936
  }
2866
2937
  const latestTs = this.entries[this.entries.length - 1]?.timestamp ?? Date.now();
@@ -3089,7 +3160,8 @@ function formatStylesAsText(styles) {
3089
3160
  if (styles.inlineStyles.length) {
3090
3161
  lines.push(" element.style {");
3091
3162
  for (const d of styles.inlineStyles) {
3092
- lines.push(` ${d.name}: ${d.value}${d.important ? " !important" : ""};`);
3163
+ const imp = d.important && !/!important\s*$/i.test(d.value) ? " !important" : "";
3164
+ lines.push(` ${d.name}: ${d.value}${imp};`);
3093
3165
  }
3094
3166
  lines.push(" }");
3095
3167
  }
@@ -3098,7 +3170,8 @@ function formatStylesAsText(styles) {
3098
3170
  lines.push(` ${r.selector} {${loc}`);
3099
3171
  for (const d of r.declarations) {
3100
3172
  const strike = d.overridden ? " /* overridden */" : "";
3101
- lines.push(` ${d.name}: ${d.value}${d.important ? " !important" : ""};${strike}`);
3173
+ const imp = d.important && !/!important\s*$/i.test(d.value) ? " !important" : "";
3174
+ lines.push(` ${d.name}: ${d.value}${imp};${strike}`);
3102
3175
  }
3103
3176
  lines.push(" }");
3104
3177
  }
@@ -7130,42 +7203,56 @@ exec ${JSON.stringify(process.execPath)} ${JSON.stringify(nativeHostJs)} "$@"
7130
7203
  }
7131
7204
 
7132
7205
  // src/skill-doc.ts
7133
- var BROWSERPILOT_SKILL_DOC = `# BrowserPilot \u2014 Zero-Click Pure-CDP Browser Control & DevTools Guide
7206
+ var BROWSERPILOT_SKILL_DOC = `# BrowserPilot \u2014 Real Chrome Automation & DevTools Guide
7207
+
7208
+ BrowserPilot controls the user's running Chrome browser (existing logins, cookies, tabs) or a Direct CDP Chromium instance via pure CDP with zero per-tab confirmation clicks.
7209
+
7210
+ ## 1. Choose Mode (MCP vs CLI)
7211
+ - If \`browser_*\` MCP tools are available in this session, prefer calling them directly (screenshots return inline image blocks automatically).
7212
+ - Otherwise use the \`browserpilot\` CLI in the shell.
7213
+ - If a command reports no browser connected, run \`browserpilot doctor\` to diagnose and report clearly.
7214
+
7215
+ ## 2. Core Workflow
7216
+ 1. **Tabs**: \`browser_tabs\` / \`browserpilot tabs\`, or \`browser_open_tab\` / \`browserpilot open <url> --tab-group <name>\`. Always pass \`--tab <id>\` (\`tabId\`) when multiple tabs are open.
7217
+ 2. **Perceive**:
7218
+ - \`browser_snapshot\` / \`browserpilot snapshot --tab <id> [--search "<regex>"] [--scope "<css>"] [--full]\`
7219
+ - First call returns full AXTree with \`e1\`, \`e2\`... refs + viewport/scroll info; subsequent calls return diffs (pass \`--full\` / \`showDiffSinceLastCall: false\` for full output).
7220
+ - Use \`browser_labeled_screenshot\` / \`browserpilot labeled-screenshot <path>\` when spatial layout or icon-only buttons matter.
7221
+ 3. **Act (trusted CDP input)**:
7222
+ - \`click\`, \`fill\`, \`type\`, \`press_key\`, \`hover\`, \`scroll\`, \`drag\`, \`select_option\`, \`upload_file\`, \`batch\`.
7223
+ - Targets accept refs (\`e5\`), CSS selectors (\`#submit\`), \`role=button[name="Save"]\`, \`label=...\`, \`placeholder=...\`, \`text=...\`, \`>> nth=N\`, or \`pinned\`.
7224
+ 4. **DevTools Debugging**:
7225
+ - \`browser_console\` / \`browserpilot console --level error --since-last\`
7226
+ - \`browser_network\` / \`browserpilot network --failed\` (pass \`requestId\` for headers, timing, initiator stack, body)
7227
+ - \`browser_network_intercept\` \u2014 mock/block API responses via CDP \`Fetch\`
7228
+ - \`browser_styles\` / \`browserpilot styles <target>\` \u2014 clean author CSS rules with \`file:line\` + forced \`:hover\`/\`:focus\`
7229
+ - \`browser_react_info\` / \`browserpilot react <target>\` \u2014 React Fiber component, source \`file:line\`, props
7230
+ - \`browser_debugger\` / \`browser_live_edit\` \u2014 breakpoints, call frames, live JS/CSS patching
7231
+ - \`browser_performance\` / \`browserpilot perf metrics\` \u2014 Web Vitals (LCP/CLS/FCP/TTFB), heap, CPU/trace
7232
+ - \`browser_downloads\`, \`browser_action_recorder\`, \`browser_record\` (MP4/WebM + smart idle speedup)
7134
7233
 
7135
- BrowserPilot controls your real logged-in Chrome browser (existing cookies, logins, extensions) via pure CDP with **zero manual confirmation clicks**.
7234
+ ## 3. Stateful JS Sandbox (\`browserpilot exec\`)
7235
+ > Important: BrowserPilot is **pure CDP, NOT Playwright** \u2014 do NOT call \`page.locator(...)\`. Use \`t.page.*\` and built-in helpers.
7136
7236
 
7137
- ## Core Workflow (Fast & Token-Efficient)
7237
+ \`\`\`bash
7238
+ SID=$(browserpilot session new --tab-group work)
7239
+ browserpilot exec -s "$SID" -e '
7240
+ const t = await tabs.open("http://localhost:3000");
7241
+ state.tab = t;
7242
+ await waitForSelector("#email", { tab: t });
7243
+ await t.page.fill("#email", "alice@example.com");
7244
+ await t.page.click("role=button[name=\\"Sign in\\"]");
7245
+ console.log(await snapshot({ tab: t }));
7246
+ '
7247
+ \`\`\`
7138
7248
 
7139
- 1. **Discover tabs**: \`browser_tabs\` (or \`browserpilot tabs\`) \u2014 lists all tabs with \`tabId\`, URL, and title.
7140
- 2. **Navigate or pick existing tab**: \`browser_open_tab\` / \`browser_select_tab\` / \`browser_navigate\`. BrowserPilot auto-attaches \`chrome.debugger\` on demand with zero clicks.
7141
- 3. **Perceive the page**:
7142
- - Prefer \`browser_snapshot\` (compact AXTree with \`e1\`, \`e2\`... refs + automatic incremental diffs).
7143
- - Use \`scope\` (CSS selector/ref) or \`search\` on large pages to save tokens.
7144
- - Use \`browser_labeled_screenshot\` (Set-of-Mark overlays) when visual layout matters.
7145
- 4. **Interact with trusted CDP input**:
7146
- - \`browser_click\`, \`browser_fill\`, \`browser_type\`, \`browser_press_key\`, \`browser_select_option\`, \`browser_drag\`, \`browser_upload_file\`.
7147
- - Every action automatically reports newly thrown Console errors and failed Network requests.
7148
- 5. **Debug like Chrome DevTools**:
7149
- - \`browser_console\` (\`sinceLastCall: true\`) \u2014 logs, warnings, uncaught exceptions with stacks.
7150
- - \`browser_network\` (\`failedOnly: true\`, or pass \`requestId\` for headers, timing, JS initiator stack, and response body).
7151
- - \`browser_network_intercept\` \u2014 mock/block API responses via CDP \`Fetch\`.
7152
- - \`browser_styles\` \u2014 matched/inherited CSS rules with \`file:line\` + forced \`:hover\`/\`:focus\`.
7153
- - \`browser_react_info\` \u2014 React Fiber component name, dev source \`file:line\`, hierarchy, props.
7154
- - \`browser_debugger\` \u2014 breakpoints, pause/step, local scope variables, evaluate in call frame.
7155
- - \`browser_live_edit\` \u2014 grep loaded scripts and live-patch JS/CSS in memory.
7156
- - \`browser_performance\` \u2014 Core Web Vitals (LCP/CLS/FCP/TTFB), heap summary, CPU profiler, Tracing insights.
7157
- - \`browser_emulate\` \u2014 viewport, mobile, dark mode, CPU throttling, Slow 3G / offline.
7158
- - \`browser_downloads\` \u2014 configure download folder, list downloads, or wait for a file download to complete with its local path.
7159
- - \`browser_action_recorder\` \u2014 record user clicks/fills/selects/navigations into reusable batch steps, exec JS script, and Agent Skill Markdown.
7160
- - \`browser_record\` \u2014 record MP4/WebM screencast video via \`ffmpeg\` (optional \`audio: true\`) and create smart idle-sped-up demo videos.
7161
- 6. **Multi-step Stateful Sandbox (Playwriter replacement)**:
7162
- - \`browserpilot session new --tab-group docs\` -> returns session ID (e.g. \`1\`)
7163
- - \`browserpilot exec -s 1 -e 'const t = await tabs.open("https://example.com"); console.log(await snapshot({ tab: t }))'\`
7164
- - Available sandbox globals: \`state\`, \`tabs\`, \`snapshot\`, \`screenshot\`, \`screenshotWithLabels\`, \`cleanHTML\`, \`markdown\`, \`inspect\`, \`getLatestLogs\`, \`getNetwork\`, \`getStyles\`, \`getReactInfo\`, \`waitForPageLoad\`, \`waitForSelector\`, \`waitForText\`, \`cdp\`, \`createDemoVideo\`.
7249
+ Globals: \`state\`, \`tabs\` (\`list\`, \`open\`, \`use\`, \`current\`, \`close\`), \`snapshot\`, \`screenshot\`, \`screenshotWithLabels\`, \`cleanHTML\`, \`markdown\`, \`inspect\`, \`getLatestLogs\`, \`getNetwork\`, \`getStyles\`, \`getReactInfo\`, \`waitForPageLoad\`, \`waitForSelector\`, \`waitForText\`, \`downloads\`, \`actionRecorder\`, \`cdp\`, \`sleep\`, \`createDemoVideo\`.
7165
7250
 
7166
- ## Safety Rules
7167
- - Never wipe profile-wide cookies/cache (BrowserPilot blocks \`Network.clearBrowserCookies\` / \`Network.clearBrowserCache\` automatically; use page-scoped \`browser_cookies\`).
7168
- - Confirm with the user before irreversible actions (payments, deletions, account/security changes, sending public posts).
7251
+ ## 4. Safety & Pitfalls
7252
+ - Confirm with the user before irreversible actions (payments, deletions, account/security changes, public posts).
7253
+ - Never bypass CAPTCHAs, Cloudflare Turnstile, or 2FA/Passkey prompts \u2014 stop and let the user complete them in Chrome.
7254
+ - If \`Another debugger is already attached\` appears, ask the user to close DevTools / detach the other extension on that tab, or open a new tab with \`browserpilot open\`.
7255
+ - Never wipe profile-wide cookies/cache (blocked automatically; use page-scoped \`browser_cookies\`).
7169
7256
  `;
7170
7257
  export {
7171
7258
  BROWSERPILOT_SKILL_DOC,