agent-browser-stealth 0.14.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.
Files changed (77) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +1219 -0
  3. package/bin/agent-browser-darwin-arm64 +0 -0
  4. package/bin/agent-browser-local +0 -0
  5. package/bin/agent-browser.js +109 -0
  6. package/dist/actions.d.ts +17 -0
  7. package/dist/actions.d.ts.map +1 -0
  8. package/dist/actions.js +1917 -0
  9. package/dist/actions.js.map +1 -0
  10. package/dist/browser.d.ts +598 -0
  11. package/dist/browser.d.ts.map +1 -0
  12. package/dist/browser.js +2287 -0
  13. package/dist/browser.js.map +1 -0
  14. package/dist/daemon.d.ts +66 -0
  15. package/dist/daemon.d.ts.map +1 -0
  16. package/dist/daemon.js +603 -0
  17. package/dist/daemon.js.map +1 -0
  18. package/dist/diff.d.ts +18 -0
  19. package/dist/diff.d.ts.map +1 -0
  20. package/dist/diff.js +271 -0
  21. package/dist/diff.js.map +1 -0
  22. package/dist/encryption.d.ts +50 -0
  23. package/dist/encryption.d.ts.map +1 -0
  24. package/dist/encryption.js +85 -0
  25. package/dist/encryption.js.map +1 -0
  26. package/dist/ios-actions.d.ts +11 -0
  27. package/dist/ios-actions.d.ts.map +1 -0
  28. package/dist/ios-actions.js +228 -0
  29. package/dist/ios-actions.js.map +1 -0
  30. package/dist/ios-manager.d.ts +266 -0
  31. package/dist/ios-manager.d.ts.map +1 -0
  32. package/dist/ios-manager.js +1073 -0
  33. package/dist/ios-manager.js.map +1 -0
  34. package/dist/protocol.d.ts +26 -0
  35. package/dist/protocol.d.ts.map +1 -0
  36. package/dist/protocol.js +935 -0
  37. package/dist/protocol.js.map +1 -0
  38. package/dist/snapshot.d.ts +67 -0
  39. package/dist/snapshot.d.ts.map +1 -0
  40. package/dist/snapshot.js +514 -0
  41. package/dist/snapshot.js.map +1 -0
  42. package/dist/state-utils.d.ts +77 -0
  43. package/dist/state-utils.d.ts.map +1 -0
  44. package/dist/state-utils.js +178 -0
  45. package/dist/state-utils.js.map +1 -0
  46. package/dist/stealth.d.ts +22 -0
  47. package/dist/stealth.d.ts.map +1 -0
  48. package/dist/stealth.js +614 -0
  49. package/dist/stealth.js.map +1 -0
  50. package/dist/stream-server.d.ts +117 -0
  51. package/dist/stream-server.d.ts.map +1 -0
  52. package/dist/stream-server.js +309 -0
  53. package/dist/stream-server.js.map +1 -0
  54. package/dist/types.d.ts +855 -0
  55. package/dist/types.d.ts.map +1 -0
  56. package/dist/types.js +2 -0
  57. package/dist/types.js.map +1 -0
  58. package/package.json +85 -0
  59. package/scripts/build-all-platforms.sh +68 -0
  60. package/scripts/check-creepjs-headless.js +137 -0
  61. package/scripts/check-sannysoft-webdriver.js +112 -0
  62. package/scripts/check-version-sync.js +39 -0
  63. package/scripts/copy-native.js +36 -0
  64. package/scripts/postinstall.js +275 -0
  65. package/scripts/sync-upstream.sh +142 -0
  66. package/scripts/sync-version.js +69 -0
  67. package/skills/agent-browser/SKILL.md +464 -0
  68. package/skills/agent-browser/references/authentication.md +202 -0
  69. package/skills/agent-browser/references/commands.md +263 -0
  70. package/skills/agent-browser/references/profiling.md +120 -0
  71. package/skills/agent-browser/references/proxy-support.md +194 -0
  72. package/skills/agent-browser/references/session-management.md +193 -0
  73. package/skills/agent-browser/references/snapshot-refs.md +194 -0
  74. package/skills/agent-browser/references/video-recording.md +173 -0
  75. package/skills/agent-browser/templates/authenticated-session.sh +100 -0
  76. package/skills/agent-browser/templates/capture-workflow.sh +69 -0
  77. package/skills/agent-browser/templates/form-automation.sh +62 -0
@@ -0,0 +1,2287 @@
1
+ import { chromium, firefox, webkit, devices, } from 'playwright-core';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { existsSync, mkdirSync, rmSync, readFileSync } from 'node:fs';
5
+ import { writeFile, mkdir } from 'node:fs/promises';
6
+ import { getEnhancedSnapshot, parseRef } from './snapshot.js';
7
+ import { safeHeaderMerge } from './state-utils.js';
8
+ import { getEncryptionKey, isEncryptedPayload, decryptData, ENCRYPTION_KEY_ENV, } from './state-utils.js';
9
+ import { STEALTH_CHROMIUM_ARGS, applyStealthScripts, } from './stealth.js';
10
+ /**
11
+ * Returns the default Playwright timeout in milliseconds for standard operations.
12
+ * Can be overridden via the AGENT_BROWSER_DEFAULT_TIMEOUT environment variable.
13
+ * Default is 25s, which is below the CLI's 30s IPC read timeout to ensure
14
+ * Playwright errors are returned before the CLI gives up with EAGAIN.
15
+ * CDP and recording contexts use a shorter fixed timeout (10s) and are not affected.
16
+ */
17
+ export function getDefaultTimeout() {
18
+ const envValue = process.env.AGENT_BROWSER_DEFAULT_TIMEOUT;
19
+ if (envValue) {
20
+ const parsed = parseInt(envValue, 10);
21
+ if (!isNaN(parsed) && parsed >= 1000) {
22
+ return parsed;
23
+ }
24
+ }
25
+ return 25000;
26
+ }
27
+ /**
28
+ * Manages the Playwright browser lifecycle with multiple tabs/windows
29
+ */
30
+ export class BrowserManager {
31
+ browser = null;
32
+ cdpEndpoint = null; // stores port number or full URL
33
+ isPersistentContext = false;
34
+ browserbaseSessionId = null;
35
+ browserbaseApiKey = null;
36
+ browserUseSessionId = null;
37
+ browserUseApiKey = null;
38
+ kernelSessionId = null;
39
+ kernelApiKey = null;
40
+ contexts = [];
41
+ pages = [];
42
+ activePageIndex = 0;
43
+ activeFrame = null;
44
+ dialogHandler = null;
45
+ trackedRequests = [];
46
+ routes = new Map();
47
+ consoleMessages = [];
48
+ pageErrors = [];
49
+ isRecordingHar = false;
50
+ refMap = {};
51
+ lastSnapshot = '';
52
+ scopedHeaderRoutes = new Map();
53
+ colorScheme = null;
54
+ stealthEnabled = false;
55
+ stealthConnectionKind = 'local';
56
+ contextLocale = undefined;
57
+ contextTimezoneId = undefined;
58
+ contextHeaders = undefined;
59
+ contextUserAgent = undefined;
60
+ /**
61
+ * Set the persistent color scheme preference.
62
+ * Applied automatically to all new pages and contexts.
63
+ */
64
+ setColorScheme(scheme) {
65
+ this.colorScheme = scheme;
66
+ }
67
+ /**
68
+ * Centralized stealth policy so launch mode semantics stay consistent.
69
+ * Local Chromium gets args + init scripts; CDP/providers get init scripts only.
70
+ */
71
+ getStealthPolicy(browserType = 'chromium') {
72
+ if (!this.stealthEnabled) {
73
+ return {
74
+ enabled: false,
75
+ connectionKind: this.stealthConnectionKind,
76
+ applyChromiumArgs: false,
77
+ applyInitScripts: false,
78
+ providerManaged: false,
79
+ capabilities: [],
80
+ };
81
+ }
82
+ const applyChromiumArgs = this.stealthConnectionKind === 'local' && browserType === 'chromium';
83
+ const applyInitScripts = true;
84
+ const providerManaged = this.stealthConnectionKind === 'provider-kernel';
85
+ const capabilities = [];
86
+ if (applyChromiumArgs) {
87
+ capabilities.push('chromium-launch-args');
88
+ }
89
+ if (applyInitScripts) {
90
+ capabilities.push('context-init-scripts');
91
+ }
92
+ if (providerManaged) {
93
+ capabilities.push('provider-managed-stealth');
94
+ }
95
+ return {
96
+ enabled: true,
97
+ connectionKind: this.stealthConnectionKind,
98
+ applyChromiumArgs,
99
+ applyInitScripts,
100
+ providerManaged,
101
+ capabilities,
102
+ };
103
+ }
104
+ logStealthPolicy(phase, browserType = 'chromium') {
105
+ if (process.env.AGENT_BROWSER_DEBUG !== '1')
106
+ return;
107
+ const policy = this.getStealthPolicy(browserType);
108
+ const capabilities = policy.capabilities.length > 0 ? policy.capabilities.join(', ') : 'none';
109
+ console.error(`[DEBUG] Stealth ${phase}: enabled=${policy.enabled} connection=${policy.connectionKind} capabilities=${capabilities}`);
110
+ }
111
+ getStealthStatus(browserType = 'chromium') {
112
+ const policy = this.getStealthPolicy(browserType);
113
+ return {
114
+ enabled: policy.enabled,
115
+ connectionKind: policy.connectionKind,
116
+ capabilities: policy.capabilities,
117
+ providerManaged: policy.providerManaged,
118
+ };
119
+ }
120
+ normalizeLocaleTag(locale) {
121
+ if (!locale)
122
+ return undefined;
123
+ const cleaned = locale.trim().split(',')[0]?.split(';')[0]?.replace(/_/g, '-');
124
+ if (!cleaned)
125
+ return undefined;
126
+ try {
127
+ return new Intl.Locale(cleaned).toString();
128
+ }
129
+ catch {
130
+ return undefined;
131
+ }
132
+ }
133
+ buildAcceptLanguageHeader(locale) {
134
+ const baseLanguage = locale.split('-')[0];
135
+ if (!baseLanguage || baseLanguage === locale) {
136
+ return `${locale};q=0.9`;
137
+ }
138
+ return `${locale},${baseLanguage};q=0.9`;
139
+ }
140
+ getHeaderValue(headers, name) {
141
+ if (!headers)
142
+ return undefined;
143
+ const target = name.toLowerCase();
144
+ for (const [key, value] of Object.entries(headers)) {
145
+ if (key.toLowerCase() === target)
146
+ return value;
147
+ }
148
+ return undefined;
149
+ }
150
+ resolveStealthLocale(headers) {
151
+ const headerLocale = this.getHeaderValue(headers, 'accept-language');
152
+ const normalizedHeaderLocale = this.normalizeLocaleTag(headerLocale);
153
+ if (normalizedHeaderLocale)
154
+ return normalizedHeaderLocale;
155
+ const candidates = [
156
+ process.env.AGENT_BROWSER_LOCALE,
157
+ process.env.LC_ALL,
158
+ process.env.LC_MESSAGES,
159
+ process.env.LANG,
160
+ Intl.DateTimeFormat().resolvedOptions().locale,
161
+ ];
162
+ for (const candidate of candidates) {
163
+ const normalized = this.normalizeLocaleTag(candidate);
164
+ if (normalized)
165
+ return normalized;
166
+ }
167
+ return 'en-US';
168
+ }
169
+ resolveStealthTimezoneId() {
170
+ const candidates = [
171
+ process.env.AGENT_BROWSER_TIMEZONE,
172
+ process.env.TZ,
173
+ Intl.DateTimeFormat().resolvedOptions().timeZone,
174
+ ];
175
+ for (const value of candidates) {
176
+ const timezone = value?.trim();
177
+ if (!timezone)
178
+ continue;
179
+ if (timezone === 'UTC' || timezone.includes('/'))
180
+ return timezone;
181
+ }
182
+ return undefined;
183
+ }
184
+ buildStealthContextDefaults(policy, headers) {
185
+ if (!policy.enabled) {
186
+ return { extraHTTPHeaders: headers };
187
+ }
188
+ const locale = this.resolveStealthLocale(headers);
189
+ const timezoneId = this.resolveStealthTimezoneId();
190
+ const hasAcceptLanguage = this.getHeaderValue(headers, 'accept-language') !== undefined;
191
+ const extraHTTPHeaders = hasAcceptLanguage
192
+ ? headers
193
+ : {
194
+ ...(headers ?? {}),
195
+ 'Accept-Language': this.buildAcceptLanguageHeader(locale),
196
+ };
197
+ return {
198
+ locale,
199
+ timezoneId,
200
+ extraHTTPHeaders,
201
+ };
202
+ }
203
+ extractChromiumVersion(versionText) {
204
+ const match = versionText.match(/(\d+\.\d+\.\d+\.\d+)/);
205
+ return match?.[1];
206
+ }
207
+ buildStealthChromiumUserAgent(chromeVersion) {
208
+ const platform = os.platform();
209
+ let osToken = 'X11; Linux x86_64';
210
+ if (platform === 'darwin') {
211
+ osToken = 'Macintosh; Intel Mac OS X 10_15_7';
212
+ }
213
+ else if (platform === 'win32') {
214
+ osToken = 'Windows NT 10.0; Win64; x64';
215
+ }
216
+ return (`Mozilla/5.0 (${osToken}) AppleWebKit/537.36 ` +
217
+ `(KHTML, like Gecko) Chrome/${chromeVersion} Safari/537.36`);
218
+ }
219
+ getStealthUserAgentVersionHint() {
220
+ const deviceUA = devices['Desktop Chrome']?.userAgent;
221
+ if (!deviceUA)
222
+ return undefined;
223
+ return this.extractChromiumVersion(deviceUA);
224
+ }
225
+ /**
226
+ * Apply context init-script stealth patches when policy allows.
227
+ */
228
+ async applyStealthIfEnabled(context, options = {}) {
229
+ const policy = this.getStealthPolicy();
230
+ if (!policy.applyInitScripts)
231
+ return;
232
+ await applyStealthScripts(context, options);
233
+ this.logStealthPolicy('init-script applied');
234
+ }
235
+ // CDP session for screencast and input injection
236
+ cdpSession = null;
237
+ screencastActive = false;
238
+ screencastSessionId = 0;
239
+ frameCallback = null;
240
+ screencastFrameHandler = null;
241
+ // Video recording (Playwright native)
242
+ recordingContext = null;
243
+ recordingPage = null;
244
+ recordingOutputPath = '';
245
+ recordingTempDir = '';
246
+ launchWarnings = [];
247
+ /**
248
+ * Get and clear launch warnings (e.g., decryption failures)
249
+ */
250
+ getAndClearWarnings() {
251
+ const warnings = this.launchWarnings;
252
+ this.launchWarnings = [];
253
+ return warnings;
254
+ }
255
+ // CDP profiling state
256
+ static MAX_PROFILE_EVENTS = 5_000_000;
257
+ profilingActive = false;
258
+ profileChunks = [];
259
+ profileEventsDropped = false;
260
+ profileCompleteResolver = null;
261
+ profileDataHandler = null;
262
+ profileCompleteHandler = null;
263
+ /**
264
+ * Check if browser is launched
265
+ */
266
+ isLaunched() {
267
+ return this.browser !== null || this.isPersistentContext;
268
+ }
269
+ /**
270
+ * Get enhanced snapshot with refs and cache the ref map
271
+ */
272
+ async getSnapshot(options) {
273
+ const page = this.getPage();
274
+ const snapshot = await getEnhancedSnapshot(page, options);
275
+ this.refMap = snapshot.refs;
276
+ this.lastSnapshot = snapshot.tree;
277
+ return snapshot;
278
+ }
279
+ /**
280
+ * Get the last snapshot tree text (empty string if no snapshot has been taken)
281
+ */
282
+ getLastSnapshot() {
283
+ return this.lastSnapshot;
284
+ }
285
+ /**
286
+ * Update the stored snapshot (used by diff to keep the baseline current)
287
+ */
288
+ setLastSnapshot(snapshot) {
289
+ this.lastSnapshot = snapshot;
290
+ }
291
+ /**
292
+ * Get the cached ref map from last snapshot
293
+ */
294
+ getRefMap() {
295
+ return this.refMap;
296
+ }
297
+ /**
298
+ * Get a locator from a ref (e.g., "e1", "@e1", "ref=e1")
299
+ * Returns null if ref doesn't exist or is invalid
300
+ */
301
+ getLocatorFromRef(refArg) {
302
+ const ref = parseRef(refArg);
303
+ if (!ref)
304
+ return null;
305
+ const refData = this.refMap[ref];
306
+ if (!refData)
307
+ return null;
308
+ const page = this.getPage();
309
+ // Check if this is a cursor-interactive element (uses CSS selector, not ARIA role)
310
+ // These have pseudo-roles 'clickable' or 'focusable' and a CSS selector
311
+ if (refData.role === 'clickable' || refData.role === 'focusable') {
312
+ // The selector is a CSS selector, use it directly
313
+ return page.locator(refData.selector);
314
+ }
315
+ // Build locator with exact: true to avoid substring matches
316
+ let locator;
317
+ if (refData.name) {
318
+ locator = page.getByRole(refData.role, { name: refData.name, exact: true });
319
+ }
320
+ else {
321
+ locator = page.getByRole(refData.role);
322
+ }
323
+ // If an nth index is stored (for disambiguation), use it
324
+ if (refData.nth !== undefined) {
325
+ locator = locator.nth(refData.nth);
326
+ }
327
+ return locator;
328
+ }
329
+ /**
330
+ * Check if a selector looks like a ref
331
+ */
332
+ isRef(selector) {
333
+ return parseRef(selector) !== null;
334
+ }
335
+ /**
336
+ * Get locator - supports both refs and regular selectors
337
+ */
338
+ getLocator(selectorOrRef) {
339
+ // Check if it's a ref first
340
+ const locator = this.getLocatorFromRef(selectorOrRef);
341
+ if (locator)
342
+ return locator;
343
+ // Otherwise treat as regular selector
344
+ const page = this.getPage();
345
+ return page.locator(selectorOrRef);
346
+ }
347
+ /**
348
+ * Check if the browser has any usable pages
349
+ */
350
+ hasPages() {
351
+ return this.pages.length > 0;
352
+ }
353
+ /**
354
+ * Ensure at least one page exists. If the browser is launched but all pages
355
+ * were closed (stale session), creates a new page on the existing context.
356
+ * No-op if pages already exist.
357
+ */
358
+ async ensurePage() {
359
+ if (this.pages.length > 0)
360
+ return;
361
+ if (!this.browser && !this.isPersistentContext)
362
+ return;
363
+ // Use the last existing context, or create a new one
364
+ let context;
365
+ if (this.contexts.length > 0) {
366
+ context = this.contexts[this.contexts.length - 1];
367
+ }
368
+ else if (this.browser) {
369
+ context = await this.browser.newContext({
370
+ ...(this.contextHeaders && { extraHTTPHeaders: this.contextHeaders }),
371
+ ...(this.contextUserAgent && { userAgent: this.contextUserAgent }),
372
+ ...(this.contextLocale && { locale: this.contextLocale }),
373
+ ...(this.contextTimezoneId && { timezoneId: this.contextTimezoneId }),
374
+ ...(this.colorScheme && { colorScheme: this.colorScheme }),
375
+ });
376
+ await this.applyStealthIfEnabled(context, { locale: this.contextLocale });
377
+ context.setDefaultTimeout(getDefaultTimeout());
378
+ this.contexts.push(context);
379
+ this.setupContextTracking(context);
380
+ }
381
+ else {
382
+ return;
383
+ }
384
+ const page = await context.newPage();
385
+ if (!this.pages.includes(page)) {
386
+ this.pages.push(page);
387
+ this.setupPageTracking(page);
388
+ }
389
+ this.activePageIndex = this.pages.length - 1;
390
+ }
391
+ /**
392
+ * Get the current active page, throws if not launched
393
+ */
394
+ getPage() {
395
+ if (this.pages.length === 0) {
396
+ throw new Error('Browser not launched. Call launch first.');
397
+ }
398
+ return this.pages[this.activePageIndex];
399
+ }
400
+ /**
401
+ * Get the current frame (or page's main frame if no frame is selected)
402
+ */
403
+ getFrame() {
404
+ if (this.activeFrame) {
405
+ return this.activeFrame;
406
+ }
407
+ return this.getPage().mainFrame();
408
+ }
409
+ /**
410
+ * Switch to a frame by selector, name, or URL
411
+ */
412
+ async switchToFrame(options) {
413
+ const page = this.getPage();
414
+ if (options.selector) {
415
+ const frameElement = await page.$(options.selector);
416
+ if (!frameElement) {
417
+ throw new Error(`Frame not found: ${options.selector}`);
418
+ }
419
+ const frame = await frameElement.contentFrame();
420
+ if (!frame) {
421
+ throw new Error(`Element is not a frame: ${options.selector}`);
422
+ }
423
+ this.activeFrame = frame;
424
+ }
425
+ else if (options.name) {
426
+ const frame = page.frame({ name: options.name });
427
+ if (!frame) {
428
+ throw new Error(`Frame not found with name: ${options.name}`);
429
+ }
430
+ this.activeFrame = frame;
431
+ }
432
+ else if (options.url) {
433
+ const frame = page.frame({ url: options.url });
434
+ if (!frame) {
435
+ throw new Error(`Frame not found with URL: ${options.url}`);
436
+ }
437
+ this.activeFrame = frame;
438
+ }
439
+ }
440
+ /**
441
+ * Switch back to main frame
442
+ */
443
+ switchToMainFrame() {
444
+ this.activeFrame = null;
445
+ }
446
+ /**
447
+ * Set up dialog handler
448
+ */
449
+ setDialogHandler(response, promptText) {
450
+ const page = this.getPage();
451
+ // Remove existing handler if any
452
+ if (this.dialogHandler) {
453
+ page.removeListener('dialog', this.dialogHandler);
454
+ }
455
+ this.dialogHandler = async (dialog) => {
456
+ if (response === 'accept') {
457
+ await dialog.accept(promptText);
458
+ }
459
+ else {
460
+ await dialog.dismiss();
461
+ }
462
+ };
463
+ page.on('dialog', this.dialogHandler);
464
+ }
465
+ /**
466
+ * Clear dialog handler
467
+ */
468
+ clearDialogHandler() {
469
+ if (this.dialogHandler) {
470
+ const page = this.getPage();
471
+ page.removeListener('dialog', this.dialogHandler);
472
+ this.dialogHandler = null;
473
+ }
474
+ }
475
+ /**
476
+ * Start tracking requests
477
+ */
478
+ startRequestTracking() {
479
+ const page = this.getPage();
480
+ page.on('request', (request) => {
481
+ this.trackedRequests.push({
482
+ url: request.url(),
483
+ method: request.method(),
484
+ headers: request.headers(),
485
+ timestamp: Date.now(),
486
+ resourceType: request.resourceType(),
487
+ });
488
+ });
489
+ }
490
+ /**
491
+ * Get tracked requests
492
+ */
493
+ getRequests(filter) {
494
+ if (filter) {
495
+ return this.trackedRequests.filter((r) => r.url.includes(filter));
496
+ }
497
+ return this.trackedRequests;
498
+ }
499
+ /**
500
+ * Clear tracked requests
501
+ */
502
+ clearRequests() {
503
+ this.trackedRequests = [];
504
+ }
505
+ /**
506
+ * Add a route to intercept requests
507
+ */
508
+ async addRoute(url, options) {
509
+ const page = this.getPage();
510
+ const handler = async (route) => {
511
+ if (options.abort) {
512
+ await route.abort();
513
+ }
514
+ else if (options.response) {
515
+ await route.fulfill({
516
+ status: options.response.status ?? 200,
517
+ body: options.response.body ?? '',
518
+ contentType: options.response.contentType ?? 'text/plain',
519
+ headers: options.response.headers,
520
+ });
521
+ }
522
+ else {
523
+ await route.continue();
524
+ }
525
+ };
526
+ this.routes.set(url, handler);
527
+ await page.route(url, handler);
528
+ }
529
+ /**
530
+ * Remove a route
531
+ */
532
+ async removeRoute(url) {
533
+ const page = this.getPage();
534
+ if (url) {
535
+ const handler = this.routes.get(url);
536
+ if (handler) {
537
+ await page.unroute(url, handler);
538
+ this.routes.delete(url);
539
+ }
540
+ }
541
+ else {
542
+ // Remove all routes
543
+ for (const [routeUrl, handler] of this.routes) {
544
+ await page.unroute(routeUrl, handler);
545
+ }
546
+ this.routes.clear();
547
+ }
548
+ }
549
+ /**
550
+ * Set geolocation
551
+ */
552
+ async setGeolocation(latitude, longitude, accuracy) {
553
+ const context = this.contexts[0];
554
+ if (context) {
555
+ await context.setGeolocation({ latitude, longitude, accuracy });
556
+ }
557
+ }
558
+ /**
559
+ * Set permissions
560
+ */
561
+ async setPermissions(permissions, grant) {
562
+ const context = this.contexts[0];
563
+ if (context) {
564
+ if (grant) {
565
+ await context.grantPermissions(permissions);
566
+ }
567
+ else {
568
+ await context.clearPermissions();
569
+ }
570
+ }
571
+ }
572
+ /**
573
+ * Set viewport
574
+ */
575
+ async setViewport(width, height) {
576
+ const page = this.getPage();
577
+ await page.setViewportSize({ width, height });
578
+ }
579
+ /**
580
+ * Set device scale factor (devicePixelRatio) via CDP
581
+ * This sets window.devicePixelRatio which affects how the page renders and responds to media queries
582
+ *
583
+ * Note: When using CDP to set deviceScaleFactor, screenshots will be at logical pixel dimensions
584
+ * (viewport size), not physical pixel dimensions (viewport × scale). This is a Playwright limitation
585
+ * when using CDP emulation on existing contexts. For true HiDPI screenshots with physical pixels,
586
+ * deviceScaleFactor must be set at context creation time.
587
+ *
588
+ * Must be called after setViewport to work correctly
589
+ */
590
+ async setDeviceScaleFactor(deviceScaleFactor, width, height, mobile = false) {
591
+ const cdp = await this.getCDPSession();
592
+ await cdp.send('Emulation.setDeviceMetricsOverride', {
593
+ width,
594
+ height,
595
+ deviceScaleFactor,
596
+ mobile,
597
+ });
598
+ }
599
+ /**
600
+ * Clear device metrics override to restore default devicePixelRatio
601
+ */
602
+ async clearDeviceMetricsOverride() {
603
+ const cdp = await this.getCDPSession();
604
+ await cdp.send('Emulation.clearDeviceMetricsOverride');
605
+ }
606
+ /**
607
+ * Get device descriptor
608
+ */
609
+ getDevice(deviceName) {
610
+ return devices[deviceName];
611
+ }
612
+ /**
613
+ * List available devices
614
+ */
615
+ listDevices() {
616
+ return Object.keys(devices);
617
+ }
618
+ /**
619
+ * Start console message tracking
620
+ */
621
+ startConsoleTracking() {
622
+ const page = this.getPage();
623
+ page.on('console', (msg) => {
624
+ this.consoleMessages.push({
625
+ type: msg.type(),
626
+ text: msg.text(),
627
+ timestamp: Date.now(),
628
+ });
629
+ });
630
+ }
631
+ /**
632
+ * Get console messages
633
+ */
634
+ getConsoleMessages() {
635
+ return this.consoleMessages;
636
+ }
637
+ /**
638
+ * Clear console messages
639
+ */
640
+ clearConsoleMessages() {
641
+ this.consoleMessages = [];
642
+ }
643
+ /**
644
+ * Start error tracking
645
+ */
646
+ startErrorTracking() {
647
+ const page = this.getPage();
648
+ page.on('pageerror', (error) => {
649
+ this.pageErrors.push({
650
+ message: error.message,
651
+ timestamp: Date.now(),
652
+ });
653
+ });
654
+ }
655
+ /**
656
+ * Get page errors
657
+ */
658
+ getPageErrors() {
659
+ return this.pageErrors;
660
+ }
661
+ /**
662
+ * Clear page errors
663
+ */
664
+ clearPageErrors() {
665
+ this.pageErrors = [];
666
+ }
667
+ /**
668
+ * Start HAR recording
669
+ */
670
+ async startHarRecording() {
671
+ // HAR is started at context level, flag for tracking
672
+ this.isRecordingHar = true;
673
+ }
674
+ /**
675
+ * Check if HAR recording
676
+ */
677
+ isHarRecording() {
678
+ return this.isRecordingHar;
679
+ }
680
+ /**
681
+ * Set offline mode
682
+ */
683
+ async setOffline(offline) {
684
+ const context = this.contexts[0];
685
+ if (context) {
686
+ await context.setOffline(offline);
687
+ }
688
+ }
689
+ /**
690
+ * Set extra HTTP headers (global - all requests)
691
+ */
692
+ async setExtraHeaders(headers) {
693
+ const context = this.contexts[0];
694
+ if (context) {
695
+ await context.setExtraHTTPHeaders(headers);
696
+ }
697
+ }
698
+ /**
699
+ * Set scoped HTTP headers (only for requests matching the origin)
700
+ * Uses route interception to add headers only to matching requests
701
+ */
702
+ async setScopedHeaders(origin, headers) {
703
+ const page = this.getPage();
704
+ // Build URL pattern from origin (e.g., "api.example.com" -> "**://api.example.com/**")
705
+ // Handle both full URLs and just hostnames
706
+ let urlPattern;
707
+ try {
708
+ const url = new URL(origin.startsWith('http') ? origin : `https://${origin}`);
709
+ // Match any protocol, the host, and any path
710
+ urlPattern = `**://${url.host}/**`;
711
+ }
712
+ catch {
713
+ // If parsing fails, treat as hostname pattern
714
+ urlPattern = `**://${origin}/**`;
715
+ }
716
+ // Remove existing route for this origin if any
717
+ const existingHandler = this.scopedHeaderRoutes.get(urlPattern);
718
+ if (existingHandler) {
719
+ await page.unroute(urlPattern, existingHandler);
720
+ }
721
+ // Create handler that adds headers to matching requests
722
+ const handler = async (route) => {
723
+ const requestHeaders = route.request().headers();
724
+ await route.continue({
725
+ headers: safeHeaderMerge(requestHeaders, headers),
726
+ });
727
+ };
728
+ // Store and register the route
729
+ this.scopedHeaderRoutes.set(urlPattern, handler);
730
+ await page.route(urlPattern, handler);
731
+ }
732
+ /**
733
+ * Clear scoped headers for an origin (or all if no origin specified)
734
+ */
735
+ async clearScopedHeaders(origin) {
736
+ const page = this.getPage();
737
+ if (origin) {
738
+ let urlPattern;
739
+ try {
740
+ const url = new URL(origin.startsWith('http') ? origin : `https://${origin}`);
741
+ urlPattern = `**://${url.host}/**`;
742
+ }
743
+ catch {
744
+ urlPattern = `**://${origin}/**`;
745
+ }
746
+ const handler = this.scopedHeaderRoutes.get(urlPattern);
747
+ if (handler) {
748
+ await page.unroute(urlPattern, handler);
749
+ this.scopedHeaderRoutes.delete(urlPattern);
750
+ }
751
+ }
752
+ else {
753
+ // Clear all scoped header routes
754
+ for (const [pattern, handler] of this.scopedHeaderRoutes) {
755
+ await page.unroute(pattern, handler);
756
+ }
757
+ this.scopedHeaderRoutes.clear();
758
+ }
759
+ }
760
+ /**
761
+ * Start tracing
762
+ */
763
+ async startTracing(options) {
764
+ const context = this.contexts[0];
765
+ if (context) {
766
+ await context.tracing.start({
767
+ screenshots: options.screenshots ?? true,
768
+ snapshots: options.snapshots ?? true,
769
+ });
770
+ }
771
+ }
772
+ /**
773
+ * Stop tracing and save
774
+ */
775
+ async stopTracing(path) {
776
+ const context = this.contexts[0];
777
+ if (context) {
778
+ await context.tracing.stop(path ? { path } : undefined);
779
+ }
780
+ }
781
+ /**
782
+ * Get the current browser context (first context)
783
+ */
784
+ getContext() {
785
+ return this.contexts[0] ?? null;
786
+ }
787
+ /**
788
+ * Save storage state (cookies, localStorage, etc.)
789
+ */
790
+ async saveStorageState(path) {
791
+ const context = this.contexts[0];
792
+ if (context) {
793
+ await context.storageState({ path });
794
+ }
795
+ }
796
+ /**
797
+ * Get all pages
798
+ */
799
+ getPages() {
800
+ return this.pages;
801
+ }
802
+ /**
803
+ * Get current page index
804
+ */
805
+ getActiveIndex() {
806
+ return this.activePageIndex;
807
+ }
808
+ /**
809
+ * Get the current browser instance
810
+ */
811
+ getBrowser() {
812
+ return this.browser;
813
+ }
814
+ /**
815
+ * Check if an existing CDP connection is still alive
816
+ * by verifying we can access browser contexts and that at least one has pages
817
+ */
818
+ isCdpConnectionAlive() {
819
+ if (!this.browser)
820
+ return false;
821
+ try {
822
+ const contexts = this.browser.contexts();
823
+ if (contexts.length === 0)
824
+ return false;
825
+ return contexts.some((context) => context.pages().length > 0);
826
+ }
827
+ catch {
828
+ return false;
829
+ }
830
+ }
831
+ /**
832
+ * Check if CDP connection needs to be re-established
833
+ */
834
+ needsCdpReconnect(cdpEndpoint) {
835
+ if (!this.browser?.isConnected())
836
+ return true;
837
+ if (this.cdpEndpoint !== cdpEndpoint)
838
+ return true;
839
+ if (!this.isCdpConnectionAlive())
840
+ return true;
841
+ return false;
842
+ }
843
+ /**
844
+ * Close a Browserbase session via API
845
+ */
846
+ async closeBrowserbaseSession(sessionId, apiKey) {
847
+ await fetch(`https://api.browserbase.com/v1/sessions/${sessionId}`, {
848
+ method: 'DELETE',
849
+ headers: {
850
+ 'X-BB-API-Key': apiKey,
851
+ },
852
+ });
853
+ }
854
+ /**
855
+ * Close a Browser Use session via API
856
+ */
857
+ async closeBrowserUseSession(sessionId, apiKey) {
858
+ const response = await fetch(`https://api.browser-use.com/api/v2/browsers/${sessionId}`, {
859
+ method: 'PATCH',
860
+ headers: {
861
+ 'Content-Type': 'application/json',
862
+ 'X-Browser-Use-API-Key': apiKey,
863
+ },
864
+ body: JSON.stringify({ action: 'stop' }),
865
+ });
866
+ if (!response.ok) {
867
+ throw new Error(`Failed to close Browser Use session: ${response.statusText}`);
868
+ }
869
+ }
870
+ /**
871
+ * Close a Kernel session via API
872
+ */
873
+ async closeKernelSession(sessionId, apiKey) {
874
+ const response = await fetch(`https://api.onkernel.com/browsers/${sessionId}`, {
875
+ method: 'DELETE',
876
+ headers: {
877
+ Authorization: `Bearer ${apiKey}`,
878
+ },
879
+ });
880
+ if (!response.ok) {
881
+ throw new Error(`Failed to close Kernel session: ${response.statusText}`);
882
+ }
883
+ }
884
+ /**
885
+ * Connect to Browserbase remote browser via CDP.
886
+ * Requires BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID environment variables.
887
+ */
888
+ async connectToBrowserbase() {
889
+ this.stealthConnectionKind = 'provider-browserbase';
890
+ const browserbaseApiKey = process.env.BROWSERBASE_API_KEY;
891
+ const browserbaseProjectId = process.env.BROWSERBASE_PROJECT_ID;
892
+ if (!browserbaseApiKey || !browserbaseProjectId) {
893
+ throw new Error('BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID are required when using browserbase as a provider');
894
+ }
895
+ const response = await fetch('https://api.browserbase.com/v1/sessions', {
896
+ method: 'POST',
897
+ headers: {
898
+ 'Content-Type': 'application/json',
899
+ 'X-BB-API-Key': browserbaseApiKey,
900
+ },
901
+ body: JSON.stringify({
902
+ projectId: browserbaseProjectId,
903
+ }),
904
+ });
905
+ if (!response.ok) {
906
+ throw new Error(`Failed to create Browserbase session: ${response.statusText}`);
907
+ }
908
+ const session = (await response.json());
909
+ const browser = await chromium.connectOverCDP(session.connectUrl).catch(() => {
910
+ throw new Error('Failed to connect to Browserbase session via CDP');
911
+ });
912
+ try {
913
+ const contexts = browser.contexts();
914
+ if (contexts.length === 0) {
915
+ throw new Error('No browser context found in Browserbase session');
916
+ }
917
+ const context = contexts[0];
918
+ await this.applyStealthIfEnabled(context, { locale: this.contextLocale });
919
+ const pages = context.pages();
920
+ const page = pages[0] ?? (await context.newPage());
921
+ this.browserbaseSessionId = session.id;
922
+ this.browserbaseApiKey = browserbaseApiKey;
923
+ this.browser = browser;
924
+ context.setDefaultTimeout(10000);
925
+ this.contexts.push(context);
926
+ this.setupContextTracking(context);
927
+ this.pages.push(page);
928
+ this.activePageIndex = 0;
929
+ this.setupPageTracking(page);
930
+ }
931
+ catch (error) {
932
+ await this.closeBrowserbaseSession(session.id, browserbaseApiKey).catch((sessionError) => {
933
+ console.error('Failed to close Browserbase session during cleanup:', sessionError);
934
+ });
935
+ throw error;
936
+ }
937
+ }
938
+ /**
939
+ * Find or create a Kernel profile by name.
940
+ * Returns the profile object if successful.
941
+ */
942
+ async findOrCreateKernelProfile(profileName, apiKey) {
943
+ // First, try to get the existing profile
944
+ const getResponse = await fetch(`https://api.onkernel.com/profiles/${encodeURIComponent(profileName)}`, {
945
+ method: 'GET',
946
+ headers: {
947
+ Authorization: `Bearer ${apiKey}`,
948
+ },
949
+ });
950
+ if (getResponse.ok) {
951
+ // Profile exists, return it
952
+ return { name: profileName };
953
+ }
954
+ if (getResponse.status !== 404) {
955
+ throw new Error(`Failed to check Kernel profile: ${getResponse.statusText}`);
956
+ }
957
+ // Profile doesn't exist, create it
958
+ const createResponse = await fetch('https://api.onkernel.com/profiles', {
959
+ method: 'POST',
960
+ headers: {
961
+ 'Content-Type': 'application/json',
962
+ Authorization: `Bearer ${apiKey}`,
963
+ },
964
+ body: JSON.stringify({ name: profileName }),
965
+ });
966
+ if (!createResponse.ok) {
967
+ throw new Error(`Failed to create Kernel profile: ${createResponse.statusText}`);
968
+ }
969
+ return { name: profileName };
970
+ }
971
+ /**
972
+ * Connect to Kernel remote browser via CDP.
973
+ * Requires KERNEL_API_KEY environment variable.
974
+ */
975
+ async connectToKernel() {
976
+ this.stealthConnectionKind = 'provider-kernel';
977
+ const kernelApiKey = process.env.KERNEL_API_KEY;
978
+ if (!kernelApiKey) {
979
+ throw new Error('KERNEL_API_KEY is required when using kernel as a provider');
980
+ }
981
+ // Find or create profile if KERNEL_PROFILE_NAME is set
982
+ const profileName = process.env.KERNEL_PROFILE_NAME;
983
+ let profileConfig;
984
+ if (profileName) {
985
+ await this.findOrCreateKernelProfile(profileName, kernelApiKey);
986
+ profileConfig = {
987
+ profile: {
988
+ name: profileName,
989
+ save_changes: true, // Save cookies/state back to the profile when session ends
990
+ },
991
+ };
992
+ }
993
+ const response = await fetch('https://api.onkernel.com/browsers', {
994
+ method: 'POST',
995
+ headers: {
996
+ 'Content-Type': 'application/json',
997
+ Authorization: `Bearer ${kernelApiKey}`,
998
+ },
999
+ body: JSON.stringify({
1000
+ // Kernel browsers are headful by default with stealth mode available
1001
+ // The user can configure these via environment variables if needed
1002
+ headless: process.env.KERNEL_HEADLESS?.toLowerCase() === 'true',
1003
+ stealth: process.env.KERNEL_STEALTH?.toLowerCase() !== 'false', // Default to stealth mode
1004
+ timeout_seconds: parseInt(process.env.KERNEL_TIMEOUT_SECONDS || '300', 10),
1005
+ // Load and save to a profile if specified
1006
+ ...profileConfig,
1007
+ }),
1008
+ });
1009
+ if (!response.ok) {
1010
+ throw new Error(`Failed to create Kernel session: ${response.statusText}`);
1011
+ }
1012
+ let session;
1013
+ try {
1014
+ session = (await response.json());
1015
+ }
1016
+ catch (error) {
1017
+ throw new Error(`Failed to parse Kernel session response: ${error instanceof Error ? error.message : String(error)}`);
1018
+ }
1019
+ if (!session.session_id || !session.cdp_ws_url) {
1020
+ throw new Error(`Invalid Kernel session response: missing ${!session.session_id ? 'session_id' : 'cdp_ws_url'}`);
1021
+ }
1022
+ const browser = await chromium.connectOverCDP(session.cdp_ws_url).catch(() => {
1023
+ throw new Error('Failed to connect to Kernel session via CDP');
1024
+ });
1025
+ try {
1026
+ const contexts = browser.contexts();
1027
+ let context;
1028
+ let page;
1029
+ // Kernel browsers launch with a default context and page
1030
+ if (contexts.length === 0) {
1031
+ context = await browser.newContext();
1032
+ await this.applyStealthIfEnabled(context, { locale: this.contextLocale });
1033
+ page = await context.newPage();
1034
+ }
1035
+ else {
1036
+ context = contexts[0];
1037
+ await this.applyStealthIfEnabled(context, { locale: this.contextLocale });
1038
+ const pages = context.pages();
1039
+ page = pages[0] ?? (await context.newPage());
1040
+ }
1041
+ this.kernelSessionId = session.session_id;
1042
+ this.kernelApiKey = kernelApiKey;
1043
+ this.browser = browser;
1044
+ context.setDefaultTimeout(getDefaultTimeout());
1045
+ this.contexts.push(context);
1046
+ this.pages.push(page);
1047
+ this.activePageIndex = 0;
1048
+ this.setupPageTracking(page);
1049
+ this.setupContextTracking(context);
1050
+ }
1051
+ catch (error) {
1052
+ await this.closeKernelSession(session.session_id, kernelApiKey).catch((sessionError) => {
1053
+ console.error('Failed to close Kernel session during cleanup:', sessionError);
1054
+ });
1055
+ throw error;
1056
+ }
1057
+ }
1058
+ /**
1059
+ * Connect to Browser Use remote browser via CDP.
1060
+ * Requires BROWSER_USE_API_KEY environment variable.
1061
+ */
1062
+ async connectToBrowserUse() {
1063
+ this.stealthConnectionKind = 'provider-browseruse';
1064
+ const browserUseApiKey = process.env.BROWSER_USE_API_KEY;
1065
+ if (!browserUseApiKey) {
1066
+ throw new Error('BROWSER_USE_API_KEY is required when using browseruse as a provider');
1067
+ }
1068
+ const response = await fetch('https://api.browser-use.com/api/v2/browsers', {
1069
+ method: 'POST',
1070
+ headers: {
1071
+ 'Content-Type': 'application/json',
1072
+ 'X-Browser-Use-API-Key': browserUseApiKey,
1073
+ },
1074
+ body: JSON.stringify({}),
1075
+ });
1076
+ if (!response.ok) {
1077
+ throw new Error(`Failed to create Browser Use session: ${response.statusText}`);
1078
+ }
1079
+ let session;
1080
+ try {
1081
+ session = (await response.json());
1082
+ }
1083
+ catch (error) {
1084
+ throw new Error(`Failed to parse Browser Use session response: ${error instanceof Error ? error.message : String(error)}`);
1085
+ }
1086
+ if (!session.id || !session.cdpUrl) {
1087
+ throw new Error(`Invalid Browser Use session response: missing ${!session.id ? 'id' : 'cdpUrl'}`);
1088
+ }
1089
+ const browser = await chromium.connectOverCDP(session.cdpUrl).catch(() => {
1090
+ throw new Error('Failed to connect to Browser Use session via CDP');
1091
+ });
1092
+ try {
1093
+ const contexts = browser.contexts();
1094
+ let context;
1095
+ let page;
1096
+ if (contexts.length === 0) {
1097
+ context = await browser.newContext();
1098
+ await this.applyStealthIfEnabled(context, { locale: this.contextLocale });
1099
+ page = await context.newPage();
1100
+ }
1101
+ else {
1102
+ context = contexts[0];
1103
+ await this.applyStealthIfEnabled(context, { locale: this.contextLocale });
1104
+ const pages = context.pages();
1105
+ page = pages[0] ?? (await context.newPage());
1106
+ }
1107
+ this.browserUseSessionId = session.id;
1108
+ this.browserUseApiKey = browserUseApiKey;
1109
+ this.browser = browser;
1110
+ context.setDefaultTimeout(getDefaultTimeout());
1111
+ this.contexts.push(context);
1112
+ this.pages.push(page);
1113
+ this.activePageIndex = 0;
1114
+ this.setupPageTracking(page);
1115
+ this.setupContextTracking(context);
1116
+ }
1117
+ catch (error) {
1118
+ await this.closeBrowserUseSession(session.id, browserUseApiKey).catch((sessionError) => {
1119
+ console.error('Failed to close Browser Use session during cleanup:', sessionError);
1120
+ });
1121
+ throw error;
1122
+ }
1123
+ }
1124
+ /**
1125
+ * Launch the browser with the specified options
1126
+ * If already launched, this is a no-op (browser stays open)
1127
+ */
1128
+ async launch(options) {
1129
+ // Determine CDP endpoint: prefer cdpUrl over cdpPort for flexibility
1130
+ const cdpEndpoint = options.cdpUrl ?? (options.cdpPort ? String(options.cdpPort) : undefined);
1131
+ const hasExtensions = !!options.extensions?.length;
1132
+ const hasProfile = !!options.profile;
1133
+ const hasStorageState = !!options.storageState;
1134
+ if (hasExtensions && cdpEndpoint) {
1135
+ throw new Error('Extensions cannot be used with CDP connection');
1136
+ }
1137
+ if (hasProfile && cdpEndpoint) {
1138
+ throw new Error('Profile cannot be used with CDP connection');
1139
+ }
1140
+ if (hasStorageState && hasProfile) {
1141
+ throw new Error('Storage state cannot be used with profile (profile is already persistent storage)');
1142
+ }
1143
+ if (hasStorageState && hasExtensions) {
1144
+ throw new Error('Storage state cannot be used with extensions (extensions require persistent context)');
1145
+ }
1146
+ if (this.isLaunched()) {
1147
+ const needsRelaunch = (!cdpEndpoint && !options.autoConnect && this.cdpEndpoint !== null) ||
1148
+ (!!cdpEndpoint && this.needsCdpReconnect(cdpEndpoint)) ||
1149
+ (!!options.autoConnect && !this.isCdpConnectionAlive());
1150
+ if (needsRelaunch) {
1151
+ await this.close();
1152
+ }
1153
+ else if (options.autoConnect && this.isCdpConnectionAlive()) {
1154
+ // Already connected via auto-connect, no need to reconnect
1155
+ return;
1156
+ }
1157
+ else {
1158
+ return;
1159
+ }
1160
+ }
1161
+ if (options.colorScheme) {
1162
+ this.colorScheme = options.colorScheme;
1163
+ }
1164
+ this.stealthEnabled = options.stealth ?? false;
1165
+ this.contextLocale = this.stealthEnabled
1166
+ ? this.resolveStealthLocale(options.headers)
1167
+ : undefined;
1168
+ this.contextTimezoneId = this.stealthEnabled ? this.resolveStealthTimezoneId() : undefined;
1169
+ this.contextHeaders = undefined;
1170
+ this.contextUserAgent = options.userAgent;
1171
+ // -p flag takes precedence over AGENT_BROWSER_PROVIDER.
1172
+ const provider = options.provider ?? process.env.AGENT_BROWSER_PROVIDER;
1173
+ if (cdpEndpoint || options.autoConnect) {
1174
+ this.stealthConnectionKind = 'cdp';
1175
+ }
1176
+ else if (provider === 'browserbase') {
1177
+ this.stealthConnectionKind = 'provider-browserbase';
1178
+ }
1179
+ else if (provider === 'browseruse') {
1180
+ this.stealthConnectionKind = 'provider-browseruse';
1181
+ }
1182
+ else if (provider === 'kernel') {
1183
+ this.stealthConnectionKind = 'provider-kernel';
1184
+ }
1185
+ else {
1186
+ this.stealthConnectionKind = 'local';
1187
+ }
1188
+ this.logStealthPolicy('launch policy', options.browser ?? 'chromium');
1189
+ if (cdpEndpoint) {
1190
+ await this.connectViaCDP(cdpEndpoint);
1191
+ return;
1192
+ }
1193
+ if (options.autoConnect) {
1194
+ await this.autoConnectViaCDP();
1195
+ return;
1196
+ }
1197
+ // Cloud browser providers require explicit opt-in via -p flag or AGENT_BROWSER_PROVIDER env var
1198
+ if (provider === 'browserbase') {
1199
+ await this.connectToBrowserbase();
1200
+ return;
1201
+ }
1202
+ if (provider === 'browseruse') {
1203
+ await this.connectToBrowserUse();
1204
+ return;
1205
+ }
1206
+ // Kernel: requires explicit opt-in via -p kernel flag or AGENT_BROWSER_PROVIDER=kernel
1207
+ if (provider === 'kernel') {
1208
+ await this.connectToKernel();
1209
+ return;
1210
+ }
1211
+ const browserType = options.browser ?? 'chromium';
1212
+ if (hasExtensions && browserType !== 'chromium') {
1213
+ throw new Error('Extensions are only supported in Chromium');
1214
+ }
1215
+ // allowFileAccess is only supported in Chromium
1216
+ if (options.allowFileAccess && browserType !== 'chromium') {
1217
+ throw new Error('allowFileAccess is only supported in Chromium');
1218
+ }
1219
+ const launcher = browserType === 'firefox' ? firefox : browserType === 'webkit' ? webkit : chromium;
1220
+ const stealthPolicy = this.getStealthPolicy(browserType);
1221
+ const contextDefaults = this.buildStealthContextDefaults(stealthPolicy, options.headers);
1222
+ const extraHTTPHeaders = contextDefaults.extraHTTPHeaders;
1223
+ this.contextLocale = contextDefaults.locale;
1224
+ this.contextTimezoneId = contextDefaults.timezoneId;
1225
+ this.contextHeaders = contextDefaults.extraHTTPHeaders;
1226
+ let contextUserAgent = options.userAgent;
1227
+ if (!contextUserAgent && stealthPolicy.enabled && browserType === 'chromium') {
1228
+ const versionHint = this.getStealthUserAgentVersionHint();
1229
+ if (versionHint) {
1230
+ contextUserAgent = this.buildStealthChromiumUserAgent(versionHint);
1231
+ }
1232
+ }
1233
+ this.contextUserAgent = contextUserAgent;
1234
+ // Build base args array with file access flags and stealth args when policy allows.
1235
+ const fileAccessArgs = options.allowFileAccess
1236
+ ? ['--allow-file-access-from-files', '--allow-file-access']
1237
+ : [];
1238
+ const stealthArgs = stealthPolicy.applyChromiumArgs ? STEALTH_CHROMIUM_ARGS : [];
1239
+ const hasUserAgentArg = options.args?.some((arg) => arg.startsWith('--user-agent='));
1240
+ const launchUserAgentArgs = !hasUserAgentArg &&
1241
+ !options.userAgent &&
1242
+ stealthPolicy.enabled &&
1243
+ browserType === 'chromium' &&
1244
+ contextUserAgent
1245
+ ? [`--user-agent=${contextUserAgent}`]
1246
+ : [];
1247
+ const implicitArgs = [...fileAccessArgs, ...stealthArgs, ...launchUserAgentArgs];
1248
+ const baseArgs = options.args
1249
+ ? [...implicitArgs, ...options.args]
1250
+ : implicitArgs.length > 0
1251
+ ? implicitArgs
1252
+ : undefined;
1253
+ // Auto-detect args that control window size and disable viewport emulation
1254
+ // so Playwright doesn't override the browser's own sizing behavior
1255
+ const hasWindowSizeArgs = baseArgs?.some((arg) => arg === '--start-maximized' || arg.startsWith('--window-size='));
1256
+ const viewport = options.viewport !== undefined
1257
+ ? options.viewport
1258
+ : hasWindowSizeArgs
1259
+ ? null
1260
+ : { width: 1280, height: 720 };
1261
+ let context;
1262
+ if (hasExtensions) {
1263
+ // Extensions require persistent context in a temp directory
1264
+ const extPaths = options.extensions.join(',');
1265
+ const session = process.env.AGENT_BROWSER_SESSION || 'default';
1266
+ // Combine extension args with custom args and file access args
1267
+ const extArgs = [`--disable-extensions-except=${extPaths}`, `--load-extension=${extPaths}`];
1268
+ const allArgs = baseArgs ? [...extArgs, ...baseArgs] : extArgs;
1269
+ context = await launcher.launchPersistentContext(path.join(os.tmpdir(), `agent-browser-ext-${session}`), {
1270
+ headless: false,
1271
+ executablePath: options.executablePath,
1272
+ args: allArgs,
1273
+ viewport,
1274
+ extraHTTPHeaders,
1275
+ userAgent: contextUserAgent,
1276
+ ...(this.contextLocale && { locale: this.contextLocale }),
1277
+ ...(this.contextTimezoneId && { timezoneId: this.contextTimezoneId }),
1278
+ ...(options.proxy && { proxy: options.proxy }),
1279
+ ignoreHTTPSErrors: options.ignoreHTTPSErrors ?? false,
1280
+ ...(this.colorScheme && { colorScheme: this.colorScheme }),
1281
+ });
1282
+ this.isPersistentContext = true;
1283
+ }
1284
+ else if (hasProfile) {
1285
+ // Profile uses persistent context for durable cookies/storage
1286
+ // Expand ~ to home directory since it won't be shell-expanded
1287
+ const profilePath = options.profile.replace(/^~\//, os.homedir() + '/');
1288
+ context = await launcher.launchPersistentContext(profilePath, {
1289
+ headless: options.headless ?? true,
1290
+ executablePath: options.executablePath,
1291
+ args: baseArgs,
1292
+ viewport,
1293
+ extraHTTPHeaders,
1294
+ userAgent: contextUserAgent,
1295
+ ...(this.contextLocale && { locale: this.contextLocale }),
1296
+ ...(this.contextTimezoneId && { timezoneId: this.contextTimezoneId }),
1297
+ ...(options.proxy && { proxy: options.proxy }),
1298
+ ignoreHTTPSErrors: options.ignoreHTTPSErrors ?? false,
1299
+ ...(this.colorScheme && { colorScheme: this.colorScheme }),
1300
+ });
1301
+ this.isPersistentContext = true;
1302
+ }
1303
+ else {
1304
+ // Regular ephemeral browser
1305
+ this.browser = await launcher.launch({
1306
+ headless: options.headless ?? true,
1307
+ executablePath: options.executablePath,
1308
+ args: baseArgs,
1309
+ });
1310
+ this.cdpEndpoint = null;
1311
+ if (!options.userAgent && stealthPolicy.enabled && browserType === 'chromium') {
1312
+ const runtimeVersion = this.extractChromiumVersion(this.browser.version());
1313
+ if (runtimeVersion) {
1314
+ contextUserAgent = this.buildStealthChromiumUserAgent(runtimeVersion);
1315
+ this.contextUserAgent = contextUserAgent;
1316
+ }
1317
+ }
1318
+ // Check for auto-load state file (supports encrypted files)
1319
+ let storageState = options.storageState ? options.storageState : undefined;
1320
+ if (!storageState && options.autoStateFilePath) {
1321
+ try {
1322
+ const fs = await import('fs');
1323
+ if (fs.existsSync(options.autoStateFilePath)) {
1324
+ const content = fs.readFileSync(options.autoStateFilePath, 'utf8');
1325
+ const parsed = JSON.parse(content);
1326
+ if (isEncryptedPayload(parsed)) {
1327
+ const key = getEncryptionKey();
1328
+ if (key) {
1329
+ try {
1330
+ const decrypted = decryptData(parsed, key);
1331
+ storageState = JSON.parse(decrypted);
1332
+ if (process.env.AGENT_BROWSER_DEBUG === '1') {
1333
+ console.error(`[DEBUG] Auto-loading session state (decrypted): ${options.autoStateFilePath}`);
1334
+ }
1335
+ }
1336
+ catch (decryptErr) {
1337
+ const warning = 'Failed to decrypt state file - wrong encryption key? Starting fresh.';
1338
+ this.launchWarnings.push(warning);
1339
+ console.error(`[WARN] ${warning}`);
1340
+ if (process.env.AGENT_BROWSER_DEBUG === '1') {
1341
+ console.error(`[DEBUG] Decryption error:`, decryptErr);
1342
+ }
1343
+ }
1344
+ }
1345
+ else {
1346
+ const warning = `State file is encrypted but ${ENCRYPTION_KEY_ENV} not set - starting fresh`;
1347
+ this.launchWarnings.push(warning);
1348
+ console.error(`[WARN] ${warning}`);
1349
+ }
1350
+ }
1351
+ else {
1352
+ storageState = options.autoStateFilePath;
1353
+ if (process.env.AGENT_BROWSER_DEBUG === '1') {
1354
+ console.error(`[DEBUG] Auto-loading session state: ${options.autoStateFilePath}`);
1355
+ }
1356
+ }
1357
+ }
1358
+ }
1359
+ catch (err) {
1360
+ if (process.env.AGENT_BROWSER_DEBUG === '1') {
1361
+ console.error(`[DEBUG] Failed to load state file, starting fresh:`, err);
1362
+ }
1363
+ }
1364
+ }
1365
+ context = await this.browser.newContext({
1366
+ viewport,
1367
+ extraHTTPHeaders,
1368
+ userAgent: contextUserAgent,
1369
+ storageState,
1370
+ ...(this.contextLocale && { locale: this.contextLocale }),
1371
+ ...(this.contextTimezoneId && { timezoneId: this.contextTimezoneId }),
1372
+ ...(options.proxy && { proxy: options.proxy }),
1373
+ ignoreHTTPSErrors: options.ignoreHTTPSErrors ?? false,
1374
+ ...(this.colorScheme && { colorScheme: this.colorScheme }),
1375
+ });
1376
+ }
1377
+ await this.applyStealthIfEnabled(context, { locale: this.contextLocale });
1378
+ context.setDefaultTimeout(getDefaultTimeout());
1379
+ this.contexts.push(context);
1380
+ this.setupContextTracking(context);
1381
+ const page = context.pages()[0] ?? (await context.newPage());
1382
+ // Only add if not already tracked (setupContextTracking may have already added it via 'page' event)
1383
+ if (!this.pages.includes(page)) {
1384
+ this.pages.push(page);
1385
+ this.setupPageTracking(page);
1386
+ }
1387
+ this.activePageIndex = this.pages.length > 0 ? this.pages.length - 1 : 0;
1388
+ }
1389
+ /**
1390
+ * Connect to a running browser via CDP (Chrome DevTools Protocol)
1391
+ * @param cdpEndpoint Either a port number (as string) or a full WebSocket URL (ws:// or wss://)
1392
+ */
1393
+ async connectViaCDP(cdpEndpoint, options) {
1394
+ this.stealthConnectionKind = 'cdp';
1395
+ if (!cdpEndpoint) {
1396
+ throw new Error('CDP endpoint is required for CDP connection');
1397
+ }
1398
+ // Determine the connection URL:
1399
+ // - If it starts with ws://, wss://, http://, or https://, use it directly
1400
+ // - If it's a numeric string (e.g., "9222"), treat as port for localhost
1401
+ // - Otherwise, treat it as a port number for localhost
1402
+ let cdpUrl;
1403
+ if (cdpEndpoint.startsWith('ws://') ||
1404
+ cdpEndpoint.startsWith('wss://') ||
1405
+ cdpEndpoint.startsWith('http://') ||
1406
+ cdpEndpoint.startsWith('https://')) {
1407
+ cdpUrl = cdpEndpoint;
1408
+ }
1409
+ else if (/^\d+$/.test(cdpEndpoint)) {
1410
+ // Numeric string - treat as port number (handles JSON serialization quirks)
1411
+ cdpUrl = `http://localhost:${cdpEndpoint}`;
1412
+ }
1413
+ else {
1414
+ // Unknown format - still try as port for backward compatibility
1415
+ cdpUrl = `http://localhost:${cdpEndpoint}`;
1416
+ }
1417
+ const browser = await chromium
1418
+ .connectOverCDP(cdpUrl, { timeout: options?.timeout })
1419
+ .catch(() => {
1420
+ throw new Error(`Failed to connect via CDP to ${cdpUrl}. ` +
1421
+ (cdpUrl.includes('localhost')
1422
+ ? `Make sure the app is running with --remote-debugging-port=${cdpEndpoint}`
1423
+ : 'Make sure the remote browser is accessible and the URL is correct.'));
1424
+ });
1425
+ // Validate and set up state, cleaning up browser connection if anything fails
1426
+ try {
1427
+ const contexts = browser.contexts();
1428
+ if (contexts.length === 0) {
1429
+ throw new Error('No browser context found. Make sure the app has an open window.');
1430
+ }
1431
+ // Filter out pages with empty URLs, which can cause Playwright to hang
1432
+ const allPages = contexts.flatMap((context) => context.pages()).filter((page) => page.url());
1433
+ if (allPages.length === 0) {
1434
+ throw new Error('No page found. Make sure the app has loaded content.');
1435
+ }
1436
+ // All validation passed - commit state
1437
+ this.browser = browser;
1438
+ this.cdpEndpoint = cdpEndpoint;
1439
+ for (const context of contexts) {
1440
+ await this.applyStealthIfEnabled(context, { locale: this.contextLocale });
1441
+ context.setDefaultTimeout(10000);
1442
+ this.contexts.push(context);
1443
+ this.setupContextTracking(context);
1444
+ }
1445
+ for (const page of allPages) {
1446
+ this.pages.push(page);
1447
+ this.setupPageTracking(page);
1448
+ }
1449
+ this.activePageIndex = 0;
1450
+ }
1451
+ catch (error) {
1452
+ // Clean up browser connection if validation or setup failed
1453
+ await browser.close().catch(() => { });
1454
+ throw error;
1455
+ }
1456
+ }
1457
+ /**
1458
+ * Get Chrome's default user data directory paths for the current platform.
1459
+ * Returns an array of candidate paths to check (stable, then beta/canary).
1460
+ */
1461
+ getChromeUserDataDirs() {
1462
+ const home = os.homedir();
1463
+ const platform = os.platform();
1464
+ if (platform === 'darwin') {
1465
+ return [
1466
+ path.join(home, 'Library', 'Application Support', 'Google', 'Chrome'),
1467
+ path.join(home, 'Library', 'Application Support', 'Google', 'Chrome Canary'),
1468
+ path.join(home, 'Library', 'Application Support', 'Chromium'),
1469
+ ];
1470
+ }
1471
+ else if (platform === 'win32') {
1472
+ const localAppData = process.env.LOCALAPPDATA ?? path.join(home, 'AppData', 'Local');
1473
+ return [
1474
+ path.join(localAppData, 'Google', 'Chrome', 'User Data'),
1475
+ path.join(localAppData, 'Google', 'Chrome SxS', 'User Data'),
1476
+ path.join(localAppData, 'Chromium', 'User Data'),
1477
+ ];
1478
+ }
1479
+ else {
1480
+ // Linux
1481
+ return [
1482
+ path.join(home, '.config', 'google-chrome'),
1483
+ path.join(home, '.config', 'google-chrome-unstable'),
1484
+ path.join(home, '.config', 'chromium'),
1485
+ ];
1486
+ }
1487
+ }
1488
+ /**
1489
+ * Try to read the DevToolsActivePort file from a Chrome user data directory.
1490
+ * Returns { port, wsPath } if found, or null if not available.
1491
+ */
1492
+ readDevToolsActivePort(userDataDir) {
1493
+ const filePath = path.join(userDataDir, 'DevToolsActivePort');
1494
+ try {
1495
+ if (!existsSync(filePath))
1496
+ return null;
1497
+ const content = readFileSync(filePath, 'utf-8').trim();
1498
+ const lines = content.split('\n');
1499
+ if (lines.length < 2)
1500
+ return null;
1501
+ const port = parseInt(lines[0].trim(), 10);
1502
+ const wsPath = lines[1].trim();
1503
+ if (isNaN(port) || port <= 0 || port > 65535)
1504
+ return null;
1505
+ if (!wsPath)
1506
+ return null;
1507
+ return { port, wsPath };
1508
+ }
1509
+ catch {
1510
+ return null;
1511
+ }
1512
+ }
1513
+ /**
1514
+ * Try to discover a Chrome CDP endpoint by querying an HTTP debug port.
1515
+ * Returns the WebSocket debugger URL if available.
1516
+ */
1517
+ async probeDebugPort(port) {
1518
+ try {
1519
+ const response = await fetch(`http://127.0.0.1:${port}/json/version`, {
1520
+ signal: AbortSignal.timeout(2000),
1521
+ });
1522
+ if (!response.ok)
1523
+ return null;
1524
+ const data = (await response.json());
1525
+ return data.webSocketDebuggerUrl ?? null;
1526
+ }
1527
+ catch {
1528
+ return null;
1529
+ }
1530
+ }
1531
+ /**
1532
+ * Auto-discover and connect to a running Chrome/Chromium instance.
1533
+ *
1534
+ * Discovery strategy:
1535
+ * 1. Read DevToolsActivePort from Chrome's default user data directories
1536
+ * 2. If found, connect using the port and WebSocket path from that file
1537
+ * 3. If not found, probe common debugging ports (9222, 9229)
1538
+ * 4. If a port responds, connect via CDP
1539
+ */
1540
+ async autoConnectViaCDP() {
1541
+ // Strategy 1: Check DevToolsActivePort files
1542
+ const userDataDirs = this.getChromeUserDataDirs();
1543
+ for (const dir of userDataDirs) {
1544
+ const activePort = this.readDevToolsActivePort(dir);
1545
+ if (activePort) {
1546
+ // Try HTTP discovery first (works with --remote-debugging-port mode)
1547
+ const wsUrl = await this.probeDebugPort(activePort.port);
1548
+ if (wsUrl) {
1549
+ await this.connectViaCDP(wsUrl);
1550
+ return;
1551
+ }
1552
+ // HTTP probe failed -- Chrome M144+ chrome://inspect remote debugging uses a
1553
+ // WebSocket-only server with no HTTP endpoints. Connect using the WebSocket
1554
+ // path read directly from DevToolsActivePort.
1555
+ const directWsUrl = `ws://127.0.0.1:${activePort.port}${activePort.wsPath}`;
1556
+ try {
1557
+ if (process.env.AGENT_BROWSER_DEBUG === '1') {
1558
+ console.error(`[DEBUG] HTTP probe failed on port ${activePort.port}, ` +
1559
+ `attempting direct WebSocket connection to ${directWsUrl}`);
1560
+ }
1561
+ await this.connectViaCDP(directWsUrl, { timeout: 60_000 });
1562
+ return;
1563
+ }
1564
+ catch {
1565
+ // Direct WebSocket also failed, try next directory
1566
+ }
1567
+ }
1568
+ }
1569
+ // Strategy 2: Probe common debugging ports
1570
+ const commonPorts = [9222, 9229];
1571
+ for (const port of commonPorts) {
1572
+ const wsUrl = await this.probeDebugPort(port);
1573
+ if (wsUrl) {
1574
+ await this.connectViaCDP(wsUrl);
1575
+ return;
1576
+ }
1577
+ }
1578
+ // Nothing found
1579
+ const platform = os.platform();
1580
+ let hint;
1581
+ if (platform === 'darwin') {
1582
+ hint =
1583
+ 'Start Chrome with: /Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome --remote-debugging-port=9222\n' +
1584
+ 'Or enable remote debugging in Chrome 144+ at chrome://inspect/#remote-debugging';
1585
+ }
1586
+ else if (platform === 'win32') {
1587
+ hint =
1588
+ 'Start Chrome with: chrome.exe --remote-debugging-port=9222\n' +
1589
+ 'Or enable remote debugging in Chrome 144+ at chrome://inspect/#remote-debugging';
1590
+ }
1591
+ else {
1592
+ hint =
1593
+ 'Start Chrome with: google-chrome --remote-debugging-port=9222\n' +
1594
+ 'Or enable remote debugging in Chrome 144+ at chrome://inspect/#remote-debugging';
1595
+ }
1596
+ throw new Error(`No running Chrome instance with remote debugging found.\n${hint}`);
1597
+ }
1598
+ /**
1599
+ * Set up console, error, and close tracking for a page
1600
+ */
1601
+ setupPageTracking(page) {
1602
+ if (this.colorScheme) {
1603
+ page.emulateMedia({ colorScheme: this.colorScheme }).catch(() => { });
1604
+ }
1605
+ page.on('console', (msg) => {
1606
+ this.consoleMessages.push({
1607
+ type: msg.type(),
1608
+ text: msg.text(),
1609
+ timestamp: Date.now(),
1610
+ });
1611
+ });
1612
+ page.on('pageerror', (error) => {
1613
+ this.pageErrors.push({
1614
+ message: error.message,
1615
+ timestamp: Date.now(),
1616
+ });
1617
+ });
1618
+ page.on('close', () => {
1619
+ const index = this.pages.indexOf(page);
1620
+ if (index !== -1) {
1621
+ this.pages.splice(index, 1);
1622
+ if (this.activePageIndex >= this.pages.length) {
1623
+ this.activePageIndex = Math.max(0, this.pages.length - 1);
1624
+ }
1625
+ }
1626
+ });
1627
+ }
1628
+ /**
1629
+ * Set up tracking for new pages in a context (for CDP connections and popups/new tabs)
1630
+ * This handles pages created externally (e.g., via target="_blank" links, window.open)
1631
+ */
1632
+ setupContextTracking(context) {
1633
+ context.on('page', (page) => {
1634
+ // Only add if not already tracked (avoids duplicates when newTab() creates pages)
1635
+ if (!this.pages.includes(page)) {
1636
+ this.pages.push(page);
1637
+ this.setupPageTracking(page);
1638
+ }
1639
+ // Auto-switch to the newly opened tab so subsequent commands target it.
1640
+ // For tabs created via newTab()/newWindow(), this is redundant (they set activePageIndex after),
1641
+ // but for externally opened tabs (window.open, target="_blank"), this ensures the active tab
1642
+ // stays in sync with the browser.
1643
+ const newIndex = this.pages.indexOf(page);
1644
+ if (newIndex !== -1 && newIndex !== this.activePageIndex) {
1645
+ this.activePageIndex = newIndex;
1646
+ // Invalidate CDP session since the active page changed
1647
+ this.invalidateCDPSession().catch(() => { });
1648
+ }
1649
+ });
1650
+ }
1651
+ /**
1652
+ * Create a new tab in the current context
1653
+ */
1654
+ async newTab() {
1655
+ if (!this.browser || this.contexts.length === 0) {
1656
+ throw new Error('Browser not launched');
1657
+ }
1658
+ // Invalidate CDP session since we're switching to a new page
1659
+ await this.invalidateCDPSession();
1660
+ const context = this.contexts[0]; // Use first context for tabs
1661
+ const page = await context.newPage();
1662
+ // Only add if not already tracked (setupContextTracking may have already added it via 'page' event)
1663
+ if (!this.pages.includes(page)) {
1664
+ this.pages.push(page);
1665
+ this.setupPageTracking(page);
1666
+ }
1667
+ this.activePageIndex = this.pages.length - 1;
1668
+ return { index: this.activePageIndex, total: this.pages.length };
1669
+ }
1670
+ /**
1671
+ * Create a new window (new context)
1672
+ */
1673
+ async newWindow(viewport) {
1674
+ if (!this.browser) {
1675
+ throw new Error('Browser not launched');
1676
+ }
1677
+ const context = await this.browser.newContext({
1678
+ viewport: viewport === undefined ? { width: 1280, height: 720 } : viewport,
1679
+ ...(this.contextHeaders && { extraHTTPHeaders: this.contextHeaders }),
1680
+ ...(this.contextUserAgent && { userAgent: this.contextUserAgent }),
1681
+ ...(this.contextLocale && { locale: this.contextLocale }),
1682
+ ...(this.contextTimezoneId && { timezoneId: this.contextTimezoneId }),
1683
+ ...(this.colorScheme && { colorScheme: this.colorScheme }),
1684
+ });
1685
+ await this.applyStealthIfEnabled(context, { locale: this.contextLocale });
1686
+ context.setDefaultTimeout(getDefaultTimeout());
1687
+ this.contexts.push(context);
1688
+ this.setupContextTracking(context);
1689
+ const page = await context.newPage();
1690
+ // Only add if not already tracked (setupContextTracking may have already added it via 'page' event)
1691
+ if (!this.pages.includes(page)) {
1692
+ this.pages.push(page);
1693
+ this.setupPageTracking(page);
1694
+ }
1695
+ this.activePageIndex = this.pages.length - 1;
1696
+ return { index: this.activePageIndex, total: this.pages.length };
1697
+ }
1698
+ /**
1699
+ * Invalidate the current CDP session (must be called before switching pages)
1700
+ * This ensures screencast and input injection work correctly after tab switch
1701
+ */
1702
+ async invalidateCDPSession() {
1703
+ // Stop screencast if active (it's tied to the current page's CDP session)
1704
+ if (this.screencastActive) {
1705
+ await this.stopScreencast();
1706
+ }
1707
+ // Detach and clear the CDP session
1708
+ if (this.cdpSession) {
1709
+ await this.cdpSession.detach().catch(() => { });
1710
+ this.cdpSession = null;
1711
+ }
1712
+ }
1713
+ /**
1714
+ * Switch to a specific tab/page by index
1715
+ */
1716
+ async switchTo(index) {
1717
+ if (index < 0 || index >= this.pages.length) {
1718
+ throw new Error(`Invalid tab index: ${index}. Available: 0-${this.pages.length - 1}`);
1719
+ }
1720
+ // Invalidate CDP session before switching (it's page-specific)
1721
+ if (index !== this.activePageIndex) {
1722
+ await this.invalidateCDPSession();
1723
+ }
1724
+ this.activePageIndex = index;
1725
+ const page = this.pages[index];
1726
+ return {
1727
+ index: this.activePageIndex,
1728
+ url: page.url(),
1729
+ title: '', // Title requires async, will be fetched separately
1730
+ };
1731
+ }
1732
+ /**
1733
+ * Close a specific tab/page
1734
+ */
1735
+ async closeTab(index) {
1736
+ const targetIndex = index ?? this.activePageIndex;
1737
+ if (targetIndex < 0 || targetIndex >= this.pages.length) {
1738
+ throw new Error(`Invalid tab index: ${targetIndex}`);
1739
+ }
1740
+ if (this.pages.length === 1) {
1741
+ throw new Error('Cannot close the last tab. Use "close" to close the browser.');
1742
+ }
1743
+ // If closing the active tab, invalidate CDP session first
1744
+ if (targetIndex === this.activePageIndex) {
1745
+ await this.invalidateCDPSession();
1746
+ }
1747
+ const page = this.pages[targetIndex];
1748
+ await page.close();
1749
+ this.pages.splice(targetIndex, 1);
1750
+ // Adjust active index if needed
1751
+ if (this.activePageIndex >= this.pages.length) {
1752
+ this.activePageIndex = this.pages.length - 1;
1753
+ }
1754
+ else if (this.activePageIndex > targetIndex) {
1755
+ this.activePageIndex--;
1756
+ }
1757
+ return { closed: targetIndex, remaining: this.pages.length };
1758
+ }
1759
+ /**
1760
+ * List all tabs with their info
1761
+ */
1762
+ async listTabs() {
1763
+ const tabs = await Promise.all(this.pages.map(async (page, index) => ({
1764
+ index,
1765
+ url: page.url(),
1766
+ title: await page.title().catch(() => ''),
1767
+ active: index === this.activePageIndex,
1768
+ })));
1769
+ return tabs;
1770
+ }
1771
+ /**
1772
+ * Get or create a CDP session for the current page
1773
+ * Only works with Chromium-based browsers
1774
+ */
1775
+ async getCDPSession() {
1776
+ if (this.cdpSession) {
1777
+ return this.cdpSession;
1778
+ }
1779
+ const page = this.getPage();
1780
+ const context = page.context();
1781
+ // Create a new CDP session attached to the page
1782
+ this.cdpSession = await context.newCDPSession(page);
1783
+ return this.cdpSession;
1784
+ }
1785
+ /**
1786
+ * Check if screencast is currently active
1787
+ */
1788
+ isScreencasting() {
1789
+ return this.screencastActive;
1790
+ }
1791
+ /**
1792
+ * Start screencast - streams viewport frames via CDP
1793
+ * @param callback Function called for each frame
1794
+ * @param options Screencast options
1795
+ */
1796
+ async startScreencast(callback, options) {
1797
+ if (this.screencastActive) {
1798
+ throw new Error('Screencast already active');
1799
+ }
1800
+ const cdp = await this.getCDPSession();
1801
+ this.frameCallback = callback;
1802
+ this.screencastActive = true;
1803
+ // Create and store the frame handler so we can remove it later
1804
+ this.screencastFrameHandler = async (params) => {
1805
+ const frame = {
1806
+ data: params.data,
1807
+ metadata: params.metadata,
1808
+ sessionId: params.sessionId,
1809
+ };
1810
+ // Acknowledge the frame to receive the next one
1811
+ await cdp.send('Page.screencastFrameAck', { sessionId: params.sessionId });
1812
+ // Call the callback with the frame
1813
+ if (this.frameCallback) {
1814
+ this.frameCallback(frame);
1815
+ }
1816
+ };
1817
+ // Listen for screencast frames
1818
+ cdp.on('Page.screencastFrame', this.screencastFrameHandler);
1819
+ // Start the screencast
1820
+ await cdp.send('Page.startScreencast', {
1821
+ format: options?.format ?? 'jpeg',
1822
+ quality: options?.quality ?? 80,
1823
+ maxWidth: options?.maxWidth ?? 1280,
1824
+ maxHeight: options?.maxHeight ?? 720,
1825
+ everyNthFrame: options?.everyNthFrame ?? 1,
1826
+ });
1827
+ }
1828
+ /**
1829
+ * Stop screencast
1830
+ */
1831
+ async stopScreencast() {
1832
+ if (!this.screencastActive) {
1833
+ return;
1834
+ }
1835
+ try {
1836
+ const cdp = await this.getCDPSession();
1837
+ await cdp.send('Page.stopScreencast');
1838
+ // Remove the event listener to prevent accumulation
1839
+ if (this.screencastFrameHandler) {
1840
+ cdp.off('Page.screencastFrame', this.screencastFrameHandler);
1841
+ }
1842
+ }
1843
+ catch {
1844
+ // Ignore errors when stopping
1845
+ }
1846
+ this.screencastActive = false;
1847
+ this.frameCallback = null;
1848
+ this.screencastFrameHandler = null;
1849
+ }
1850
+ /**
1851
+ * Check if profiling is currently active
1852
+ */
1853
+ isProfilingActive() {
1854
+ return this.profilingActive;
1855
+ }
1856
+ /**
1857
+ * Start CDP profiling (Tracing)
1858
+ */
1859
+ async startProfiling(options) {
1860
+ if (this.profilingActive) {
1861
+ throw new Error('Profiling already active');
1862
+ }
1863
+ const cdp = await this.getCDPSession();
1864
+ const dataHandler = (params) => {
1865
+ if (params.value) {
1866
+ for (const evt of params.value) {
1867
+ if (this.profileChunks.length >= BrowserManager.MAX_PROFILE_EVENTS) {
1868
+ if (!this.profileEventsDropped) {
1869
+ this.profileEventsDropped = true;
1870
+ console.warn(`Profiling: exceeded ${BrowserManager.MAX_PROFILE_EVENTS} events, dropping further data`);
1871
+ }
1872
+ return;
1873
+ }
1874
+ this.profileChunks.push(evt);
1875
+ }
1876
+ }
1877
+ };
1878
+ const completeHandler = () => {
1879
+ if (this.profileCompleteResolver) {
1880
+ this.profileCompleteResolver();
1881
+ }
1882
+ };
1883
+ cdp.on('Tracing.dataCollected', dataHandler);
1884
+ cdp.on('Tracing.tracingComplete', completeHandler);
1885
+ const categories = options?.categories ?? [
1886
+ 'devtools.timeline',
1887
+ 'disabled-by-default-devtools.timeline',
1888
+ 'disabled-by-default-devtools.timeline.frame',
1889
+ 'disabled-by-default-devtools.timeline.stack',
1890
+ 'v8.execute',
1891
+ 'disabled-by-default-v8.cpu_profiler',
1892
+ 'disabled-by-default-v8.cpu_profiler.hires',
1893
+ 'v8',
1894
+ 'disabled-by-default-v8.runtime_stats',
1895
+ 'blink',
1896
+ 'blink.user_timing',
1897
+ 'latencyInfo',
1898
+ 'renderer.scheduler',
1899
+ 'sequence_manager',
1900
+ 'toplevel',
1901
+ ];
1902
+ try {
1903
+ await cdp.send('Tracing.start', {
1904
+ traceConfig: {
1905
+ includedCategories: categories,
1906
+ enableSampling: true,
1907
+ },
1908
+ transferMode: 'ReportEvents',
1909
+ });
1910
+ }
1911
+ catch (error) {
1912
+ cdp.off('Tracing.dataCollected', dataHandler);
1913
+ cdp.off('Tracing.tracingComplete', completeHandler);
1914
+ throw error;
1915
+ }
1916
+ // Only commit state after the CDP call succeeds
1917
+ this.profilingActive = true;
1918
+ this.profileChunks = [];
1919
+ this.profileEventsDropped = false;
1920
+ this.profileDataHandler = dataHandler;
1921
+ this.profileCompleteHandler = completeHandler;
1922
+ }
1923
+ /**
1924
+ * Stop CDP profiling and save to file
1925
+ */
1926
+ async stopProfiling(outputPath) {
1927
+ if (!this.profilingActive) {
1928
+ throw new Error('No profiling session active');
1929
+ }
1930
+ const cdp = await this.getCDPSession();
1931
+ const TRACE_TIMEOUT_MS = 30_000;
1932
+ const completePromise = new Promise((resolve, reject) => {
1933
+ const timer = setTimeout(() => reject(new Error('Profiling data collection timed out')), TRACE_TIMEOUT_MS);
1934
+ this.profileCompleteResolver = () => {
1935
+ clearTimeout(timer);
1936
+ resolve();
1937
+ };
1938
+ });
1939
+ await cdp.send('Tracing.end');
1940
+ let chunks;
1941
+ try {
1942
+ await completePromise;
1943
+ chunks = this.profileChunks;
1944
+ }
1945
+ finally {
1946
+ if (this.profileDataHandler) {
1947
+ cdp.off('Tracing.dataCollected', this.profileDataHandler);
1948
+ }
1949
+ if (this.profileCompleteHandler) {
1950
+ cdp.off('Tracing.tracingComplete', this.profileCompleteHandler);
1951
+ }
1952
+ this.profilingActive = false;
1953
+ this.profileChunks = [];
1954
+ this.profileEventsDropped = false;
1955
+ this.profileCompleteResolver = null;
1956
+ this.profileDataHandler = null;
1957
+ this.profileCompleteHandler = null;
1958
+ }
1959
+ const clockDomain = process.platform === 'linux'
1960
+ ? 'LINUX_CLOCK_MONOTONIC'
1961
+ : process.platform === 'darwin'
1962
+ ? 'MAC_MACH_ABSOLUTE_TIME'
1963
+ : undefined;
1964
+ const traceData = {
1965
+ traceEvents: chunks,
1966
+ };
1967
+ if (clockDomain) {
1968
+ traceData.metadata = { 'clock-domain': clockDomain };
1969
+ }
1970
+ const dir = path.dirname(outputPath);
1971
+ await mkdir(dir, { recursive: true });
1972
+ await writeFile(outputPath, JSON.stringify(traceData));
1973
+ const eventCount = chunks.length;
1974
+ return { path: outputPath, eventCount };
1975
+ }
1976
+ /**
1977
+ * Inject a mouse event via CDP
1978
+ */
1979
+ async injectMouseEvent(params) {
1980
+ const cdp = await this.getCDPSession();
1981
+ const cdpButton = params.button === 'left'
1982
+ ? 'left'
1983
+ : params.button === 'right'
1984
+ ? 'right'
1985
+ : params.button === 'middle'
1986
+ ? 'middle'
1987
+ : 'none';
1988
+ await cdp.send('Input.dispatchMouseEvent', {
1989
+ type: params.type,
1990
+ x: params.x,
1991
+ y: params.y,
1992
+ button: cdpButton,
1993
+ clickCount: params.clickCount ?? 1,
1994
+ deltaX: params.deltaX ?? 0,
1995
+ deltaY: params.deltaY ?? 0,
1996
+ modifiers: params.modifiers ?? 0,
1997
+ });
1998
+ }
1999
+ /**
2000
+ * Inject a keyboard event via CDP
2001
+ */
2002
+ async injectKeyboardEvent(params) {
2003
+ const cdp = await this.getCDPSession();
2004
+ await cdp.send('Input.dispatchKeyEvent', {
2005
+ type: params.type,
2006
+ key: params.key,
2007
+ code: params.code,
2008
+ text: params.text,
2009
+ modifiers: params.modifiers ?? 0,
2010
+ });
2011
+ }
2012
+ /**
2013
+ * Inject touch event via CDP (for mobile emulation)
2014
+ */
2015
+ async injectTouchEvent(params) {
2016
+ const cdp = await this.getCDPSession();
2017
+ await cdp.send('Input.dispatchTouchEvent', {
2018
+ type: params.type,
2019
+ touchPoints: params.touchPoints.map((tp, i) => ({
2020
+ x: tp.x,
2021
+ y: tp.y,
2022
+ id: tp.id ?? i,
2023
+ })),
2024
+ modifiers: params.modifiers ?? 0,
2025
+ });
2026
+ }
2027
+ /**
2028
+ * Check if video recording is currently active
2029
+ */
2030
+ isRecording() {
2031
+ return this.recordingContext !== null;
2032
+ }
2033
+ /**
2034
+ * Start recording to a video file using Playwright's native video recording.
2035
+ * Creates a fresh browser context with video recording enabled.
2036
+ * Automatically captures current URL and transfers cookies/storage if no URL provided.
2037
+ *
2038
+ * @param outputPath - Path to the output video file (will be .webm)
2039
+ * @param url - Optional URL to navigate to (defaults to current page URL)
2040
+ */
2041
+ async startRecording(outputPath, url) {
2042
+ if (this.recordingContext) {
2043
+ throw new Error("Recording already in progress. Run 'record stop' first, or use 'record restart' to stop and start a new recording.");
2044
+ }
2045
+ if (!this.browser) {
2046
+ throw new Error('Browser not launched. Call launch first.');
2047
+ }
2048
+ // Check if output file already exists
2049
+ if (existsSync(outputPath)) {
2050
+ throw new Error(`Output file already exists: ${outputPath}`);
2051
+ }
2052
+ // Validate output path is .webm (Playwright native format)
2053
+ if (!outputPath.endsWith('.webm')) {
2054
+ throw new Error('Playwright native recording only supports WebM format. Please use a .webm extension.');
2055
+ }
2056
+ // Auto-capture current URL if none provided
2057
+ const currentPage = this.pages.length > 0 ? this.pages[this.activePageIndex] : null;
2058
+ const currentContext = this.contexts.length > 0 ? this.contexts[0] : null;
2059
+ if (!url && currentPage) {
2060
+ const currentUrl = currentPage.url();
2061
+ if (currentUrl && currentUrl !== 'about:blank') {
2062
+ url = currentUrl;
2063
+ }
2064
+ }
2065
+ // Capture state from current context (cookies + storage)
2066
+ let storageState;
2067
+ if (currentContext) {
2068
+ try {
2069
+ storageState = await currentContext.storageState();
2070
+ }
2071
+ catch {
2072
+ // Ignore errors - context might be closed or invalid
2073
+ }
2074
+ }
2075
+ // Create a temp directory for video recording
2076
+ const session = process.env.AGENT_BROWSER_SESSION || 'default';
2077
+ this.recordingTempDir = path.join(os.tmpdir(), `agent-browser-recording-${session}-${Date.now()}`);
2078
+ mkdirSync(this.recordingTempDir, { recursive: true });
2079
+ this.recordingOutputPath = outputPath;
2080
+ // Create a new context with video recording enabled and restored state
2081
+ const viewport = { width: 1280, height: 720 };
2082
+ this.recordingContext = await this.browser.newContext({
2083
+ viewport,
2084
+ recordVideo: {
2085
+ dir: this.recordingTempDir,
2086
+ size: viewport,
2087
+ },
2088
+ storageState,
2089
+ });
2090
+ this.recordingContext.setDefaultTimeout(10000);
2091
+ // Create a page in the recording context
2092
+ this.recordingPage = await this.recordingContext.newPage();
2093
+ // Add the recording context and page to our managed lists
2094
+ this.contexts.push(this.recordingContext);
2095
+ this.pages.push(this.recordingPage);
2096
+ this.activePageIndex = this.pages.length - 1;
2097
+ // Set up page tracking
2098
+ this.setupPageTracking(this.recordingPage);
2099
+ // Invalidate CDP session since we switched pages
2100
+ await this.invalidateCDPSession();
2101
+ // Navigate to URL if provided or captured
2102
+ if (url) {
2103
+ await this.recordingPage.goto(url, { waitUntil: 'load' });
2104
+ }
2105
+ }
2106
+ /**
2107
+ * Stop recording and save the video file
2108
+ * @returns Recording result with path
2109
+ */
2110
+ async stopRecording() {
2111
+ if (!this.recordingContext || !this.recordingPage) {
2112
+ return { path: '', frames: 0, error: 'No recording in progress' };
2113
+ }
2114
+ const outputPath = this.recordingOutputPath;
2115
+ try {
2116
+ // Get the video object before closing the page
2117
+ const video = this.recordingPage.video();
2118
+ // Remove recording page/context from our managed lists before closing
2119
+ const pageIndex = this.pages.indexOf(this.recordingPage);
2120
+ if (pageIndex !== -1) {
2121
+ this.pages.splice(pageIndex, 1);
2122
+ }
2123
+ const contextIndex = this.contexts.indexOf(this.recordingContext);
2124
+ if (contextIndex !== -1) {
2125
+ this.contexts.splice(contextIndex, 1);
2126
+ }
2127
+ // Close the page to finalize the video
2128
+ await this.recordingPage.close();
2129
+ // Save the video to the desired output path
2130
+ if (video) {
2131
+ await video.saveAs(outputPath);
2132
+ }
2133
+ // Clean up temp directory
2134
+ if (this.recordingTempDir) {
2135
+ rmSync(this.recordingTempDir, { recursive: true, force: true });
2136
+ }
2137
+ // Close the recording context
2138
+ await this.recordingContext.close();
2139
+ // Reset recording state
2140
+ this.recordingContext = null;
2141
+ this.recordingPage = null;
2142
+ this.recordingOutputPath = '';
2143
+ this.recordingTempDir = '';
2144
+ // Adjust active page index
2145
+ if (this.pages.length > 0) {
2146
+ this.activePageIndex = Math.min(this.activePageIndex, this.pages.length - 1);
2147
+ }
2148
+ else {
2149
+ this.activePageIndex = 0;
2150
+ }
2151
+ // Invalidate CDP session since we may have switched pages
2152
+ await this.invalidateCDPSession();
2153
+ return { path: outputPath, frames: 0 }; // Playwright doesn't expose frame count
2154
+ }
2155
+ catch (error) {
2156
+ // Clean up temp directory on error
2157
+ if (this.recordingTempDir) {
2158
+ rmSync(this.recordingTempDir, { recursive: true, force: true });
2159
+ }
2160
+ // Reset state on error
2161
+ this.recordingContext = null;
2162
+ this.recordingPage = null;
2163
+ this.recordingOutputPath = '';
2164
+ this.recordingTempDir = '';
2165
+ const message = error instanceof Error ? error.message : String(error);
2166
+ return { path: outputPath, frames: 0, error: message };
2167
+ }
2168
+ }
2169
+ /**
2170
+ * Restart recording - stops current recording (if any) and starts a new one.
2171
+ * Convenience method that combines stopRecording and startRecording.
2172
+ *
2173
+ * @param outputPath - Path to the output video file (must be .webm)
2174
+ * @param url - Optional URL to navigate to (defaults to current page URL)
2175
+ * @returns Result from stopping the previous recording (if any)
2176
+ */
2177
+ async restartRecording(outputPath, url) {
2178
+ let previousPath;
2179
+ let stopped = false;
2180
+ // Stop current recording if active
2181
+ if (this.recordingContext) {
2182
+ const result = await this.stopRecording();
2183
+ previousPath = result.path;
2184
+ stopped = true;
2185
+ }
2186
+ // Start new recording
2187
+ await this.startRecording(outputPath, url);
2188
+ return { previousPath, stopped };
2189
+ }
2190
+ /**
2191
+ * Close the browser and clean up
2192
+ */
2193
+ async close() {
2194
+ // Stop recording if active (saves video)
2195
+ if (this.recordingContext) {
2196
+ await this.stopRecording();
2197
+ }
2198
+ // Stop screencast if active
2199
+ if (this.screencastActive) {
2200
+ await this.stopScreencast();
2201
+ }
2202
+ // Clean up profiling state if active (without saving)
2203
+ if (this.profilingActive) {
2204
+ const cdp = this.cdpSession;
2205
+ if (cdp) {
2206
+ if (this.profileDataHandler) {
2207
+ cdp.off('Tracing.dataCollected', this.profileDataHandler);
2208
+ }
2209
+ if (this.profileCompleteHandler) {
2210
+ cdp.off('Tracing.tracingComplete', this.profileCompleteHandler);
2211
+ }
2212
+ await cdp.send('Tracing.end').catch(() => { });
2213
+ }
2214
+ this.profilingActive = false;
2215
+ this.profileChunks = [];
2216
+ this.profileEventsDropped = false;
2217
+ this.profileCompleteResolver = null;
2218
+ this.profileDataHandler = null;
2219
+ this.profileCompleteHandler = null;
2220
+ }
2221
+ // Clean up CDP session
2222
+ if (this.cdpSession) {
2223
+ await this.cdpSession.detach().catch(() => { });
2224
+ this.cdpSession = null;
2225
+ }
2226
+ if (this.browserbaseSessionId && this.browserbaseApiKey) {
2227
+ await this.closeBrowserbaseSession(this.browserbaseSessionId, this.browserbaseApiKey).catch((error) => {
2228
+ console.error('Failed to close Browserbase session:', error);
2229
+ });
2230
+ this.browser = null;
2231
+ }
2232
+ else if (this.browserUseSessionId && this.browserUseApiKey) {
2233
+ await this.closeBrowserUseSession(this.browserUseSessionId, this.browserUseApiKey).catch((error) => {
2234
+ console.error('Failed to close Browser Use session:', error);
2235
+ });
2236
+ this.browser = null;
2237
+ }
2238
+ else if (this.kernelSessionId && this.kernelApiKey) {
2239
+ await this.closeKernelSession(this.kernelSessionId, this.kernelApiKey).catch((error) => {
2240
+ console.error('Failed to close Kernel session:', error);
2241
+ });
2242
+ this.browser = null;
2243
+ }
2244
+ else if (this.cdpEndpoint !== null) {
2245
+ // CDP: only disconnect, don't close external app's pages
2246
+ if (this.browser) {
2247
+ await this.browser.close().catch(() => { });
2248
+ this.browser = null;
2249
+ }
2250
+ }
2251
+ else {
2252
+ // Regular browser: close everything
2253
+ for (const page of this.pages) {
2254
+ await page.close().catch(() => { });
2255
+ }
2256
+ for (const context of this.contexts) {
2257
+ await context.close().catch(() => { });
2258
+ }
2259
+ if (this.browser) {
2260
+ await this.browser.close().catch(() => { });
2261
+ this.browser = null;
2262
+ }
2263
+ }
2264
+ this.pages = [];
2265
+ this.contexts = [];
2266
+ this.cdpEndpoint = null;
2267
+ this.browserbaseSessionId = null;
2268
+ this.browserbaseApiKey = null;
2269
+ this.browserUseSessionId = null;
2270
+ this.browserUseApiKey = null;
2271
+ this.kernelSessionId = null;
2272
+ this.kernelApiKey = null;
2273
+ this.isPersistentContext = false;
2274
+ this.activePageIndex = 0;
2275
+ this.colorScheme = null;
2276
+ this.stealthEnabled = false;
2277
+ this.stealthConnectionKind = 'local';
2278
+ this.contextLocale = undefined;
2279
+ this.contextTimezoneId = undefined;
2280
+ this.contextHeaders = undefined;
2281
+ this.contextUserAgent = undefined;
2282
+ this.refMap = {};
2283
+ this.lastSnapshot = '';
2284
+ this.frameCallback = null;
2285
+ }
2286
+ }
2287
+ //# sourceMappingURL=browser.js.map