-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathbrowser.ts
More file actions
2557 lines (2269 loc) · 77.4 KB
/
browser.ts
File metadata and controls
2557 lines (2269 loc) · 77.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
chromium,
firefox,
webkit,
devices,
type Browser,
type BrowserContext,
type Page,
type Frame,
type Dialog,
type Request,
type Route,
type Locator,
type CDPSession,
type Video,
} from 'playwright-core';
import path from 'node:path';
import os from 'node:os';
import { existsSync, mkdirSync, rmSync, readFileSync, statSync } from 'node:fs';
import { writeFile, mkdir } from 'node:fs/promises';
import type { LaunchCommand, TraceEvent } from './types.js';
import { type RefMap, type EnhancedSnapshot, getEnhancedSnapshot, parseRef } from './snapshot.js';
import { safeHeaderMerge } from './state-utils.js';
import { isDomainAllowed, installDomainFilter, parseDomainList } from './domain-filter.js';
import {
getEncryptionKey,
isEncryptedPayload,
decryptData,
ENCRYPTION_KEY_ENV,
} from './state-utils.js';
/**
* Returns the default Playwright timeout in milliseconds for standard operations.
* Can be overridden via the AGENT_BROWSER_DEFAULT_TIMEOUT environment variable.
* Default is 25s, which is below the CLI's 30s IPC read timeout to ensure
* Playwright errors are returned before the CLI gives up with EAGAIN.
* CDP and recording contexts use a shorter fixed timeout (10s) and are not affected.
*/
export function getDefaultTimeout(): number {
const envValue = process.env.AGENT_BROWSER_DEFAULT_TIMEOUT;
if (envValue) {
const parsed = parseInt(envValue, 10);
if (!isNaN(parsed) && parsed >= 1000) {
return parsed;
}
}
return 25000;
}
// Screencast frame data from CDP
export interface ScreencastFrame {
data: string; // base64 encoded image
metadata: {
offsetTop: number;
pageScaleFactor: number;
deviceWidth: number;
deviceHeight: number;
scrollOffsetX: number;
scrollOffsetY: number;
timestamp?: number;
};
sessionId: number;
}
// Screencast options
export interface ScreencastOptions {
format?: 'jpeg' | 'png';
quality?: number; // 0-100, only for jpeg
maxWidth?: number;
maxHeight?: number;
everyNthFrame?: number;
}
interface TrackedRequest {
url: string;
method: string;
headers: Record<string, string>;
timestamp: number;
resourceType: string;
}
interface ConsoleMessage {
type: string;
text: string;
timestamp: number;
}
interface PageError {
message: string;
timestamp: number;
}
/**
* Manages the Playwright browser lifecycle with multiple tabs/windows
*/
export class BrowserManager {
private browser: Browser | null = null;
private cdpEndpoint: string | null = null; // stores port number or full URL
private isPersistentContext: boolean = false;
private browserbaseSessionId: string | null = null;
private browserbaseApiKey: string | null = null;
private browserUseSessionId: string | null = null;
private browserUseApiKey: string | null = null;
private kernelSessionId: string | null = null;
private kernelApiKey: string | null = null;
private contexts: BrowserContext[] = [];
private pages: Page[] = [];
private activePageIndex: number = 0;
private activeFrame: Frame | null = null;
private dialogHandler: ((dialog: Dialog) => Promise<void>) | null = null;
private trackedRequests: TrackedRequest[] = [];
private routes: Map<string, (route: Route) => Promise<void>> = new Map();
private consoleMessages: ConsoleMessage[] = [];
private pageErrors: PageError[] = [];
private isRecordingHar: boolean = false;
private refMap: RefMap = {};
private lastSnapshot: string = '';
private scopedHeaderRoutes: Map<string, (route: Route) => Promise<void>> = new Map();
private colorScheme: 'light' | 'dark' | 'no-preference' | null = null;
private downloadPath: string | null = null;
private allowedDomains: string[] = [];
/**
* Set the persistent color scheme preference.
* Applied automatically to all new pages and contexts.
*/
setColorScheme(scheme: 'light' | 'dark' | 'no-preference' | null): void {
this.colorScheme = scheme;
}
// CDP session for screencast and input injection
private cdpSession: CDPSession | null = null;
private screencastActive: boolean = false;
private screencastSessionId: number = 0;
private frameCallback: ((frame: ScreencastFrame) => void) | null = null;
private screencastFrameHandler: ((params: any) => void) | null = null;
// Video recording (Playwright native)
private recordingContext: BrowserContext | null = null;
private recordingPage: Page | null = null;
private recordingOutputPath: string = '';
private recordingTempDir: string = '';
private launchWarnings: string[] = [];
/**
* Get and clear launch warnings (e.g., decryption failures)
*/
getAndClearWarnings(): string[] {
const warnings = this.launchWarnings;
this.launchWarnings = [];
return warnings;
}
// CDP profiling state
private static readonly MAX_PROFILE_EVENTS = 5_000_000;
private profilingActive: boolean = false;
private profileChunks: TraceEvent[] = [];
private profileEventsDropped: boolean = false;
private profileCompleteResolver: (() => void) | null = null;
private profileDataHandler: ((params: { value?: TraceEvent[] }) => void) | null = null;
private profileCompleteHandler: (() => void) | null = null;
/**
* Check if browser is launched
*/
isLaunched(): boolean {
return (this.browser !== null && this.browser.isConnected()) || this.isPersistentContext;
}
/**
* Get enhanced snapshot with refs and cache the ref map
*/
async getSnapshot(options?: {
interactive?: boolean;
cursor?: boolean;
maxDepth?: number;
compact?: boolean;
selector?: string;
}): Promise<EnhancedSnapshot> {
const page = this.getPage();
const snapshot = await getEnhancedSnapshot(page, options);
this.refMap = snapshot.refs;
this.lastSnapshot = snapshot.tree;
return snapshot;
}
/**
* Get the last snapshot tree text (empty string if no snapshot has been taken)
*/
getLastSnapshot(): string {
return this.lastSnapshot;
}
/**
* Update the stored snapshot (used by diff to keep the baseline current)
*/
setLastSnapshot(snapshot: string): void {
this.lastSnapshot = snapshot;
}
/**
* Get the cached ref map from last snapshot
*/
getRefMap(): RefMap {
return this.refMap;
}
/**
* Get a locator from a ref (e.g., "e1", "@e1", "ref=e1")
* Returns null if ref doesn't exist or is invalid
*/
getLocatorFromRef(refArg: string): Locator | null {
const ref = parseRef(refArg);
if (!ref) return null;
const refData = this.refMap[ref];
if (!refData) return null;
const page = this.getPage();
// Check if this is a cursor-interactive element (uses CSS selector, not ARIA role)
// These have pseudo-roles 'clickable' or 'focusable' and a CSS selector
if (refData.role === 'clickable' || refData.role === 'focusable') {
// The selector is a CSS selector, use it directly
return page.locator(refData.selector);
}
// Build locator with exact: true to avoid substring matches
let locator: Locator = page.getByRole(refData.role as any, {
name: refData.name,
exact: true,
});
// If an nth index is stored (for disambiguation), use it
if (refData.nth !== undefined) {
locator = locator.nth(refData.nth);
}
return locator;
}
/**
* Check if a selector looks like a ref
*/
isRef(selector: string): boolean {
return parseRef(selector) !== null;
}
/**
* Install the domain filter on a context if an allowlist is configured.
* Should be called before any pages navigate on the context.
*/
private async ensureDomainFilter(context: BrowserContext): Promise<void> {
if (this.allowedDomains.length > 0) {
await installDomainFilter(context, this.allowedDomains);
}
}
/**
* After installing the domain filter, verify existing pages are on allowed
* domains. Pages that pre-date the filter (e.g. CDP/cloud connect) may have
* already navigated to disallowed domains. Navigate them to about:blank.
*/
private async sanitizeExistingPages(pages: Page[]): Promise<void> {
if (this.allowedDomains.length === 0) return;
for (const page of pages) {
const url = page.url();
if (!url || url === 'about:blank') continue;
try {
const hostname = new URL(url).hostname.toLowerCase();
if (!isDomainAllowed(hostname, this.allowedDomains)) {
await page.goto('about:blank');
}
} catch {
await page.goto('about:blank').catch(() => {});
}
}
}
/**
* Check if a URL is allowed by the domain allowlist.
* Throws if the URL's domain is blocked. No-op if no allowlist is set.
* Blocks non-http(s) schemes and unparseable URLs by default.
*/
checkDomainAllowed(url: string): void {
if (this.allowedDomains.length === 0) return;
if (!url.startsWith('http://') && !url.startsWith('https://')) {
throw new Error(`Navigation blocked: non-http(s) scheme in URL "${url}"`);
}
let hostname: string;
try {
hostname = new URL(url).hostname.toLowerCase();
} catch {
throw new Error(`Navigation blocked: unable to parse URL "${url}"`);
}
if (!isDomainAllowed(hostname, this.allowedDomains)) {
throw new Error(`Navigation blocked: ${hostname} is not in the allowed domains list`);
}
}
/**
* Get locator - supports both refs and regular selectors
*/
getLocator(selectorOrRef: string): Locator {
// Check if it's a ref first
const locator = this.getLocatorFromRef(selectorOrRef);
if (locator) return locator;
// Otherwise treat as regular selector
const page = this.getPage();
return page.locator(selectorOrRef);
}
/**
* Check if the browser has any usable pages
*/
hasPages(): boolean {
return this.pages.length > 0;
}
/**
* Ensure at least one page exists. If the browser is launched but all pages
* were closed (stale session), creates a new page on the existing context.
* No-op if pages already exist.
*/
async ensurePage(): Promise<void> {
if (this.pages.length > 0) return;
if (!this.browser && !this.isPersistentContext) return;
// Use the last existing context, or create a new one
let context: BrowserContext;
if (this.contexts.length > 0) {
context = this.contexts[this.contexts.length - 1];
} else if (this.browser) {
context = await this.browser.newContext({
...(this.colorScheme && { colorScheme: this.colorScheme }),
});
context.setDefaultTimeout(getDefaultTimeout());
this.contexts.push(context);
this.setupContextTracking(context);
await this.ensureDomainFilter(context);
} else {
return;
}
const page = await context.newPage();
if (!this.pages.includes(page)) {
this.pages.push(page);
this.setupPageTracking(page);
}
this.activePageIndex = this.pages.length - 1;
}
/**
* Get the current active page, throws if not launched
*/
getPage(): Page {
if (this.pages.length === 0) {
throw new Error('Browser not launched. Call launch first.');
}
return this.pages[this.activePageIndex];
}
/**
* Get the current frame (or page's main frame if no frame is selected)
*/
getFrame(): Frame {
if (this.activeFrame) {
return this.activeFrame;
}
return this.getPage().mainFrame();
}
/**
* Switch to a frame by selector, name, or URL
*/
async switchToFrame(options: { selector?: string; name?: string; url?: string }): Promise<void> {
const page = this.getPage();
if (options.selector) {
const frameElement = await page.$(options.selector);
if (!frameElement) {
throw new Error(`Frame not found: ${options.selector}`);
}
const frame = await frameElement.contentFrame();
if (!frame) {
throw new Error(`Element is not a frame: ${options.selector}`);
}
this.activeFrame = frame;
} else if (options.name) {
const frame = page.frame({ name: options.name });
if (!frame) {
throw new Error(`Frame not found with name: ${options.name}`);
}
this.activeFrame = frame;
} else if (options.url) {
const frame = page.frame({ url: options.url });
if (!frame) {
throw new Error(`Frame not found with URL: ${options.url}`);
}
this.activeFrame = frame;
}
}
/**
* Switch back to main frame
*/
switchToMainFrame(): void {
this.activeFrame = null;
}
/**
* Set up dialog handler
*/
setDialogHandler(response: 'accept' | 'dismiss', promptText?: string): void {
const page = this.getPage();
// Remove existing handler if any
if (this.dialogHandler) {
page.removeListener('dialog', this.dialogHandler);
}
this.dialogHandler = async (dialog: Dialog) => {
if (response === 'accept') {
await dialog.accept(promptText);
} else {
await dialog.dismiss();
}
};
page.on('dialog', this.dialogHandler);
}
/**
* Clear dialog handler
*/
clearDialogHandler(): void {
if (this.dialogHandler) {
const page = this.getPage();
page.removeListener('dialog', this.dialogHandler);
this.dialogHandler = null;
}
}
/**
* Start tracking requests
*/
startRequestTracking(): void {
const page = this.getPage();
page.on('request', (request: Request) => {
this.trackedRequests.push({
url: request.url(),
method: request.method(),
headers: request.headers(),
timestamp: Date.now(),
resourceType: request.resourceType(),
});
});
}
/**
* Get tracked requests
*/
getRequests(filter?: string): TrackedRequest[] {
if (filter) {
return this.trackedRequests.filter((r) => r.url.includes(filter));
}
return this.trackedRequests;
}
/**
* Clear tracked requests
*/
clearRequests(): void {
this.trackedRequests = [];
}
/**
* Add a route to intercept requests
*/
async addRoute(
url: string,
options: {
response?: {
status?: number;
body?: string;
contentType?: string;
headers?: Record<string, string>;
};
abort?: boolean;
}
): Promise<void> {
const page = this.getPage();
const handler = async (route: Route) => {
if (options.abort) {
await route.abort();
} else if (options.response) {
await route.fulfill({
status: options.response.status ?? 200,
body: options.response.body ?? '',
contentType: options.response.contentType ?? 'text/plain',
headers: options.response.headers,
});
} else {
await route.continue();
}
};
this.routes.set(url, handler);
await page.route(url, handler);
}
/**
* Remove a route
*/
async removeRoute(url?: string): Promise<void> {
const page = this.getPage();
if (url) {
const handler = this.routes.get(url);
if (handler) {
await page.unroute(url, handler);
this.routes.delete(url);
}
} else {
// Remove all routes
for (const [routeUrl, handler] of this.routes) {
await page.unroute(routeUrl, handler);
}
this.routes.clear();
}
}
/**
* Set geolocation
*/
async setGeolocation(latitude: number, longitude: number, accuracy?: number): Promise<void> {
const context = this.contexts[0];
if (context) {
await context.setGeolocation({ latitude, longitude, accuracy });
}
}
/**
* Set permissions
*/
async setPermissions(permissions: string[], grant: boolean): Promise<void> {
const context = this.contexts[0];
if (context) {
if (grant) {
await context.grantPermissions(permissions);
} else {
await context.clearPermissions();
}
}
}
/**
* Set viewport
*/
async setViewport(width: number, height: number): Promise<void> {
const page = this.getPage();
await page.setViewportSize({ width, height });
}
/**
* Set device scale factor (devicePixelRatio) via CDP
* This sets window.devicePixelRatio which affects how the page renders and responds to media queries
*
* Note: When using CDP to set deviceScaleFactor, screenshots will be at logical pixel dimensions
* (viewport size), not physical pixel dimensions (viewport × scale). This is a Playwright limitation
* when using CDP emulation on existing contexts. For true HiDPI screenshots with physical pixels,
* deviceScaleFactor must be set at context creation time.
*
* Must be called after setViewport to work correctly
*/
async setDeviceScaleFactor(
deviceScaleFactor: number,
width: number,
height: number,
mobile: boolean = false
): Promise<void> {
const cdp = await this.getCDPSession();
await cdp.send('Emulation.setDeviceMetricsOverride', {
width,
height,
deviceScaleFactor,
mobile,
});
}
/**
* Clear device metrics override to restore default devicePixelRatio
*/
async clearDeviceMetricsOverride(): Promise<void> {
const cdp = await this.getCDPSession();
await cdp.send('Emulation.clearDeviceMetricsOverride');
}
/**
* Get device descriptor
*/
getDevice(deviceName: string): (typeof devices)[keyof typeof devices] | undefined {
return devices[deviceName as keyof typeof devices];
}
/**
* List available devices
*/
listDevices(): string[] {
return Object.keys(devices);
}
/**
* Start console message tracking
*/
startConsoleTracking(): void {
const page = this.getPage();
page.on('console', (msg) => {
this.consoleMessages.push({
type: msg.type(),
text: msg.text(),
timestamp: Date.now(),
});
});
}
/**
* Get console messages
*/
getConsoleMessages(): ConsoleMessage[] {
return this.consoleMessages;
}
/**
* Clear console messages
*/
clearConsoleMessages(): void {
this.consoleMessages = [];
}
/**
* Start error tracking
*/
startErrorTracking(): void {
const page = this.getPage();
page.on('pageerror', (error) => {
this.pageErrors.push({
message: error.message,
timestamp: Date.now(),
});
});
}
/**
* Get page errors
*/
getPageErrors(): PageError[] {
return this.pageErrors;
}
/**
* Clear page errors
*/
clearPageErrors(): void {
this.pageErrors = [];
}
/**
* Start HAR recording
*/
async startHarRecording(): Promise<void> {
// HAR is started at context level, flag for tracking
this.isRecordingHar = true;
}
/**
* Check if HAR recording
*/
isHarRecording(): boolean {
return this.isRecordingHar;
}
/**
* Set offline mode
*/
async setOffline(offline: boolean): Promise<void> {
const context = this.contexts[0];
if (context) {
await context.setOffline(offline);
}
}
/**
* Set extra HTTP headers (global - all requests)
*/
async setExtraHeaders(headers: Record<string, string>): Promise<void> {
const context = this.contexts[0];
if (context) {
await context.setExtraHTTPHeaders(headers);
}
}
/**
* Set scoped HTTP headers (only for requests matching the origin)
* Uses route interception to add headers only to matching requests
*/
async setScopedHeaders(origin: string, headers: Record<string, string>): Promise<void> {
const page = this.getPage();
// Build URL pattern from origin (e.g., "api.example.com" -> "**://api.example.com/**")
// Handle both full URLs and just hostnames
let urlPattern: string;
try {
const url = new URL(origin.startsWith('http') ? origin : `https://${origin}`);
// Match any protocol, the host, and any path
urlPattern = `**://${url.host}/**`;
} catch {
// If parsing fails, treat as hostname pattern
urlPattern = `**://${origin}/**`;
}
// Remove existing route for this origin if any
const existingHandler = this.scopedHeaderRoutes.get(urlPattern);
if (existingHandler) {
await page.unroute(urlPattern, existingHandler);
}
// Create handler that adds headers to matching requests
const handler = async (route: Route) => {
const requestHeaders = route.request().headers();
await route.continue({
headers: safeHeaderMerge(requestHeaders, headers),
});
};
// Store and register the route
this.scopedHeaderRoutes.set(urlPattern, handler);
await page.route(urlPattern, handler);
}
/**
* Clear scoped headers for an origin (or all if no origin specified)
*/
async clearScopedHeaders(origin?: string): Promise<void> {
const page = this.getPage();
if (origin) {
let urlPattern: string;
try {
const url = new URL(origin.startsWith('http') ? origin : `https://${origin}`);
urlPattern = `**://${url.host}/**`;
} catch {
urlPattern = `**://${origin}/**`;
}
const handler = this.scopedHeaderRoutes.get(urlPattern);
if (handler) {
await page.unroute(urlPattern, handler);
this.scopedHeaderRoutes.delete(urlPattern);
}
} else {
// Clear all scoped header routes
for (const [pattern, handler] of this.scopedHeaderRoutes) {
await page.unroute(pattern, handler);
}
this.scopedHeaderRoutes.clear();
}
}
/**
* Start tracing
*/
async startTracing(options: { screenshots?: boolean; snapshots?: boolean }): Promise<void> {
const context = this.contexts[0];
if (context) {
await context.tracing.start({
screenshots: options.screenshots ?? true,
snapshots: options.snapshots ?? true,
});
}
}
/**
* Stop tracing and save
*/
async stopTracing(path?: string): Promise<void> {
const context = this.contexts[0];
if (context) {
await context.tracing.stop(path ? { path } : undefined);
}
}
/**
* Get the current browser context (first context)
*/
getContext(): BrowserContext | null {
return this.contexts[0] ?? null;
}
/**
* Save storage state (cookies, localStorage, etc.)
*/
async saveStorageState(path: string): Promise<void> {
const context = this.contexts[0];
if (context) {
await context.storageState({ path });
}
}
/**
* Get all pages
*/
getPages(): Page[] {
return this.pages;
}
/**
* Get current page index
*/
getActiveIndex(): number {
return this.activePageIndex;
}
/**
* Get the current browser instance
*/
getBrowser(): Browser | null {
return this.browser;
}
/**
* Check if an existing CDP connection is still alive
* by verifying we can access browser contexts and that at least one has pages
*/
private isCdpConnectionAlive(): boolean {
if (!this.browser) return false;
try {
const contexts = this.browser.contexts();
if (contexts.length === 0) return false;
return contexts.some((context) => context.pages().length > 0);
} catch {
return false;
}
}
/**
* Check if CDP connection needs to be re-established
*/
private needsCdpReconnect(cdpEndpoint: string): boolean {
if (!this.browser?.isConnected()) return true;
if (this.cdpEndpoint !== cdpEndpoint) return true;
if (!this.isCdpConnectionAlive()) return true;
return false;
}
/**
* Close a Browserbase session via API
*/
private async closeBrowserbaseSession(sessionId: string, apiKey: string): Promise<void> {
await fetch(`https://api.browserbase.com/v1/sessions/${sessionId}`, {
method: 'DELETE',
headers: {
'X-BB-API-Key': apiKey,
},
});
}
/**
* Close a Browser Use session via API
*/
private async closeBrowserUseSession(sessionId: string, apiKey: string): Promise<void> {
const response = await fetch(`https://api.browser-use.com/api/v2/browsers/${sessionId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'X-Browser-Use-API-Key': apiKey,
},
body: JSON.stringify({ action: 'stop' }),
});
if (!response.ok) {
throw new Error(`Failed to close Browser Use session: ${response.statusText}`);
}
}
/**
* Close a Kernel session via API
*/
private async closeKernelSession(sessionId: string, apiKey: string): Promise<void> {
const response = await fetch(`https://api.onkernel.com/browsers/${sessionId}`, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${apiKey}`,
},
});
if (!response.ok) {
throw new Error(`Failed to close Kernel session: ${response.statusText}`);
}
}
/**
* Connect to Browserbase remote browser via CDP.
* Requires BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID environment variables.
*/
private async connectToBrowserbase(): Promise<void> {
const browserbaseApiKey = process.env.BROWSERBASE_API_KEY;
const browserbaseProjectId = process.env.BROWSERBASE_PROJECT_ID;
if (!browserbaseApiKey || !browserbaseProjectId) {
throw new Error(
'BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID are required when using browserbase as a provider'
);
}
const response = await fetch('https://api.browserbase.com/v1/sessions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-BB-API-Key': browserbaseApiKey,
},
body: JSON.stringify({
projectId: browserbaseProjectId,
}),
});
if (!response.ok) {
throw new Error(`Failed to create Browserbase session: ${response.statusText}`);
}
const session = (await response.json()) as { id: string; connectUrl: string };
const browser = await chromium.connectOverCDP(session.connectUrl).catch(() => {
throw new Error('Failed to connect to Browserbase session via CDP');
});
try {
const contexts = browser.contexts();
if (contexts.length === 0) {
throw new Error('No browser context found in Browserbase session');
}
const context = contexts[0];
const pages = context.pages();
const page = pages[0] ?? (await context.newPage());
this.browserbaseSessionId = session.id;
this.browserbaseApiKey = browserbaseApiKey;
this.browser = browser;
context.setDefaultTimeout(10000);
this.contexts.push(context);
this.setupContextTracking(context);
await this.ensureDomainFilter(context);
await this.sanitizeExistingPages([page]);
this.pages.push(page);
this.activePageIndex = 0;
this.setupPageTracking(page);
} catch (error) {
await this.closeBrowserbaseSession(session.id, browserbaseApiKey).catch((sessionError) => {
console.error('Failed to close Browserbase session during cleanup:', sessionError);
});
throw error;
}
}
/**
* Find or create a Kernel profile by name.
* Returns the profile object if successful.
*/
private async findOrCreateKernelProfile(
profileName: string,
apiKey: string
): Promise<{ name: string }> {
// First, try to get the existing profile
const getResponse = await fetch(
`https://api.onkernel.com/profiles/${encodeURIComponent(profileName)}`,
{
method: 'GET',
headers: {
Authorization: `Bearer ${apiKey}`,
},
}
);
if (getResponse.ok) {
// Profile exists, return it
return { name: profileName };
}
if (getResponse.status !== 404) {
throw new Error(`Failed to check Kernel profile: ${getResponse.statusText}`);
}
// Profile doesn't exist, create it
const createResponse = await fetch('https://api.onkernel.com/profiles', {