browserpilot-cdp 1.2.3 → 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,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.3";
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";
@@ -772,7 +772,13 @@ var IGNORED_ANALYTICS_PATTERNS = [
772
772
  /posthog\.com/i,
773
773
  /datadoghq\.com/i,
774
774
  /hm\.baidu\.com/i,
775
- /\/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
776
782
  ];
777
783
  function isIgnoredAnalyticsUrl(url) {
778
784
  return IGNORED_ANALYTICS_PATTERNS.some((re) => re.test(url));
@@ -792,7 +798,7 @@ async function waitForPageLoad(session, options = {}) {
792
798
  return;
793
799
  if (isIgnoredAnalyticsUrl(url))
794
800
  return;
795
- inflight.set(id, url);
801
+ inflight.set(id, { url, startedAt: Date.now() });
796
802
  });
797
803
  const offFin = session.on("Network.loadingFinished", (params) => {
798
804
  inflight.delete(String(params.requestId ?? ""));
@@ -800,6 +806,16 @@ async function waitForPageLoad(session, options = {}) {
800
806
  const offFail = session.on("Network.loadingFailed", (params) => {
801
807
  inflight.delete(String(params.requestId ?? ""));
802
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
+ };
803
819
  let readyState = "loading";
804
820
  let idleSince = null;
805
821
  try {
@@ -818,17 +834,19 @@ async function waitForPageLoad(session, options = {}) {
818
834
  } catch {
819
835
  readyState = "loading";
820
836
  }
837
+ const now = Date.now();
821
838
  const stillOnBlank = Boolean(options.ignoreAboutBlank) && (!href || href === "about:blank");
822
- 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) {
823
841
  if (idleSince === null)
824
- idleSince = Date.now();
825
- if (Date.now() - idleSince >= idleMs || readyState === "complete") {
826
- 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)) {
827
845
  return {
828
846
  success: true,
829
847
  readyState,
830
848
  pendingRequests: 0,
831
- waitTimeMs: Date.now() - start,
849
+ waitTimeMs: now - start,
832
850
  timedOut: false
833
851
  };
834
852
  }
@@ -971,14 +989,35 @@ var LANDMARK_AND_STRUCTURE_ROLES = /* @__PURE__ */ new Set([
971
989
  "iframe"
972
990
  ]);
973
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
+ ]);
974
1008
  function getProp(node, name) {
975
1009
  const prop = node.properties?.find((p) => p.name === name);
976
1010
  return prop?.value?.value;
977
1011
  }
978
- function cleanText(raw, maxLen = 140) {
1012
+ function normalizeWs(raw) {
979
1013
  if (raw === void 0 || raw === null)
980
1014
  return "";
981
- 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 "";
982
1021
  if (s.length <= maxLen)
983
1022
  return s;
984
1023
  return `${s.slice(0, maxLen - 1)}\u2026`;
@@ -1004,7 +1043,7 @@ function formatAXTree(nodes, options = {}) {
1004
1043
  }
1005
1044
  }
1006
1045
  const visited = /* @__PURE__ */ new Set();
1007
- function renderNode(node, depth, parentName) {
1046
+ function renderNode(node, depth, parentName, parentLeafText) {
1008
1047
  if (depth > maxDepth || visited.has(node.nodeId))
1009
1048
  return;
1010
1049
  visited.add(node.nodeId);
@@ -1014,27 +1053,30 @@ function formatAXTree(nodes, options = {}) {
1014
1053
  const children = (node.childIds ?? []).map((id) => nodeMap.get(id)).filter((c) => Boolean(c));
1015
1054
  if (node.ignored) {
1016
1055
  for (const child of children)
1017
- renderNode(child, depth, parentName);
1056
+ renderNode(child, depth, parentName, parentLeafText);
1018
1057
  return;
1019
1058
  }
1020
- const name = cleanText(node.name?.value);
1059
+ const fullRawName = normalizeWs(node.name?.value);
1060
+ const name = cleanText(fullRawName);
1021
1061
  const value = cleanText(node.value?.value, 100);
1022
1062
  const isInteractive = INTERACTIVE_ROLES.has(role) || getProp(node, "focusable") === true;
1023
1063
  if (role === "RootWebArea" || role === "WebArea") {
1024
1064
  for (const child of children)
1025
- renderNode(child, depth, name);
1065
+ renderNode(child, depth, name, "");
1026
1066
  return;
1027
1067
  }
1028
1068
  if (role === "StaticText") {
1029
- if (includeText && name && name !== parentName) {
1030
- lines.push(`${" ".repeat(depth)}- text: "${name}"`);
1031
- }
1069
+ if (!includeText || !name || name === parentName)
1070
+ return;
1071
+ if (parentLeafText && parentLeafText.includes(fullRawName))
1072
+ return;
1073
+ lines.push(`${" ".repeat(depth)}- text: "${name}"`);
1032
1074
  return;
1033
1075
  }
1034
1076
  const isMeaningful = isInteractive || LANDMARK_AND_STRUCTURE_ROLES.has(role);
1035
1077
  if (!isMeaningful) {
1036
1078
  for (const child of children)
1037
- renderNode(child, depth, parentName);
1079
+ renderNode(child, depth, parentName, parentLeafText);
1038
1080
  return;
1039
1081
  }
1040
1082
  const lineStartIndex = lines.length;
@@ -1084,17 +1126,18 @@ function formatAXTree(nodes, options = {}) {
1084
1126
  const namePart = name ? ` "${name}"` : "";
1085
1127
  const attrPart = attrs.length > 0 ? ` (${attrs.join(", ")})` : "";
1086
1128
  lines.push(`${indent}- ${refPrefix}${role}${namePart}${attrPart}`);
1129
+ const nextLeafText = fullRawName && LEAF_LABELED_ROLES.has(role) ? fullRawName : parentLeafText;
1087
1130
  for (const child of children) {
1088
- renderNode(child, depth + 1, name || parentName);
1131
+ renderNode(child, depth + 1, name || parentName, nextLeafText);
1089
1132
  }
1090
1133
  if (!isInteractive && !name && attrs.length === 0 && lines.length === lineStartIndex + 1) {
1091
1134
  lines.pop();
1092
1135
  }
1093
1136
  }
1094
- renderNode(rootNode, 0, "");
1137
+ renderNode(rootNode, 0, "", "");
1095
1138
  return { lines, refs, nextRefIndex: refCounter };
1096
1139
  }
1097
- function filterSnapshotLines(fullText, search, maxMatches = 25) {
1140
+ function filterSnapshotLines(fullText, search, maxMatches = 40) {
1098
1141
  const allLines = fullText.split("\n");
1099
1142
  const header = allLines[0]?.startsWith("URL:") ? allLines[0] : "";
1100
1143
  const body = header ? allLines.slice(1) : allLines;
@@ -2679,7 +2722,16 @@ var ConsoleCollector = class {
2679
2722
  }
2680
2723
  }
2681
2724
  if (options.search !== void 0) {
2682
- 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
+ }
2683
2735
  list = list.filter((e) => regex.test(e.text) || e.url && regex.test(e.url) || e.stackTrace && regex.test(e.stackTrace));
2684
2736
  }
2685
2737
  this.cursors.set(cursorKey, this.getLatestId());
@@ -2870,7 +2922,16 @@ var NetworkInspector = class {
2870
2922
  list = list.filter((e) => e.resourceType?.toLowerCase() === rt);
2871
2923
  }
2872
2924
  if (options.search !== void 0) {
2873
- 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
+ }
2874
2935
  list = list.filter((e) => regex.test(e.url) || e.errorText && regex.test(e.errorText));
2875
2936
  }
2876
2937
  const latestTs = this.entries[this.entries.length - 1]?.timestamp ?? Date.now();
@@ -3099,7 +3160,8 @@ function formatStylesAsText(styles) {
3099
3160
  if (styles.inlineStyles.length) {
3100
3161
  lines.push(" element.style {");
3101
3162
  for (const d of styles.inlineStyles) {
3102
- 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};`);
3103
3165
  }
3104
3166
  lines.push(" }");
3105
3167
  }
@@ -3108,7 +3170,8 @@ function formatStylesAsText(styles) {
3108
3170
  lines.push(` ${r.selector} {${loc}`);
3109
3171
  for (const d of r.declarations) {
3110
3172
  const strike = d.overridden ? " /* overridden */" : "";
3111
- 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}`);
3112
3175
  }
3113
3176
  lines.push(" }");
3114
3177
  }
@@ -7140,42 +7203,56 @@ exec ${JSON.stringify(process.execPath)} ${JSON.stringify(nativeHostJs)} "$@"
7140
7203
  }
7141
7204
 
7142
7205
  // src/skill-doc.ts
7143
- 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)
7144
7233
 
7145
- 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.
7146
7236
 
7147
- ## 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
+ \`\`\`
7148
7248
 
7149
- 1. **Discover tabs**: \`browser_tabs\` (or \`browserpilot tabs\`) \u2014 lists all tabs with \`tabId\`, URL, and title.
7150
- 2. **Navigate or pick existing tab**: \`browser_open_tab\` / \`browser_select_tab\` / \`browser_navigate\`. BrowserPilot auto-attaches \`chrome.debugger\` on demand with zero clicks.
7151
- 3. **Perceive the page**:
7152
- - Prefer \`browser_snapshot\` (compact AXTree with \`e1\`, \`e2\`... refs + automatic incremental diffs).
7153
- - Use \`scope\` (CSS selector/ref) or \`search\` on large pages to save tokens.
7154
- - Use \`browser_labeled_screenshot\` (Set-of-Mark overlays) when visual layout matters.
7155
- 4. **Interact with trusted CDP input**:
7156
- - \`browser_click\`, \`browser_fill\`, \`browser_type\`, \`browser_press_key\`, \`browser_select_option\`, \`browser_drag\`, \`browser_upload_file\`.
7157
- - Every action automatically reports newly thrown Console errors and failed Network requests.
7158
- 5. **Debug like Chrome DevTools**:
7159
- - \`browser_console\` (\`sinceLastCall: true\`) \u2014 logs, warnings, uncaught exceptions with stacks.
7160
- - \`browser_network\` (\`failedOnly: true\`, or pass \`requestId\` for headers, timing, JS initiator stack, and response body).
7161
- - \`browser_network_intercept\` \u2014 mock/block API responses via CDP \`Fetch\`.
7162
- - \`browser_styles\` \u2014 matched/inherited CSS rules with \`file:line\` + forced \`:hover\`/\`:focus\`.
7163
- - \`browser_react_info\` \u2014 React Fiber component name, dev source \`file:line\`, hierarchy, props.
7164
- - \`browser_debugger\` \u2014 breakpoints, pause/step, local scope variables, evaluate in call frame.
7165
- - \`browser_live_edit\` \u2014 grep loaded scripts and live-patch JS/CSS in memory.
7166
- - \`browser_performance\` \u2014 Core Web Vitals (LCP/CLS/FCP/TTFB), heap summary, CPU profiler, Tracing insights.
7167
- - \`browser_emulate\` \u2014 viewport, mobile, dark mode, CPU throttling, Slow 3G / offline.
7168
- - \`browser_downloads\` \u2014 configure download folder, list downloads, or wait for a file download to complete with its local path.
7169
- - \`browser_action_recorder\` \u2014 record user clicks/fills/selects/navigations into reusable batch steps, exec JS script, and Agent Skill Markdown.
7170
- - \`browser_record\` \u2014 record MP4/WebM screencast video via \`ffmpeg\` (optional \`audio: true\`) and create smart idle-sped-up demo videos.
7171
- 6. **Multi-step Stateful Sandbox (Playwriter replacement)**:
7172
- - \`browserpilot session new --tab-group docs\` -> returns session ID (e.g. \`1\`)
7173
- - \`browserpilot exec -s 1 -e 'const t = await tabs.open("https://example.com"); console.log(await snapshot({ tab: t }))'\`
7174
- - 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\`.
7175
7250
 
7176
- ## Safety Rules
7177
- - Never wipe profile-wide cookies/cache (BrowserPilot blocks \`Network.clearBrowserCookies\` / \`Network.clearBrowserCache\` automatically; use page-scoped \`browser_cookies\`).
7178
- - 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\`).
7179
7256
  `;
7180
7257
  export {
7181
7258
  BROWSERPILOT_SKILL_DOC,