browserpilot-cdp 0.0.0-stage → 1.1.0

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.
@@ -0,0 +1,784 @@
1
+ // ../protocol/dist/constants.js
2
+ var BROWSERPILOT_VERSION = "1.1.0";
3
+ var CDP_PROTOCOL_VERSION = "1.3";
4
+ var NATIVE_HOST_NAME = "com.browserpilot.bridge";
5
+ var NATIVE_MESSAGE_MAX_BYTES = 1024 * 1024;
6
+ var MAX_ACTIVITY_BUFFER = 200;
7
+ var DEFAULT_TAB_GROUP_TITLE = "browserpilot";
8
+ var BLOCKED_PROFILE_WIDE_CDP_COMMANDS = /* @__PURE__ */ new Set([
9
+ "Network.clearBrowserCookies",
10
+ "Network.clearBrowserCache"
11
+ ]);
12
+ var RESTRICTED_URL_PREFIXES = [
13
+ "chrome://",
14
+ "chrome-extension://",
15
+ "chrome-untrusted://",
16
+ "devtools://",
17
+ "edge://",
18
+ "brave://",
19
+ "about:blank#blocked",
20
+ "https://chrome.google.com/webstore",
21
+ "https://chromewebstore.google.com"
22
+ ];
23
+ function isRestrictedUrl(url) {
24
+ if (!url)
25
+ return false;
26
+ const lower = url.toLowerCase();
27
+ return RESTRICTED_URL_PREFIXES.some((prefix) => lower.startsWith(prefix));
28
+ }
29
+ function isBlockedProfileWideCommand(method) {
30
+ return BLOCKED_PROFILE_WIDE_CDP_COMMANDS.has(method);
31
+ }
32
+
33
+ // ../protocol/dist/rpc.js
34
+ function matchesDomainPattern(url, pattern) {
35
+ const normalized = pattern.trim().toLowerCase();
36
+ if (!normalized)
37
+ return false;
38
+ let hostname;
39
+ try {
40
+ hostname = new URL(url).hostname.toLowerCase();
41
+ } catch {
42
+ return false;
43
+ }
44
+ if (normalized.startsWith("*.")) {
45
+ const suffix = normalized.slice(2);
46
+ return hostname === suffix || hostname.endsWith(`.${suffix}`);
47
+ }
48
+ return hostname === normalized;
49
+ }
50
+ function isUrlAllowedByDomainRules(url, rules) {
51
+ if (rules.blockedDomains.some((p) => matchesDomainPattern(url, p))) {
52
+ return false;
53
+ }
54
+ if (rules.allowedDomains.length > 0) {
55
+ return rules.allowedDomains.some((p) => matchesDomainPattern(url, p));
56
+ }
57
+ return true;
58
+ }
59
+
60
+ // src/background.ts
61
+ var STORAGE_CONFIG_KEY = "browserpilot_config_v1";
62
+ var KEEPALIVE_ALARM = "browserpilot-keepalive";
63
+ var CONTEXT_MENU_PIN_ID = "browserpilot-pin-element";
64
+ var DEFAULT_CONFIG = {
65
+ theme: "dark",
66
+ autoAttach: true,
67
+ paused: false,
68
+ showHighlights: true,
69
+ showGhostCursor: true,
70
+ groupTabs: true,
71
+ daemonUrl: "ws://127.0.0.1:19888/extension" ? "ws://127.0.0.1:19888/extension" : `ws://${DEFAULT_DAEMON_HOST}:${DEFAULT_DAEMON_PORT}/extension`,
72
+ authToken: true ? "" : "",
73
+ domainRules: {
74
+ blockedDomains: [],
75
+ allowedDomains: []
76
+ }
77
+ };
78
+ var config = { ...DEFAULT_CONFIG };
79
+ var nativePort = null;
80
+ var ws = null;
81
+ var transportMode = "disconnected";
82
+ var reconnectTimer = null;
83
+ var heartbeatTimer = null;
84
+ var nativeRetryAfter = 0;
85
+ var attachedTabs = /* @__PURE__ */ new Map();
86
+ var inFlightAttaches = /* @__PURE__ */ new Map();
87
+ var recentActivity = [];
88
+ var recentErrors = [];
89
+ var recentFailedRequests = [];
90
+ var pendingRequestsByTab = /* @__PURE__ */ new Map();
91
+ var tabGroupIds = /* @__PURE__ */ new Map();
92
+ function logActivity(action, status, detail, tabId, durationMs) {
93
+ const entry = {
94
+ id: `${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
95
+ timestamp: Date.now(),
96
+ tabId,
97
+ action,
98
+ detail,
99
+ status,
100
+ durationMs
101
+ };
102
+ recentActivity.push(entry);
103
+ if (recentActivity.length > MAX_ACTIVITY_BUFFER) {
104
+ recentActivity.splice(0, recentActivity.length - MAX_ACTIVITY_BUFFER);
105
+ }
106
+ sendEvent("activity.logged", { entry });
107
+ broadcastUiUpdate();
108
+ }
109
+ async function getExtensionState() {
110
+ const tabs = await listAllTabs();
111
+ return {
112
+ connected: transportMode !== "disconnected",
113
+ transport: transportMode,
114
+ extensionId: chrome.runtime.id,
115
+ version: BROWSERPILOT_VERSION,
116
+ config,
117
+ attachedTabs: tabs.filter((t) => t.attached),
118
+ recentActivity: recentActivity.slice(-80),
119
+ recentErrors: recentErrors.slice(-50),
120
+ recentFailedRequests: recentFailedRequests.slice(-50)
121
+ };
122
+ }
123
+ function broadcastUiUpdate() {
124
+ void getExtensionState().then((state) => {
125
+ chrome.runtime.sendMessage({ type: "browserpilot:state-update", state }).catch(() => {
126
+ });
127
+ }).catch(() => {
128
+ });
129
+ }
130
+ function updateBadge() {
131
+ if (config.paused) {
132
+ void chrome.action.setBadgeText({ text: "OFF" });
133
+ void chrome.action.setBadgeBackgroundColor({ color: "#f59e0b" });
134
+ return;
135
+ }
136
+ if (transportMode === "disconnected") {
137
+ void chrome.action.setBadgeText({ text: "" });
138
+ return;
139
+ }
140
+ const count = attachedTabs.size;
141
+ void chrome.action.setBadgeText({ text: count > 0 ? String(count) : "ON" });
142
+ void chrome.action.setBadgeBackgroundColor({ color: count > 0 ? "#10b981" : "#0ea5e9" });
143
+ }
144
+ async function loadConfig() {
145
+ const stored = await chrome.storage.local.get(STORAGE_CONFIG_KEY);
146
+ const saved = stored[STORAGE_CONFIG_KEY];
147
+ if (saved) {
148
+ config = {
149
+ ...DEFAULT_CONFIG,
150
+ ...saved,
151
+ domainRules: {
152
+ blockedDomains: saved.domainRules?.blockedDomains ?? [],
153
+ allowedDomains: saved.domainRules?.allowedDomains ?? []
154
+ }
155
+ };
156
+ }
157
+ }
158
+ async function saveConfig(patch) {
159
+ const prevUrl = config.daemonUrl;
160
+ const prevToken = config.authToken;
161
+ config = {
162
+ ...config,
163
+ ...patch,
164
+ domainRules: patch.domainRules ? {
165
+ blockedDomains: patch.domainRules.blockedDomains ?? config.domainRules.blockedDomains,
166
+ allowedDomains: patch.domainRules.allowedDomains ?? config.domainRules.allowedDomains
167
+ } : config.domainRules
168
+ };
169
+ await chrome.storage.local.set({ [STORAGE_CONFIG_KEY]: config });
170
+ updateBadge();
171
+ broadcastUiUpdate();
172
+ if (config.daemonUrl !== prevUrl || config.authToken !== prevToken) {
173
+ disconnectTransport();
174
+ scheduleConnect(100);
175
+ }
176
+ return config;
177
+ }
178
+ function sendToBridge(msg) {
179
+ if (transportMode === "native" && nativePort) {
180
+ try {
181
+ nativePort.postMessage(msg);
182
+ } catch {
183
+ handleTransportDisconnected("native");
184
+ }
185
+ } else if (transportMode === "websocket" && ws && ws.readyState === WebSocket.OPEN) {
186
+ try {
187
+ ws.send(JSON.stringify(msg));
188
+ } catch {
189
+ handleTransportDisconnected("websocket");
190
+ }
191
+ }
192
+ }
193
+ function sendEvent(event, params) {
194
+ if (transportMode === "disconnected") return;
195
+ const msg = { type: "event", event, params };
196
+ sendToBridge(msg);
197
+ }
198
+ function sendHello(transport) {
199
+ const hello = {
200
+ type: "hello",
201
+ token: config.authToken,
202
+ extensionId: chrome.runtime.id,
203
+ extensionVersion: BROWSERPILOT_VERSION,
204
+ browser: navigator.userAgent.includes("Edg/") ? "Edge" : navigator.userAgent.includes("Brave") ? "Brave" : "Chrome",
205
+ transport
206
+ };
207
+ sendToBridge(hello);
208
+ }
209
+ function startHeartbeat() {
210
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
211
+ heartbeatTimer = setInterval(() => {
212
+ if (transportMode !== "disconnected") {
213
+ sendToBridge({ type: "ping", ts: Date.now() });
214
+ }
215
+ }, 18e3);
216
+ }
217
+ function disconnectTransport() {
218
+ if (heartbeatTimer) {
219
+ clearInterval(heartbeatTimer);
220
+ heartbeatTimer = null;
221
+ }
222
+ if (nativePort) {
223
+ try {
224
+ nativePort.disconnect();
225
+ } catch {
226
+ }
227
+ nativePort = null;
228
+ }
229
+ if (ws) {
230
+ try {
231
+ ws.close();
232
+ } catch {
233
+ }
234
+ ws = null;
235
+ }
236
+ transportMode = "disconnected";
237
+ updateBadge();
238
+ }
239
+ function handleTransportDisconnected(source) {
240
+ if (source === "native") {
241
+ nativePort = null;
242
+ nativeRetryAfter = Date.now() + 3e4;
243
+ } else {
244
+ ws = null;
245
+ }
246
+ if (transportMode === source) {
247
+ transportMode = "disconnected";
248
+ if (heartbeatTimer) {
249
+ clearInterval(heartbeatTimer);
250
+ heartbeatTimer = null;
251
+ }
252
+ updateBadge();
253
+ broadcastUiUpdate();
254
+ }
255
+ scheduleConnect(source === "native" ? 150 : 2e3);
256
+ }
257
+ function scheduleConnect(delayMs) {
258
+ if (reconnectTimer) clearTimeout(reconnectTimer);
259
+ reconnectTimer = setTimeout(() => {
260
+ reconnectTimer = null;
261
+ void connectBridge();
262
+ }, delayMs);
263
+ }
264
+ async function connectBridge() {
265
+ if (transportMode !== "disconnected") return;
266
+ if (Date.now() >= nativeRetryAfter && typeof chrome.runtime.connectNative === "function") {
267
+ try {
268
+ const port = chrome.runtime.connectNative(NATIVE_HOST_NAME);
269
+ nativePort = port;
270
+ transportMode = "native";
271
+ let receivedValidTraffic = false;
272
+ port.onMessage.addListener((msg) => {
273
+ receivedValidTraffic = true;
274
+ void handleBridgeMessage(msg);
275
+ });
276
+ port.onDisconnect.addListener(() => {
277
+ const err = chrome.runtime.lastError?.message;
278
+ if (!receivedValidTraffic && err) {
279
+ nativePort = null;
280
+ if (transportMode === "native") transportMode = "disconnected";
281
+ nativeRetryAfter = Date.now() + 6e4;
282
+ void connectWebSocket();
283
+ return;
284
+ }
285
+ handleTransportDisconnected("native");
286
+ });
287
+ sendHello("native");
288
+ startHeartbeat();
289
+ updateBadge();
290
+ broadcastUiUpdate();
291
+ return;
292
+ } catch {
293
+ nativeRetryAfter = Date.now() + 6e4;
294
+ }
295
+ }
296
+ await connectWebSocket();
297
+ }
298
+ async function connectWebSocket() {
299
+ if (transportMode !== "disconnected") return;
300
+ if (!config.daemonUrl) return;
301
+ try {
302
+ const url = new URL(config.daemonUrl);
303
+ if (config.authToken) {
304
+ url.searchParams.set("token", config.authToken);
305
+ }
306
+ const socket = new WebSocket(url.toString());
307
+ ws = socket;
308
+ socket.addEventListener("open", () => {
309
+ if (ws !== socket) return;
310
+ transportMode = "websocket";
311
+ sendHello("websocket");
312
+ startHeartbeat();
313
+ updateBadge();
314
+ broadcastUiUpdate();
315
+ logActivity("bridge.connect", "info", `Connected via WebSocket (${config.daemonUrl})`);
316
+ });
317
+ socket.addEventListener("message", (ev) => {
318
+ try {
319
+ const parsed = JSON.parse(String(ev.data));
320
+ void handleBridgeMessage(parsed);
321
+ } catch {
322
+ }
323
+ });
324
+ socket.addEventListener("close", () => {
325
+ if (ws === socket) {
326
+ handleTransportDisconnected("websocket");
327
+ }
328
+ });
329
+ socket.addEventListener("error", () => {
330
+ });
331
+ } catch {
332
+ scheduleConnect(3e3);
333
+ }
334
+ }
335
+ async function listAllTabs() {
336
+ const tabs = await chrome.tabs.query({});
337
+ const out = [];
338
+ for (const t of tabs) {
339
+ if (t.id === void 0) continue;
340
+ const rec = attachedTabs.get(t.id);
341
+ out.push({
342
+ tabId: t.id,
343
+ windowId: t.windowId,
344
+ url: t.url || t.pendingUrl || "",
345
+ title: t.title || "",
346
+ active: Boolean(t.active),
347
+ attached: Boolean(rec),
348
+ groupId: t.groupId !== void 0 && t.groupId >= 0 ? t.groupId : void 0,
349
+ groupTitle: rec?.tabGroup,
350
+ openerTabId: t.openerTabId,
351
+ status: t.status,
352
+ favIconUrl: t.favIconUrl
353
+ });
354
+ }
355
+ return out;
356
+ }
357
+ async function removeForeignExtensionIframes(tabId) {
358
+ try {
359
+ await chrome.scripting.executeScript({
360
+ target: { tabId },
361
+ func: (selfOrigin) => {
362
+ for (const iframe of Array.from(document.querySelectorAll("iframe"))) {
363
+ const src = iframe.getAttribute("src") || "";
364
+ if (src.startsWith("chrome-extension://") && !src.startsWith(selfOrigin)) {
365
+ iframe.remove();
366
+ }
367
+ }
368
+ },
369
+ args: [chrome.runtime.getURL("")]
370
+ });
371
+ } catch {
372
+ }
373
+ }
374
+ async function assignTabGroup(tabId, groupTitle, groupColor) {
375
+ if (!config.groupTabs) return;
376
+ const title = (groupTitle || DEFAULT_TAB_GROUP_TITLE).trim();
377
+ const color = groupColor || "green";
378
+ try {
379
+ const existingGroupId = tabGroupIds.get(title);
380
+ let groupId;
381
+ if (existingGroupId !== void 0) {
382
+ try {
383
+ await chrome.tabGroups.get(existingGroupId);
384
+ groupId = await chrome.tabs.group({ groupId: existingGroupId, tabIds: [tabId] });
385
+ } catch {
386
+ groupId = await chrome.tabs.group({ tabIds: [tabId] });
387
+ }
388
+ } else {
389
+ groupId = await chrome.tabs.group({ tabIds: [tabId] });
390
+ }
391
+ tabGroupIds.set(title, groupId);
392
+ await chrome.tabGroups.update(groupId, { title, color });
393
+ } catch {
394
+ }
395
+ }
396
+ async function ensureAttached(tabId, options) {
397
+ if (config.paused) {
398
+ throw new Error("BrowserPilot is paused by user in the extension popup.");
399
+ }
400
+ const existing = attachedTabs.get(tabId);
401
+ if (existing) return existing;
402
+ const inflight = inFlightAttaches.get(tabId);
403
+ if (inflight) return inflight;
404
+ const task = (async () => {
405
+ const tab = await chrome.tabs.get(tabId);
406
+ const url = tab.url || tab.pendingUrl || "";
407
+ if (isRestrictedUrl(url)) {
408
+ throw new Error(`Cannot attach chrome.debugger to restricted URL: ${url}`);
409
+ }
410
+ if (url.startsWith("http") && !isUrlAllowedByDomainRules(url, config.domainRules)) {
411
+ throw new Error(`Domain blocked by BrowserPilot domain rules: ${url}`);
412
+ }
413
+ await removeForeignExtensionIframes(tabId);
414
+ try {
415
+ await chrome.debugger.attach({ tabId }, CDP_PROTOCOL_VERSION);
416
+ } catch (err) {
417
+ const msg = err instanceof Error ? err.message : String(err);
418
+ if (!/already attached/i.test(msg)) {
419
+ throw err;
420
+ }
421
+ }
422
+ const rec = {
423
+ tabId,
424
+ attachedAt: Date.now(),
425
+ tabGroup: options?.tabGroup,
426
+ tabGroupColor: options?.tabGroupColor,
427
+ childSessions: /* @__PURE__ */ new Set()
428
+ };
429
+ attachedTabs.set(tabId, rec);
430
+ await chrome.debugger.sendCommand({ tabId }, "Target.setAutoAttach", {
431
+ autoAttach: true,
432
+ waitForDebuggerOnStart: false,
433
+ flatten: true
434
+ }).catch(() => {
435
+ });
436
+ if (options?.tabGroup) {
437
+ await assignTabGroup(tabId, options.tabGroup, options.tabGroupColor);
438
+ }
439
+ updateBadge();
440
+ broadcastUiUpdate();
441
+ sendEvent("tab.attached", { tabId, url, title: tab.title || "" });
442
+ logActivity("tab.attach", "ok", `${tab.title || url || `Tab #${tabId}`}`, tabId);
443
+ return rec;
444
+ })();
445
+ inFlightAttaches.set(tabId, task);
446
+ try {
447
+ return await task;
448
+ } finally {
449
+ inFlightAttaches.delete(tabId);
450
+ }
451
+ }
452
+ async function detachTab(tabId) {
453
+ if (!attachedTabs.has(tabId)) return;
454
+ attachedTabs.delete(tabId);
455
+ await chrome.debugger.detach({ tabId }).catch(() => {
456
+ });
457
+ updateBadge();
458
+ broadcastUiUpdate();
459
+ sendEvent("tab.detached", { tabId, reason: "requested" });
460
+ logActivity("tab.detach", "info", `Detached tab #${tabId}`, tabId);
461
+ }
462
+ async function handleBridgeMessage(msg) {
463
+ if (!msg || typeof msg !== "object") return;
464
+ if (msg.type === "ping") {
465
+ sendToBridge({ type: "pong", ts: msg.ts });
466
+ return;
467
+ }
468
+ if (msg.type === "pong") return;
469
+ if (msg.type !== "request") return;
470
+ const req = msg;
471
+ const start = Date.now();
472
+ let response;
473
+ try {
474
+ const result = await executeBridgeMethod(req.method, req.params ?? {});
475
+ response = { type: "response", id: req.id, ok: true, result };
476
+ if (req.method !== "cdp.send" && req.method !== "tabs.list" && req.method !== "extension.getState") {
477
+ logActivity(req.method, "ok", void 0, req.params?.tabId, Date.now() - start);
478
+ }
479
+ } catch (err) {
480
+ const message = err instanceof Error ? err.message : String(err);
481
+ response = {
482
+ type: "response",
483
+ id: req.id,
484
+ ok: false,
485
+ error: { code: "EXTENSION_ERROR", message }
486
+ };
487
+ logActivity(req.method, "error", message, req.params?.tabId, Date.now() - start);
488
+ }
489
+ sendToBridge(response);
490
+ }
491
+ async function executeBridgeMethod(method, params) {
492
+ switch (method) {
493
+ case "tabs.list": {
494
+ return { tabs: await listAllTabs() };
495
+ }
496
+ case "tabs.create": {
497
+ const url = typeof params.url === "string" && params.url ? params.url : "about:blank";
498
+ const active = params.active !== false;
499
+ const tabGroup = params.tabGroup;
500
+ const tabGroupColor = params.tabGroupColor;
501
+ const tab = await chrome.tabs.create({ url, active });
502
+ if (tab.id === void 0) throw new Error("Failed to create tab");
503
+ if (config.autoAttach && !isRestrictedUrl(url)) {
504
+ await ensureAttached(tab.id, { tabGroup, tabGroupColor });
505
+ }
506
+ const tabs = await listAllTabs();
507
+ return tabs.find((t) => t.tabId === tab.id) ?? { tabId: tab.id, url, title: tab.title || "", active, attached: true };
508
+ }
509
+ case "tabs.close": {
510
+ const tabId = Number(params.tabId);
511
+ await detachTab(tabId);
512
+ await chrome.tabs.remove(tabId).catch(() => {
513
+ });
514
+ return { closed: true };
515
+ }
516
+ case "tabs.activate": {
517
+ const tabId = Number(params.tabId);
518
+ const tab = await chrome.tabs.update(tabId, { active: true });
519
+ if (tab?.windowId !== void 0) {
520
+ await chrome.windows.update(tab.windowId, { focused: true }).catch(() => {
521
+ });
522
+ }
523
+ return { activated: true };
524
+ }
525
+ case "tabs.attach": {
526
+ const tabId = Number(params.tabId);
527
+ await ensureAttached(tabId, {
528
+ tabGroup: params.tabGroup,
529
+ tabGroupColor: params.tabGroupColor
530
+ });
531
+ const tabs = await listAllTabs();
532
+ return tabs.find((t) => t.tabId === tabId);
533
+ }
534
+ case "tabs.detach": {
535
+ await detachTab(Number(params.tabId));
536
+ return { detached: true };
537
+ }
538
+ case "cdp.send": {
539
+ const tabId = Number(params.tabId);
540
+ const cdpMethod = String(params.method ?? "");
541
+ const cdpParams = params.params ?? void 0;
542
+ const sessionId = params.sessionId;
543
+ if (!cdpMethod) throw new Error("Missing CDP method");
544
+ if (!params.allowUnsafeBrowserWide && isBlockedProfileWideCommand(cdpMethod)) {
545
+ throw new Error(`Blocked destructive profile-wide CDP command: ${cdpMethod}`);
546
+ }
547
+ if (!attachedTabs.has(tabId)) {
548
+ if (!config.autoAttach) {
549
+ throw new Error(`Tab ${tabId} is not attached and autoAttach is disabled`);
550
+ }
551
+ await ensureAttached(tabId);
552
+ }
553
+ const target = sessionId ? { tabId, sessionId } : { tabId };
554
+ const result = await chrome.debugger.sendCommand(target, cdpMethod, cdpParams);
555
+ if (cdpMethod === "Page.navigate" || cdpMethod === "Input.dispatchMouseEvent" || cdpMethod === "Input.insertText" || cdpMethod === "Runtime.evaluate") {
556
+ logActivity(cdpMethod, "ok", cdpMethod === "Page.navigate" ? String(cdpParams?.url ?? "") : void 0, tabId);
557
+ }
558
+ return result ?? {};
559
+ }
560
+ case "extension.getState": {
561
+ return await getExtensionState();
562
+ }
563
+ case "extension.setConfig": {
564
+ return await saveConfig(params);
565
+ }
566
+ case "extension.highlight": {
567
+ if (!config.showHighlights) return { ok: true };
568
+ const tabId = Number(params.tabId);
569
+ await chrome.tabs.sendMessage(tabId, {
570
+ type: "browserpilot:highlight",
571
+ box: params.box,
572
+ label: params.label
573
+ }).catch(() => {
574
+ });
575
+ return { ok: true };
576
+ }
577
+ case "extension.ghostCursor": {
578
+ if (!config.showGhostCursor) return { ok: true };
579
+ const tabId = Number(params.tabId);
580
+ await chrome.tabs.sendMessage(tabId, {
581
+ type: "browserpilot:ghost-cursor",
582
+ x: params.x,
583
+ y: params.y,
584
+ clicking: params.clicking
585
+ }).catch(() => {
586
+ });
587
+ return { ok: true };
588
+ }
589
+ case "extension.getPinnedElement": {
590
+ const tabId = Number(params.tabId);
591
+ const rec = attachedTabs.get(tabId);
592
+ const tab = await chrome.tabs.get(tabId).catch(() => null);
593
+ return rec?.lastPinnedVar ? { globalVar: rec.lastPinnedVar, url: tab?.url } : null;
594
+ }
595
+ default:
596
+ throw new Error(`Unknown extension RPC method: ${method}`);
597
+ }
598
+ }
599
+ chrome.debugger.onEvent.addListener((source, method, params) => {
600
+ const tabId = source.tabId;
601
+ if (tabId === void 0) return;
602
+ const sessionId = source.sessionId;
603
+ const p = params ?? {};
604
+ const rec = attachedTabs.get(tabId);
605
+ if (rec && method === "Target.attachedToTarget" && typeof p.sessionId === "string") {
606
+ rec.childSessions.add(p.sessionId);
607
+ } else if (rec && method === "Target.detachedFromTarget" && typeof p.sessionId === "string") {
608
+ rec.childSessions.delete(p.sessionId);
609
+ }
610
+ if (method === "Runtime.consoleAPICalled" && p.type === "error") {
611
+ const args = p.args ?? [];
612
+ const text = args.map((a) => a.value !== void 0 ? String(a.value) : a.description || "").join(" ").slice(0, 300);
613
+ recentErrors.push({ timestamp: Date.now(), tabId, text });
614
+ if (recentErrors.length > 100) recentErrors.splice(0, recentErrors.length - 100);
615
+ broadcastUiUpdate();
616
+ } else if (method === "Runtime.exceptionThrown") {
617
+ const d = p.exceptionDetails ?? {};
618
+ recentErrors.push({
619
+ timestamp: Date.now(),
620
+ tabId,
621
+ text: (d.exception?.description || d.text || "Uncaught exception").slice(0, 300),
622
+ url: d.url
623
+ });
624
+ if (recentErrors.length > 100) recentErrors.splice(0, recentErrors.length - 100);
625
+ broadcastUiUpdate();
626
+ } else if (method === "Network.requestWillBeSent") {
627
+ const req = p.request ?? {};
628
+ if (typeof p.requestId === "string" && req.url) {
629
+ pendingRequestsByTab.set(`${tabId}:${p.requestId}`, { url: req.url, method: req.method || "GET" });
630
+ if (pendingRequestsByTab.size > 500) {
631
+ const firstKey = pendingRequestsByTab.keys().next().value;
632
+ if (firstKey) pendingRequestsByTab.delete(firstKey);
633
+ }
634
+ }
635
+ } else if (method === "Network.responseReceived") {
636
+ const res = p.response ?? {};
637
+ if (typeof res.status === "number" && res.status >= 400) {
638
+ const reqInfo = typeof p.requestId === "string" ? pendingRequestsByTab.get(`${tabId}:${p.requestId}`) : void 0;
639
+ recentFailedRequests.push({
640
+ timestamp: Date.now(),
641
+ tabId,
642
+ method: reqInfo?.method || "GET",
643
+ status: res.status,
644
+ url: res.url || reqInfo?.url || ""
645
+ });
646
+ if (recentFailedRequests.length > 100) recentFailedRequests.splice(0, recentFailedRequests.length - 100);
647
+ broadcastUiUpdate();
648
+ }
649
+ } else if (method === "Network.loadingFailed") {
650
+ const reqInfo = typeof p.requestId === "string" ? pendingRequestsByTab.get(`${tabId}:${p.requestId}`) : void 0;
651
+ recentFailedRequests.push({
652
+ timestamp: Date.now(),
653
+ tabId,
654
+ method: reqInfo?.method || "GET",
655
+ url: reqInfo?.url || "",
656
+ errorText: String(p.errorText || "Failed")
657
+ });
658
+ if (recentFailedRequests.length > 100) recentFailedRequests.splice(0, recentFailedRequests.length - 100);
659
+ broadcastUiUpdate();
660
+ }
661
+ sendEvent("cdp.event", {
662
+ tabId,
663
+ method,
664
+ params: p,
665
+ ...sessionId ? { sessionId } : {}
666
+ });
667
+ });
668
+ chrome.debugger.onDetach.addListener((source, reason) => {
669
+ const tabId = source.tabId;
670
+ if (tabId === void 0) return;
671
+ attachedTabs.delete(tabId);
672
+ updateBadge();
673
+ broadcastUiUpdate();
674
+ sendEvent("tab.detached", { tabId, reason });
675
+ logActivity("tab.detached", "info", `Tab #${tabId} detached (${reason})`, tabId);
676
+ });
677
+ chrome.tabs.onRemoved.addListener((tabId) => {
678
+ if (attachedTabs.has(tabId)) {
679
+ attachedTabs.delete(tabId);
680
+ updateBadge();
681
+ broadcastUiUpdate();
682
+ }
683
+ sendEvent("tab.removed", { tabId });
684
+ });
685
+ chrome.webNavigation.onCreatedNavigationTarget.addListener((details) => {
686
+ const opener = attachedTabs.get(details.sourceTabId);
687
+ if (!opener || !config.autoAttach || config.paused) return;
688
+ void ensureAttached(details.tabId, {
689
+ tabGroup: opener.tabGroup,
690
+ tabGroupColor: opener.tabGroupColor
691
+ }).then(() => {
692
+ sendEvent("popup.opened", {
693
+ openerTabId: details.sourceTabId,
694
+ tabId: details.tabId,
695
+ url: details.url
696
+ });
697
+ }).catch(() => {
698
+ });
699
+ });
700
+ chrome.runtime.onInstalled.addListener(() => {
701
+ chrome.contextMenus.removeAll(() => {
702
+ chrome.contextMenus.create({
703
+ id: CONTEXT_MENU_PIN_ID,
704
+ title: "Pin Element for BrowserPilot",
705
+ contexts: ["all"]
706
+ });
707
+ });
708
+ });
709
+ chrome.contextMenus.onClicked.addListener((info, tab) => {
710
+ if (info.menuItemId !== CONTEXT_MENU_PIN_ID || !tab?.id) return;
711
+ const tabId = tab.id;
712
+ void (async () => {
713
+ const resp = await chrome.tabs.sendMessage(tabId, { type: "browserpilot:pin-last-right-clicked" }).catch(() => null);
714
+ if (resp?.globalVar) {
715
+ const rec = await ensureAttached(tabId).catch(() => null);
716
+ if (rec) rec.lastPinnedVar = resp.globalVar;
717
+ logActivity("element.pin", "ok", `${resp.globalVar} (${resp.selector ?? ""})`, tabId);
718
+ sendEvent("element.pinned", { tabId, ...resp, url: tab.url });
719
+ }
720
+ })();
721
+ });
722
+ chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
723
+ if (!msg || typeof msg !== "object") return false;
724
+ if (msg.type === "browserpilot:get-state") {
725
+ void getExtensionState().then(sendResponse);
726
+ return true;
727
+ }
728
+ if (msg.type === "browserpilot:update-config") {
729
+ void saveConfig(msg.patch).then((cfg) => sendResponse({ ok: true, config: cfg }));
730
+ return true;
731
+ }
732
+ if (msg.type === "browserpilot:detach-tab") {
733
+ void detachTab(Number(msg.tabId)).then(() => sendResponse({ ok: true }));
734
+ return true;
735
+ }
736
+ if (msg.type === "browserpilot:detach-all") {
737
+ void Promise.all(Array.from(attachedTabs.keys()).map((id) => detachTab(id))).then(() => sendResponse({ ok: true }));
738
+ return true;
739
+ }
740
+ if (msg.type === "browserpilot:reconnect") {
741
+ nativeRetryAfter = 0;
742
+ disconnectTransport();
743
+ void connectBridge().then(() => sendResponse({ ok: true }));
744
+ return true;
745
+ }
746
+ if (msg.type === "browserpilot:open-sidepanel") {
747
+ void chrome.windows.getCurrent().then((win) => {
748
+ if (win.id !== void 0 && chrome.sidePanel?.open) {
749
+ return chrome.sidePanel.open({ windowId: win.id });
750
+ }
751
+ }).then(() => sendResponse({ ok: true })).catch(() => sendResponse({ ok: false }));
752
+ return true;
753
+ }
754
+ if (msg.type === "browserpilot:start-picker") {
755
+ void chrome.tabs.query({ active: true, currentWindow: true }).then(([tab]) => {
756
+ if (tab?.id) {
757
+ return chrome.tabs.sendMessage(tab.id, { type: "browserpilot:start-picker" });
758
+ }
759
+ }).then(() => sendResponse({ ok: true })).catch(() => sendResponse({ ok: false }));
760
+ return true;
761
+ }
762
+ if (msg.type === "browserpilot:picked-element") {
763
+ logActivity("element.picked", "ok", `${msg.selector} (${msg.text ?? ""})`, _sender.tab?.id);
764
+ sendEvent("element.picked", { tabId: _sender.tab?.id, ...msg });
765
+ sendResponse({ ok: true });
766
+ return false;
767
+ }
768
+ return false;
769
+ });
770
+ chrome.alarms.create(KEEPALIVE_ALARM, { periodInMinutes: 0.4 });
771
+ chrome.alarms.onAlarm.addListener((alarm) => {
772
+ if (alarm.name === KEEPALIVE_ALARM) {
773
+ if (transportMode === "disconnected") {
774
+ void connectBridge();
775
+ } else {
776
+ sendToBridge({ type: "ping", ts: Date.now() });
777
+ }
778
+ }
779
+ });
780
+ void loadConfig().then(() => {
781
+ updateBadge();
782
+ void connectBridge();
783
+ });
784
+ //# sourceMappingURL=background.js.map