@dyyz1993/agent-browser 0.9.2

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 (187) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +907 -0
  3. package/bin/agent-browser-darwin-arm64 +0 -0
  4. package/bin/agent-browser.js +120 -0
  5. package/dist/__tests__/e2e/utils/test-helpers.d.ts +5 -0
  6. package/dist/__tests__/e2e/utils/test-helpers.d.ts.map +1 -0
  7. package/dist/__tests__/e2e/utils/test-helpers.js +22 -0
  8. package/dist/__tests__/e2e/utils/test-helpers.js.map +1 -0
  9. package/dist/__tests__/test-iframe.d.ts +2 -0
  10. package/dist/__tests__/test-iframe.d.ts.map +1 -0
  11. package/dist/__tests__/test-iframe.js +52 -0
  12. package/dist/__tests__/test-iframe.js.map +1 -0
  13. package/dist/__tests__/utils/parseCli.d.ts +20 -0
  14. package/dist/__tests__/utils/parseCli.d.ts.map +1 -0
  15. package/dist/__tests__/utils/parseCli.js +1086 -0
  16. package/dist/__tests__/utils/parseCli.js.map +1 -0
  17. package/dist/actions.d.ts +50 -0
  18. package/dist/actions.d.ts.map +1 -0
  19. package/dist/actions.js +2164 -0
  20. package/dist/actions.js.map +1 -0
  21. package/dist/browser.d.ts +556 -0
  22. package/dist/browser.d.ts.map +1 -0
  23. package/dist/browser.js +2599 -0
  24. package/dist/browser.js.map +1 -0
  25. package/dist/cli/commands.d.ts +8 -0
  26. package/dist/cli/commands.d.ts.map +1 -0
  27. package/dist/cli/commands.js +1038 -0
  28. package/dist/cli/commands.js.map +1 -0
  29. package/dist/cli/connection.d.ts +50 -0
  30. package/dist/cli/connection.d.ts.map +1 -0
  31. package/dist/cli/connection.js +595 -0
  32. package/dist/cli/connection.js.map +1 -0
  33. package/dist/cli/flags.d.ts +36 -0
  34. package/dist/cli/flags.d.ts.map +1 -0
  35. package/dist/cli/flags.js +206 -0
  36. package/dist/cli/flags.js.map +1 -0
  37. package/dist/cli/help.d.ts +4 -0
  38. package/dist/cli/help.d.ts.map +1 -0
  39. package/dist/cli/help.js +1024 -0
  40. package/dist/cli/help.js.map +1 -0
  41. package/dist/cli/output.d.ts +14 -0
  42. package/dist/cli/output.d.ts.map +1 -0
  43. package/dist/cli/output.js +456 -0
  44. package/dist/cli/output.js.map +1 -0
  45. package/dist/cli-new.d.ts +3 -0
  46. package/dist/cli-new.d.ts.map +1 -0
  47. package/dist/cli-new.js +308 -0
  48. package/dist/cli-new.js.map +1 -0
  49. package/dist/cli-old.d.ts +3 -0
  50. package/dist/cli-old.d.ts.map +1 -0
  51. package/dist/cli-old.js +1101 -0
  52. package/dist/cli-old.js.map +1 -0
  53. package/dist/cli.d.ts +3 -0
  54. package/dist/cli.d.ts.map +1 -0
  55. package/dist/cli.js +403 -0
  56. package/dist/cli.js.map +1 -0
  57. package/dist/content-detection.d.ts +18 -0
  58. package/dist/content-detection.d.ts.map +1 -0
  59. package/dist/content-detection.js +68 -0
  60. package/dist/content-detection.js.map +1 -0
  61. package/dist/daemon.d.ts +55 -0
  62. package/dist/daemon.d.ts.map +1 -0
  63. package/dist/daemon.js +426 -0
  64. package/dist/daemon.js.map +1 -0
  65. package/dist/diff.d.ts +42 -0
  66. package/dist/diff.d.ts.map +1 -0
  67. package/dist/diff.js +166 -0
  68. package/dist/diff.js.map +1 -0
  69. package/dist/human-mouse.d.ts +31 -0
  70. package/dist/human-mouse.d.ts.map +1 -0
  71. package/dist/human-mouse.js +184 -0
  72. package/dist/human-mouse.js.map +1 -0
  73. package/dist/ios-actions.d.ts +11 -0
  74. package/dist/ios-actions.d.ts.map +1 -0
  75. package/dist/ios-actions.js +228 -0
  76. package/dist/ios-actions.js.map +1 -0
  77. package/dist/ios-manager.d.ts +266 -0
  78. package/dist/ios-manager.d.ts.map +1 -0
  79. package/dist/ios-manager.js +1076 -0
  80. package/dist/ios-manager.js.map +1 -0
  81. package/dist/message-bridge.d.ts +10 -0
  82. package/dist/message-bridge.d.ts.map +1 -0
  83. package/dist/message-bridge.js +60 -0
  84. package/dist/message-bridge.js.map +1 -0
  85. package/dist/protocol.d.ts +26 -0
  86. package/dist/protocol.d.ts.map +1 -0
  87. package/dist/protocol.js +912 -0
  88. package/dist/protocol.js.map +1 -0
  89. package/dist/recorder/binding.d.ts +24 -0
  90. package/dist/recorder/binding.d.ts.map +1 -0
  91. package/dist/recorder/binding.js +215 -0
  92. package/dist/recorder/binding.js.map +1 -0
  93. package/dist/recorder/index.d.ts +4 -0
  94. package/dist/recorder/index.d.ts.map +1 -0
  95. package/dist/recorder/index.js +4 -0
  96. package/dist/recorder/index.js.map +1 -0
  97. package/dist/recorder/inject.js +1913 -0
  98. package/dist/recorder/recorder.d.ts +19 -0
  99. package/dist/recorder/recorder.d.ts.map +1 -0
  100. package/dist/recorder/recorder.js +101 -0
  101. package/dist/recorder/recorder.js.map +1 -0
  102. package/dist/recorder/store.d.ts +22 -0
  103. package/dist/recorder/store.d.ts.map +1 -0
  104. package/dist/recorder/store.js +150 -0
  105. package/dist/recorder/store.js.map +1 -0
  106. package/dist/recorder/types.d.ts +73 -0
  107. package/dist/recorder/types.d.ts.map +1 -0
  108. package/dist/recorder/types.js +5 -0
  109. package/dist/recorder/types.js.map +1 -0
  110. package/dist/snapshot.d.ts +81 -0
  111. package/dist/snapshot.d.ts.map +1 -0
  112. package/dist/snapshot.js +1348 -0
  113. package/dist/snapshot.js.map +1 -0
  114. package/dist/stream-server-standalone.d.ts +38 -0
  115. package/dist/stream-server-standalone.d.ts.map +1 -0
  116. package/dist/stream-server-standalone.js +494 -0
  117. package/dist/stream-server-standalone.js.map +1 -0
  118. package/dist/stream-server.d.ts +214 -0
  119. package/dist/stream-server.d.ts.map +1 -0
  120. package/dist/stream-server.js +811 -0
  121. package/dist/stream-server.js.map +1 -0
  122. package/dist/types.d.ts +914 -0
  123. package/dist/types.d.ts.map +1 -0
  124. package/dist/types.js +4 -0
  125. package/dist/types.js.map +1 -0
  126. package/dist/viewer-html.d.ts +2 -0
  127. package/dist/viewer-html.d.ts.map +1 -0
  128. package/dist/viewer-html.js +185 -0
  129. package/dist/viewer-html.js.map +1 -0
  130. package/dist/viewer-script.d.ts +47 -0
  131. package/dist/viewer-script.d.ts.map +1 -0
  132. package/dist/viewer-script.js +586 -0
  133. package/dist/viewer-script.js.map +1 -0
  134. package/package.json +86 -0
  135. package/scripts/build-all-platforms.sh +68 -0
  136. package/scripts/check-version-sync.js +39 -0
  137. package/scripts/check_goods_container.js +35 -0
  138. package/scripts/check_page_content.js +36 -0
  139. package/scripts/click_applause_rate.js +30 -0
  140. package/scripts/copy-native.js +36 -0
  141. package/scripts/copy-recorder.js +21 -0
  142. package/scripts/e2e-test-recorder.ts +584 -0
  143. package/scripts/explore_jd_page.js +31 -0
  144. package/scripts/extract_all_jd_data.js +80 -0
  145. package/scripts/extract_jd_product_detail.js +62 -0
  146. package/scripts/extract_jd_products_correct_links.js +78 -0
  147. package/scripts/extract_jd_products_final.js +80 -0
  148. package/scripts/extract_jd_reviews.js +48 -0
  149. package/scripts/extract_jd_seafood_final.js +78 -0
  150. package/scripts/extract_multiple_products.js +77 -0
  151. package/scripts/extract_products_no_scroll.js +68 -0
  152. package/scripts/extract_products_simple.js +68 -0
  153. package/scripts/find_applause_rate.js +26 -0
  154. package/scripts/find_jd_links.js +28 -0
  155. package/scripts/find_main_content.js +20 -0
  156. package/scripts/find_product_cards.js +38 -0
  157. package/scripts/find_root_content.js +26 -0
  158. package/scripts/find_unique_products.js +55 -0
  159. package/scripts/get_jd_product_detail.js +16 -0
  160. package/scripts/get_jd_products.js +23 -0
  161. package/scripts/get_jd_seafood_products.js +44 -0
  162. package/scripts/get_product_details_from_images.js +54 -0
  163. package/scripts/postinstall.js +235 -0
  164. package/scripts/scroll_and_get_products.js +47 -0
  165. package/scripts/scroll_deep_and_find.js +45 -0
  166. package/scripts/sync-version.js +69 -0
  167. package/scripts/verify-baidu-enter.ts +116 -0
  168. package/skills/agent-browser/SKILL.md +310 -0
  169. package/skills/agent-browser/references/authentication.md +198 -0
  170. package/skills/agent-browser/references/commands.md +471 -0
  171. package/skills/agent-browser/references/data-extraction.md +377 -0
  172. package/skills/agent-browser/references/proxy-support.md +188 -0
  173. package/skills/agent-browser/references/session-management.md +197 -0
  174. package/skills/agent-browser/references/snapshot-refs.md +379 -0
  175. package/skills/agent-browser/references/video-recording.md +173 -0
  176. package/skills/agent-browser/templates/api-interception.sh +53 -0
  177. package/skills/agent-browser/templates/authenticated-session.sh +97 -0
  178. package/skills/agent-browser/templates/capture-workflow.sh +69 -0
  179. package/skills/agent-browser/templates/data-extraction.sh +210 -0
  180. package/skills/agent-browser/templates/form-automation.sh +62 -0
  181. package/skills/skill-creator/LICENSE.txt +202 -0
  182. package/skills/skill-creator/SKILL.md +356 -0
  183. package/skills/skill-creator/references/output-patterns.md +82 -0
  184. package/skills/skill-creator/references/workflows.md +28 -0
  185. package/skills/skill-creator/scripts/init_skill.py +303 -0
  186. package/skills/skill-creator/scripts/package_skill.py +113 -0
  187. package/skills/skill-creator/scripts/quick_validate.py +95 -0
@@ -0,0 +1,2599 @@
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 { fileURLToPath } from 'node:url';
6
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
7
+ import { getEnhancedSnapshot, parseRef } from './snapshot.js';
8
+ import { getEventCallbacks } from './actions.js';
9
+ /**
10
+ * Manages the Playwright browser lifecycle with multiple tabs/windows
11
+ */
12
+ export class BrowserManager {
13
+ browser = null;
14
+ cdpEndpoint = null; // stores port number or full URL
15
+ isPersistentContext = false;
16
+ browserbaseSessionId = null;
17
+ browserbaseApiKey = null;
18
+ browserUseSessionId = null;
19
+ browserUseApiKey = null;
20
+ kernelSessionId = null;
21
+ kernelApiKey = null;
22
+ contexts = [];
23
+ pages = [];
24
+ activePageIndex = 0;
25
+ dialogHandler = null;
26
+ trackedRequests = [];
27
+ routes = new Map();
28
+ consoleMessages = [];
29
+ pageErrors = [];
30
+ isRecordingHar = false;
31
+ refMap = {};
32
+ lastSnapshot = '';
33
+ scopedHeaderRoutes = new Map();
34
+ // CDP session for screencast and input injection
35
+ cdpSession = null;
36
+ screencastActive = false;
37
+ screencastShouldBeActive = false;
38
+ screencastSessionId = 0;
39
+ frameCallback = null;
40
+ screencastFrameHandler = null;
41
+ lastScreencastOptions = null;
42
+ // Video recording (Playwright native)
43
+ recordingContext = null;
44
+ recordingPage = null;
45
+ recordingOutputPath = '';
46
+ recordingTempDir = '';
47
+ // User interaction recorder
48
+ recorderSessionId = null;
49
+ recorderBindingName = null; // 唯一绑定名称,避免 Playwright 绑定冲突
50
+ recorderStartTime = 0;
51
+ recorderSteps = [];
52
+ recorderPages = [];
53
+ recorderPageHandler = null;
54
+ navigationHistory = [];
55
+ navigationHistoryIndex = -1;
56
+ lastNavigationUrl = '';
57
+ lastNavigationTime = 0;
58
+ recorderNavigatedHandler = null;
59
+ recorderFrameAttachedHandler = null;
60
+ /**
61
+ * Check if browser is launched and still connected
62
+ */
63
+ isLaunched() {
64
+ if (this.isPersistentContext)
65
+ return true;
66
+ if (!this.browser)
67
+ return false;
68
+ // Also check if the browser is still connected (user might have closed it manually)
69
+ return this.browser.isConnected();
70
+ }
71
+ /**
72
+ * Get enhanced snapshot with refs and cache the ref map
73
+ */
74
+ async getSnapshot(options) {
75
+ const frame = options?.framePath ? this.getFrame(options.framePath) : this.getFrame();
76
+ const snapshot = await getEnhancedSnapshot(frame, options);
77
+ this.refMap = snapshot.refs;
78
+ this.lastSnapshot = snapshot.tree;
79
+ return snapshot;
80
+ }
81
+ /**
82
+ * Get the cached ref map from last snapshot
83
+ */
84
+ getRefMap() {
85
+ return this.refMap;
86
+ }
87
+ /**
88
+ * Get a locator from a ref (e.g., "e1", "@e1", "ref=e1")
89
+ * Returns null if ref doesn't exist or is invalid
90
+ * @param refArg - The ref string (e.g., "e1", "@e1", "ref=e1")
91
+ * @param framePath - Optional path to iframe where the ref was captured
92
+ */
93
+ getLocatorFromRef(refArg, framePath) {
94
+ const ref = parseRef(refArg);
95
+ if (!ref)
96
+ return null;
97
+ const refData = this.refMap[ref];
98
+ if (!refData)
99
+ return null;
100
+ const frame = this.getFrame(framePath);
101
+ if (refData.role === 'clickable' || refData.role === 'focusable') {
102
+ return frame.locator(refData.selector);
103
+ }
104
+ let locator;
105
+ if (refData.name) {
106
+ locator = frame.getByRole(refData.role, { name: refData.name, exact: true });
107
+ }
108
+ else {
109
+ locator = frame.getByRole(refData.role);
110
+ }
111
+ if (refData.nth !== undefined) {
112
+ locator = locator.nth(refData.nth);
113
+ }
114
+ return locator;
115
+ }
116
+ /**
117
+ * Check if a selector looks like a ref
118
+ */
119
+ isRef(selector) {
120
+ return parseRef(selector) !== null;
121
+ }
122
+ /**
123
+ * Get locator - supports both refs and regular selectors
124
+ */
125
+ getLocator(selectorOrRef, framePath) {
126
+ const locator = this.getLocatorFromRef(selectorOrRef, framePath);
127
+ if (locator)
128
+ return locator;
129
+ const frame = framePath ? this.getFrame(framePath) : this.getFrame();
130
+ return frame.locator(selectorOrRef);
131
+ }
132
+ /**
133
+ * Get the current active page, throws if not launched
134
+ */
135
+ getPage() {
136
+ if (this.pages.length === 0) {
137
+ throw new Error('Browser not launched. Call launch first.');
138
+ }
139
+ return this.pages[this.activePageIndex];
140
+ }
141
+ /**
142
+ * Get frame by optional path
143
+ * @param framePath - Optional path to iframe (e.g., "#frame1/#frame2/#frame3")
144
+ * - If not provided, returns the main frame of current page
145
+ * - Path is absolute from main frame, using "/" as separator
146
+ * - Supports multiple matching strategies:
147
+ * - Index: "0", "1", "2" - match by position
148
+ * - Name/ID: "#my-frame", "my-frame" - match by name or id attribute
149
+ * - URL: partial URL match like "httpbin.org"
150
+ * @returns Frame for the target iframe
151
+ */
152
+ getFrame(framePath) {
153
+ if (!framePath) {
154
+ return this.getPage().mainFrame();
155
+ }
156
+ return this.getFrameByPath(framePath);
157
+ }
158
+ /**
159
+ * Internal method to get frame by path
160
+ * Path is absolute from main frame, using "/" as separator
161
+ */
162
+ getFrameByPath(framePath) {
163
+ const page = this.getPage();
164
+ const selectors = framePath
165
+ .split('/')
166
+ .map((s) => s.trim())
167
+ .filter(Boolean);
168
+ if (selectors.length === 0) {
169
+ return page.mainFrame();
170
+ }
171
+ let current = page.mainFrame();
172
+ for (let i = 0; i < selectors.length; i++) {
173
+ const selector = selectors[i];
174
+ const childFrames = current.childFrames();
175
+ if (childFrames.length === 0) {
176
+ throw new Error(`No child frames found for selector "${selector}" at path position ${i + 1}. ` +
177
+ `Path: "${framePath}". ` +
178
+ `Current frame has no child frames.`);
179
+ }
180
+ const matchedFrame = this.findMatchingFrame(childFrames, selector);
181
+ if (!matchedFrame) {
182
+ const availableInfo = childFrames.map((f, idx) => ({
183
+ index: idx,
184
+ name: f.name(),
185
+ url: f.url(),
186
+ }));
187
+ throw new Error(`Frame not found for selector "${selector}" at path position ${i + 1}. ` +
188
+ `Path: "${framePath}". ` +
189
+ `Available child frames: ${JSON.stringify(availableInfo, null, 2)}`);
190
+ }
191
+ current = matchedFrame;
192
+ }
193
+ return current;
194
+ }
195
+ /**
196
+ * Find a matching frame from a list of child frames
197
+ * Supports matching by:
198
+ * - Index: "0", "1", "2"
199
+ * - Name/ID: "#my-frame", "my-frame"
200
+ * - URL: partial URL match
201
+ */
202
+ findMatchingFrame(frames, selector) {
203
+ // 1. Try index matching (e.g., "0", "1", "2")
204
+ const indexMatch = selector.match(/^(\d+)$/);
205
+ if (indexMatch) {
206
+ const index = parseInt(indexMatch[1], 10);
207
+ return frames[index];
208
+ }
209
+ // 2. Try name/ID matching
210
+ const cleanSelector = selector.replace('#', '');
211
+ const nameMatch = frames.find((f) => f.name() === selector || f.name() === cleanSelector);
212
+ if (nameMatch)
213
+ return nameMatch;
214
+ // 3. Try URL path matching (e.g., "outer-iframe" matches URL containing "/outer-iframe")
215
+ const urlPathMatch = frames.find((f) => {
216
+ const url = f.url();
217
+ // Match by path segment in URL (e.g., "outer-iframe" matches "/.../outer-iframe")
218
+ return url.includes(`/${cleanSelector}`) || url.endsWith(`/${cleanSelector}`);
219
+ });
220
+ if (urlPathMatch)
221
+ return urlPathMatch;
222
+ return undefined;
223
+ }
224
+ /**
225
+ * Set up dialog handler
226
+ */
227
+ setDialogHandler(response, promptText) {
228
+ const page = this.getPage();
229
+ // Remove existing handler if any
230
+ if (this.dialogHandler) {
231
+ page.removeListener('dialog', this.dialogHandler);
232
+ }
233
+ this.dialogHandler = async (dialog) => {
234
+ if (response === 'accept') {
235
+ await dialog.accept(promptText);
236
+ }
237
+ else {
238
+ await dialog.dismiss();
239
+ }
240
+ };
241
+ page.on('dialog', this.dialogHandler);
242
+ }
243
+ /**
244
+ * Clear dialog handler
245
+ */
246
+ clearDialogHandler() {
247
+ if (this.dialogHandler) {
248
+ const page = this.getPage();
249
+ page.removeListener('dialog', this.dialogHandler);
250
+ this.dialogHandler = null;
251
+ }
252
+ }
253
+ /**
254
+ * Start tracking requests
255
+ */
256
+ startRequestTracking() {
257
+ const page = this.getPage();
258
+ page.on('request', (request) => {
259
+ this.trackedRequests.push({
260
+ url: request.url(),
261
+ method: request.method(),
262
+ headers: request.headers(),
263
+ timestamp: Date.now(),
264
+ resourceType: request.resourceType(),
265
+ });
266
+ });
267
+ }
268
+ /**
269
+ * Get tracked requests
270
+ */
271
+ getRequests(filter) {
272
+ if (filter) {
273
+ return this.trackedRequests.filter((r) => r.url.includes(filter));
274
+ }
275
+ return this.trackedRequests;
276
+ }
277
+ /**
278
+ * Clear tracked requests
279
+ */
280
+ clearRequests() {
281
+ this.trackedRequests = [];
282
+ }
283
+ /**
284
+ * Add a route to intercept requests
285
+ */
286
+ async addRoute(url, options) {
287
+ const page = this.getPage();
288
+ const handler = async (route) => {
289
+ if (options.abort) {
290
+ await route.abort();
291
+ }
292
+ else if (options.response) {
293
+ await route.fulfill({
294
+ status: options.response.status ?? 200,
295
+ body: options.response.body ?? '',
296
+ contentType: options.response.contentType ?? 'text/plain',
297
+ headers: options.response.headers,
298
+ });
299
+ }
300
+ else {
301
+ await route.continue();
302
+ }
303
+ };
304
+ this.routes.set(url, handler);
305
+ await page.route(url, handler);
306
+ }
307
+ /**
308
+ * Remove a route
309
+ */
310
+ async removeRoute(url) {
311
+ const page = this.getPage();
312
+ if (url) {
313
+ const handler = this.routes.get(url);
314
+ if (handler) {
315
+ await page.unroute(url, handler);
316
+ this.routes.delete(url);
317
+ }
318
+ }
319
+ else {
320
+ // Remove all routes
321
+ for (const [routeUrl, handler] of this.routes) {
322
+ await page.unroute(routeUrl, handler);
323
+ }
324
+ this.routes.clear();
325
+ }
326
+ }
327
+ /**
328
+ * Set geolocation
329
+ */
330
+ async setGeolocation(latitude, longitude, accuracy) {
331
+ const context = this.contexts[0];
332
+ if (context) {
333
+ await context.setGeolocation({ latitude, longitude, accuracy });
334
+ }
335
+ }
336
+ /**
337
+ * Set permissions
338
+ */
339
+ async setPermissions(permissions, grant) {
340
+ const context = this.contexts[0];
341
+ if (context) {
342
+ if (grant) {
343
+ await context.grantPermissions(permissions);
344
+ }
345
+ else {
346
+ await context.clearPermissions();
347
+ }
348
+ }
349
+ }
350
+ /**
351
+ * Set viewport
352
+ */
353
+ async setViewport(width, height) {
354
+ const page = this.getPage();
355
+ await page.setViewportSize({ width, height });
356
+ }
357
+ /**
358
+ * Set device scale factor (devicePixelRatio) via CDP
359
+ * This sets window.devicePixelRatio which affects how the page renders and responds to media queries
360
+ *
361
+ * Note: When using CDP to set deviceScaleFactor, screenshots will be at logical pixel dimensions
362
+ * (viewport size), not physical pixel dimensions (viewport × scale). This is a Playwright limitation
363
+ * when using CDP emulation on existing contexts. For true HiDPI screenshots with physical pixels,
364
+ * deviceScaleFactor must be set at context creation time.
365
+ *
366
+ * Must be called after setViewport to work correctly
367
+ */
368
+ async setDeviceScaleFactor(deviceScaleFactor, width, height, mobile = false) {
369
+ const cdp = await this.getCDPSession();
370
+ await cdp.send('Emulation.setDeviceMetricsOverride', {
371
+ width,
372
+ height,
373
+ deviceScaleFactor,
374
+ mobile,
375
+ });
376
+ }
377
+ /**
378
+ * Clear device metrics override to restore default devicePixelRatio
379
+ */
380
+ async clearDeviceMetricsOverride() {
381
+ const cdp = await this.getCDPSession();
382
+ await cdp.send('Emulation.clearDeviceMetricsOverride');
383
+ }
384
+ /**
385
+ * Get device descriptor
386
+ */
387
+ getDevice(deviceName) {
388
+ return devices[deviceName];
389
+ }
390
+ /**
391
+ * List available devices
392
+ */
393
+ listDevices() {
394
+ return Object.keys(devices);
395
+ }
396
+ /**
397
+ * Start console message tracking
398
+ */
399
+ startConsoleTracking() {
400
+ const page = this.getPage();
401
+ page.on('console', (msg) => {
402
+ this.consoleMessages.push({
403
+ type: msg.type(),
404
+ text: msg.text(),
405
+ timestamp: Date.now(),
406
+ });
407
+ });
408
+ }
409
+ /**
410
+ * Get console messages
411
+ */
412
+ getConsoleMessages() {
413
+ return this.consoleMessages;
414
+ }
415
+ /**
416
+ * Clear console messages
417
+ */
418
+ clearConsoleMessages() {
419
+ this.consoleMessages = [];
420
+ }
421
+ /**
422
+ * Start error tracking
423
+ */
424
+ startErrorTracking() {
425
+ const page = this.getPage();
426
+ page.on('pageerror', (error) => {
427
+ this.pageErrors.push({
428
+ message: error.message,
429
+ timestamp: Date.now(),
430
+ });
431
+ });
432
+ }
433
+ /**
434
+ * Get page errors
435
+ */
436
+ getPageErrors() {
437
+ return this.pageErrors;
438
+ }
439
+ /**
440
+ * Clear page errors
441
+ */
442
+ clearPageErrors() {
443
+ this.pageErrors = [];
444
+ }
445
+ /**
446
+ * Start HAR recording
447
+ */
448
+ async startHarRecording() {
449
+ // HAR is started at context level, flag for tracking
450
+ this.isRecordingHar = true;
451
+ }
452
+ /**
453
+ * Check if HAR recording
454
+ */
455
+ isHarRecording() {
456
+ return this.isRecordingHar;
457
+ }
458
+ /**
459
+ * Set offline mode
460
+ */
461
+ async setOffline(offline) {
462
+ const context = this.contexts[0];
463
+ if (context) {
464
+ await context.setOffline(offline);
465
+ }
466
+ }
467
+ /**
468
+ * Set extra HTTP headers (global - all requests)
469
+ */
470
+ async setExtraHeaders(headers) {
471
+ const context = this.contexts[0];
472
+ if (context) {
473
+ await context.setExtraHTTPHeaders(headers);
474
+ }
475
+ }
476
+ /**
477
+ * Set scoped HTTP headers (only for requests matching the origin)
478
+ * Uses route interception to add headers only to matching requests
479
+ */
480
+ async setScopedHeaders(origin, headers) {
481
+ const page = this.getPage();
482
+ // Build URL pattern from origin (e.g., "api.example.com" -> "**://api.example.com/**")
483
+ // Handle both full URLs and just hostnames
484
+ let urlPattern;
485
+ try {
486
+ const url = new URL(origin.startsWith('http') ? origin : `https://${origin}`);
487
+ // Match any protocol, the host, and any path
488
+ urlPattern = `**://${url.host}/**`;
489
+ }
490
+ catch {
491
+ // If parsing fails, treat as hostname pattern
492
+ urlPattern = `**://${origin}/**`;
493
+ }
494
+ // Remove existing route for this origin if any
495
+ const existingHandler = this.scopedHeaderRoutes.get(urlPattern);
496
+ if (existingHandler) {
497
+ await page.unroute(urlPattern, existingHandler);
498
+ }
499
+ // Create handler that adds headers to matching requests
500
+ const handler = async (route) => {
501
+ const requestHeaders = route.request().headers();
502
+ await route.continue({
503
+ headers: {
504
+ ...requestHeaders,
505
+ ...headers,
506
+ },
507
+ });
508
+ };
509
+ // Store and register the route
510
+ this.scopedHeaderRoutes.set(urlPattern, handler);
511
+ await page.route(urlPattern, handler);
512
+ }
513
+ /**
514
+ * Clear scoped headers for an origin (or all if no origin specified)
515
+ */
516
+ async clearScopedHeaders(origin) {
517
+ const page = this.getPage();
518
+ if (origin) {
519
+ let urlPattern;
520
+ try {
521
+ const url = new URL(origin.startsWith('http') ? origin : `https://${origin}`);
522
+ urlPattern = `**://${url.host}/**`;
523
+ }
524
+ catch {
525
+ urlPattern = `**://${origin}/**`;
526
+ }
527
+ const handler = this.scopedHeaderRoutes.get(urlPattern);
528
+ if (handler) {
529
+ await page.unroute(urlPattern, handler);
530
+ this.scopedHeaderRoutes.delete(urlPattern);
531
+ }
532
+ }
533
+ else {
534
+ // Clear all scoped header routes
535
+ for (const [pattern, handler] of this.scopedHeaderRoutes) {
536
+ await page.unroute(pattern, handler);
537
+ }
538
+ this.scopedHeaderRoutes.clear();
539
+ }
540
+ }
541
+ /**
542
+ * Start tracing
543
+ */
544
+ async startTracing(options) {
545
+ const context = this.contexts[0];
546
+ if (context) {
547
+ await context.tracing.start({
548
+ screenshots: options.screenshots ?? true,
549
+ snapshots: options.snapshots ?? true,
550
+ });
551
+ }
552
+ }
553
+ /**
554
+ * Stop tracing and save
555
+ */
556
+ async stopTracing(path) {
557
+ const context = this.contexts[0];
558
+ if (context) {
559
+ await context.tracing.stop({ path });
560
+ }
561
+ }
562
+ /**
563
+ * Save storage state (cookies, localStorage, etc.)
564
+ */
565
+ async saveStorageState(path) {
566
+ const context = this.contexts[0];
567
+ if (context) {
568
+ await context.storageState({ path });
569
+ }
570
+ }
571
+ /**
572
+ * Get all pages
573
+ */
574
+ getPages() {
575
+ return this.pages;
576
+ }
577
+ /**
578
+ * Get current page index
579
+ */
580
+ getActiveIndex() {
581
+ return this.activePageIndex;
582
+ }
583
+ /**
584
+ * Get the current browser instance
585
+ */
586
+ getBrowser() {
587
+ return this.browser;
588
+ }
589
+ /**
590
+ * Check if an existing CDP connection is still alive
591
+ * by verifying we can access browser contexts and that at least one has pages
592
+ */
593
+ isCdpConnectionAlive() {
594
+ console.log('[DEBUG isCdpConnectionAlive] browser exists:', !!this.browser);
595
+ if (!this.browser)
596
+ return false;
597
+ try {
598
+ const contexts = this.browser.contexts();
599
+ console.log('[DEBUG isCdpConnectionAlive] contexts count:', contexts.length);
600
+ if (contexts.length === 0) {
601
+ console.log('[DEBUG isCdpConnectionAlive] returning false: no contexts');
602
+ return false;
603
+ }
604
+ const pagesPerContext = contexts.map((context) => context.pages().length);
605
+ console.log('[DEBUG isCdpConnectionAlive] pages per context:', pagesPerContext);
606
+ const hasPages = contexts.some((context) => context.pages().length > 0);
607
+ console.log('[DEBUG isCdpConnectionAlive] hasPages:', hasPages);
608
+ return hasPages;
609
+ }
610
+ catch (e) {
611
+ console.log('[DEBUG isCdpConnectionAlive] exception:', e);
612
+ return false;
613
+ }
614
+ }
615
+ /**
616
+ * Check if CDP connection needs to be re-established
617
+ */
618
+ needsCdpReconnect(cdpEndpoint) {
619
+ const isConnected = this.browser?.isConnected();
620
+ const endpointMatch = this.cdpEndpoint === cdpEndpoint;
621
+ const isAlive = this.isCdpConnectionAlive();
622
+ console.log('[DEBUG needsCdpReconnect] isConnected:', isConnected);
623
+ console.log('[DEBUG needsCdpReconnect] endpointMatch:', endpointMatch, '(this:', this.cdpEndpoint, 'vs param:', cdpEndpoint, ')');
624
+ console.log('[DEBUG needsCdpReconnect] isCdpConnectionAlive:', isAlive);
625
+ if (!isConnected) {
626
+ console.log('[DEBUG needsCdpReconnect] returning true: not connected');
627
+ return true;
628
+ }
629
+ if (!endpointMatch) {
630
+ console.log('[DEBUG needsCdpReconnect] returning true: endpoint mismatch');
631
+ return true;
632
+ }
633
+ if (!isAlive) {
634
+ console.log('[DEBUG needsCdpReconnect] returning true: not alive');
635
+ return true;
636
+ }
637
+ console.log('[DEBUG needsCdpReconnect] returning false: all checks passed');
638
+ return false;
639
+ }
640
+ /**
641
+ * Close a Browserbase session via API
642
+ */
643
+ async closeBrowserbaseSession(sessionId, apiKey) {
644
+ await fetch(`https://api.browserbase.com/v1/sessions/${sessionId}`, {
645
+ method: 'DELETE',
646
+ headers: {
647
+ 'X-BB-API-Key': apiKey,
648
+ },
649
+ });
650
+ }
651
+ /**
652
+ * Close a Browser Use session via API
653
+ */
654
+ async closeBrowserUseSession(sessionId, apiKey) {
655
+ const response = await fetch(`https://api.browser-use.com/api/v2/browsers/${sessionId}`, {
656
+ method: 'PATCH',
657
+ headers: {
658
+ 'Content-Type': 'application/json',
659
+ 'X-Browser-Use-API-Key': apiKey,
660
+ },
661
+ body: JSON.stringify({ action: 'stop' }),
662
+ });
663
+ if (!response.ok) {
664
+ throw new Error(`Failed to close Browser Use session: ${response.statusText}`);
665
+ }
666
+ }
667
+ /**
668
+ * Close a Kernel session via API
669
+ */
670
+ async closeKernelSession(sessionId, apiKey) {
671
+ const response = await fetch(`https://api.onkernel.com/browsers/${sessionId}`, {
672
+ method: 'DELETE',
673
+ headers: {
674
+ Authorization: `Bearer ${apiKey}`,
675
+ },
676
+ });
677
+ if (!response.ok) {
678
+ throw new Error(`Failed to close Kernel session: ${response.statusText}`);
679
+ }
680
+ }
681
+ /**
682
+ * Connect to Browserbase remote browser via CDP.
683
+ * Requires BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID environment variables.
684
+ */
685
+ async connectToBrowserbase() {
686
+ const browserbaseApiKey = process.env.BROWSERBASE_API_KEY;
687
+ const browserbaseProjectId = process.env.BROWSERBASE_PROJECT_ID;
688
+ if (!browserbaseApiKey || !browserbaseProjectId) {
689
+ throw new Error('BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID are required when using browserbase as a provider');
690
+ }
691
+ const response = await fetch('https://api.browserbase.com/v1/sessions', {
692
+ method: 'POST',
693
+ headers: {
694
+ 'Content-Type': 'application/json',
695
+ 'X-BB-API-Key': browserbaseApiKey,
696
+ },
697
+ body: JSON.stringify({
698
+ projectId: browserbaseProjectId,
699
+ }),
700
+ });
701
+ if (!response.ok) {
702
+ throw new Error(`Failed to create Browserbase session: ${response.statusText}`);
703
+ }
704
+ const session = (await response.json());
705
+ const browser = await chromium.connectOverCDP(session.connectUrl).catch(() => {
706
+ throw new Error('Failed to connect to Browserbase session via CDP');
707
+ });
708
+ try {
709
+ const contexts = browser.contexts();
710
+ if (contexts.length === 0) {
711
+ throw new Error('No browser context found in Browserbase session');
712
+ }
713
+ const context = contexts[0];
714
+ const pages = context.pages();
715
+ const page = pages[0] ?? (await context.newPage());
716
+ this.browserbaseSessionId = session.id;
717
+ this.browserbaseApiKey = browserbaseApiKey;
718
+ this.browser = browser;
719
+ context.setDefaultTimeout(10000);
720
+ this.contexts.push(context);
721
+ this.setupContextTracking(context);
722
+ this.pages.push(page);
723
+ this.activePageIndex = 0;
724
+ this.setupPageTracking(page);
725
+ this.setupContextTracking(context);
726
+ }
727
+ catch (error) {
728
+ await this.closeBrowserbaseSession(session.id, browserbaseApiKey).catch((sessionError) => {
729
+ console.error('Failed to close Browserbase session during cleanup:', sessionError);
730
+ });
731
+ throw error;
732
+ }
733
+ }
734
+ /**
735
+ * Find or create a Kernel profile by name.
736
+ * Returns the profile object if successful.
737
+ */
738
+ async findOrCreateKernelProfile(profileName, apiKey) {
739
+ // First, try to get the existing profile
740
+ const getResponse = await fetch(`https://api.onkernel.com/profiles/${encodeURIComponent(profileName)}`, {
741
+ method: 'GET',
742
+ headers: {
743
+ Authorization: `Bearer ${apiKey}`,
744
+ },
745
+ });
746
+ if (getResponse.ok) {
747
+ // Profile exists, return it
748
+ return { name: profileName };
749
+ }
750
+ if (getResponse.status !== 404) {
751
+ throw new Error(`Failed to check Kernel profile: ${getResponse.statusText}`);
752
+ }
753
+ // Profile doesn't exist, create it
754
+ const createResponse = await fetch('https://api.onkernel.com/profiles', {
755
+ method: 'POST',
756
+ headers: {
757
+ 'Content-Type': 'application/json',
758
+ Authorization: `Bearer ${apiKey}`,
759
+ },
760
+ body: JSON.stringify({ name: profileName }),
761
+ });
762
+ if (!createResponse.ok) {
763
+ throw new Error(`Failed to create Kernel profile: ${createResponse.statusText}`);
764
+ }
765
+ return { name: profileName };
766
+ }
767
+ /**
768
+ * Connect to Kernel remote browser via CDP.
769
+ * Requires KERNEL_API_KEY environment variable.
770
+ */
771
+ async connectToKernel() {
772
+ const kernelApiKey = process.env.KERNEL_API_KEY;
773
+ if (!kernelApiKey) {
774
+ throw new Error('KERNEL_API_KEY is required when using kernel as a provider');
775
+ }
776
+ // Find or create profile if KERNEL_PROFILE_NAME is set
777
+ const profileName = process.env.KERNEL_PROFILE_NAME;
778
+ let profileConfig;
779
+ if (profileName) {
780
+ await this.findOrCreateKernelProfile(profileName, kernelApiKey);
781
+ profileConfig = {
782
+ profile: {
783
+ name: profileName,
784
+ save_changes: true, // Save cookies/state back to the profile when session ends
785
+ },
786
+ };
787
+ }
788
+ const response = await fetch('https://api.onkernel.com/browsers', {
789
+ method: 'POST',
790
+ headers: {
791
+ 'Content-Type': 'application/json',
792
+ Authorization: `Bearer ${kernelApiKey}`,
793
+ },
794
+ body: JSON.stringify({
795
+ // Kernel browsers are headful by default with stealth mode available
796
+ // The user can configure these via environment variables if needed
797
+ headless: process.env.KERNEL_HEADLESS?.toLowerCase() === 'true',
798
+ stealth: process.env.KERNEL_STEALTH?.toLowerCase() !== 'false', // Default to stealth mode
799
+ timeout_seconds: parseInt(process.env.KERNEL_TIMEOUT_SECONDS || '300', 10),
800
+ // Load and save to a profile if specified
801
+ ...profileConfig,
802
+ }),
803
+ });
804
+ if (!response.ok) {
805
+ throw new Error(`Failed to create Kernel session: ${response.statusText}`);
806
+ }
807
+ let session;
808
+ try {
809
+ session = (await response.json());
810
+ }
811
+ catch (error) {
812
+ throw new Error(`Failed to parse Kernel session response: ${error instanceof Error ? error.message : String(error)}`);
813
+ }
814
+ if (!session.session_id || !session.cdp_ws_url) {
815
+ throw new Error(`Invalid Kernel session response: missing ${!session.session_id ? 'session_id' : 'cdp_ws_url'}`);
816
+ }
817
+ const browser = await chromium.connectOverCDP(session.cdp_ws_url).catch(() => {
818
+ throw new Error('Failed to connect to Kernel session via CDP');
819
+ });
820
+ try {
821
+ const contexts = browser.contexts();
822
+ let context;
823
+ let page;
824
+ // Kernel browsers launch with a default context and page
825
+ if (contexts.length === 0) {
826
+ context = await browser.newContext();
827
+ page = await context.newPage();
828
+ }
829
+ else {
830
+ context = contexts[0];
831
+ const pages = context.pages();
832
+ page = pages[0] ?? (await context.newPage());
833
+ }
834
+ this.kernelSessionId = session.session_id;
835
+ this.kernelApiKey = kernelApiKey;
836
+ this.browser = browser;
837
+ context.setDefaultTimeout(60000);
838
+ this.contexts.push(context);
839
+ this.pages.push(page);
840
+ this.activePageIndex = 0;
841
+ this.setupPageTracking(page);
842
+ this.setupContextTracking(context);
843
+ }
844
+ catch (error) {
845
+ await this.closeKernelSession(session.session_id, kernelApiKey).catch((sessionError) => {
846
+ console.error('Failed to close Kernel session during cleanup:', sessionError);
847
+ });
848
+ throw error;
849
+ }
850
+ }
851
+ /**
852
+ * Connect to Browser Use remote browser via CDP.
853
+ * Requires BROWSER_USE_API_KEY environment variable.
854
+ */
855
+ async connectToBrowserUse() {
856
+ const browserUseApiKey = process.env.BROWSER_USE_API_KEY;
857
+ if (!browserUseApiKey) {
858
+ throw new Error('BROWSER_USE_API_KEY is required when using browseruse as a provider');
859
+ }
860
+ const response = await fetch('https://api.browser-use.com/api/v2/browsers', {
861
+ method: 'POST',
862
+ headers: {
863
+ 'Content-Type': 'application/json',
864
+ 'X-Browser-Use-API-Key': browserUseApiKey,
865
+ },
866
+ body: JSON.stringify({}),
867
+ });
868
+ if (!response.ok) {
869
+ throw new Error(`Failed to create Browser Use session: ${response.statusText}`);
870
+ }
871
+ let session;
872
+ try {
873
+ session = (await response.json());
874
+ }
875
+ catch (error) {
876
+ throw new Error(`Failed to parse Browser Use session response: ${error instanceof Error ? error.message : String(error)}`);
877
+ }
878
+ if (!session.id || !session.cdpUrl) {
879
+ throw new Error(`Invalid Browser Use session response: missing ${!session.id ? 'id' : 'cdpUrl'}`);
880
+ }
881
+ const browser = await chromium.connectOverCDP(session.cdpUrl).catch(() => {
882
+ throw new Error('Failed to connect to Browser Use session via CDP');
883
+ });
884
+ try {
885
+ const contexts = browser.contexts();
886
+ let context;
887
+ let page;
888
+ if (contexts.length === 0) {
889
+ context = await browser.newContext();
890
+ page = await context.newPage();
891
+ }
892
+ else {
893
+ context = contexts[0];
894
+ const pages = context.pages();
895
+ page = pages[0] ?? (await context.newPage());
896
+ }
897
+ this.browserUseSessionId = session.id;
898
+ this.browserUseApiKey = browserUseApiKey;
899
+ this.browser = browser;
900
+ context.setDefaultTimeout(60000);
901
+ this.contexts.push(context);
902
+ this.pages.push(page);
903
+ this.activePageIndex = 0;
904
+ this.setupPageTracking(page);
905
+ this.setupContextTracking(context);
906
+ }
907
+ catch (error) {
908
+ await this.closeBrowserUseSession(session.id, browserUseApiKey).catch((sessionError) => {
909
+ console.error('Failed to close Browser Use session during cleanup:', sessionError);
910
+ });
911
+ throw error;
912
+ }
913
+ }
914
+ /**
915
+ * Launch the browser with the specified options
916
+ * If already launched, this is a no-op (browser stays open)
917
+ */
918
+ async launch(options) {
919
+ // Determine CDP endpoint: prefer cdpUrl over cdpPort for flexibility
920
+ const cdpEndpoint = options.cdpUrl ?? (options.cdpPort ? String(options.cdpPort) : undefined);
921
+ const hasExtensions = !!options.extensions?.length;
922
+ const hasProfile = !!options.profile;
923
+ const hasStorageState = !!options.storageState;
924
+ if (hasExtensions && cdpEndpoint) {
925
+ throw new Error('Extensions cannot be used with CDP connection');
926
+ }
927
+ if (hasProfile && cdpEndpoint) {
928
+ throw new Error('Profile cannot be used with CDP connection');
929
+ }
930
+ if (hasStorageState && hasProfile) {
931
+ throw new Error('Storage state cannot be used with profile (profile is already persistent storage)');
932
+ }
933
+ if (hasStorageState && hasExtensions) {
934
+ throw new Error('Storage state cannot be used with extensions (extensions require persistent context)');
935
+ }
936
+ // Clean up stale browser state if exists but not connected
937
+ // This handles the case where user manually closed the headed browser
938
+ if (this.browser && !this.browser.isConnected()) {
939
+ await this.close();
940
+ }
941
+ if (this.isLaunched()) {
942
+ // Check if we need to reconnect to a different CDP endpoint
943
+ const needsRelaunch = (!cdpEndpoint && this.cdpEndpoint !== null) ||
944
+ (!!cdpEndpoint && this.needsCdpReconnect(cdpEndpoint));
945
+ if (needsRelaunch) {
946
+ await this.close();
947
+ }
948
+ else {
949
+ return;
950
+ }
951
+ }
952
+ if (cdpEndpoint) {
953
+ await this.connectViaCDP(cdpEndpoint);
954
+ return;
955
+ }
956
+ // Cloud browser providers require explicit opt-in via -p flag or AGENT_BROWSER_PROVIDER env var
957
+ // -p flag takes precedence over env var
958
+ const provider = options.provider ?? process.env.AGENT_BROWSER_PROVIDER;
959
+ if (provider === 'browserbase') {
960
+ await this.connectToBrowserbase();
961
+ return;
962
+ }
963
+ if (provider === 'browseruse') {
964
+ await this.connectToBrowserUse();
965
+ return;
966
+ }
967
+ // Kernel: requires explicit opt-in via -p kernel flag or AGENT_BROWSER_PROVIDER=kernel
968
+ if (provider === 'kernel') {
969
+ await this.connectToKernel();
970
+ return;
971
+ }
972
+ const browserType = options.browser ?? 'chromium';
973
+ if (hasExtensions && browserType !== 'chromium') {
974
+ throw new Error('Extensions are only supported in Chromium');
975
+ }
976
+ // allowFileAccess is only supported in Chromium
977
+ if (options.allowFileAccess && browserType !== 'chromium') {
978
+ throw new Error('allowFileAccess is only supported in Chromium');
979
+ }
980
+ const launcher = browserType === 'firefox' ? firefox : browserType === 'webkit' ? webkit : chromium;
981
+ const viewport = options.viewport ?? { width: 1280, height: 720 };
982
+ // Build base args array with file access flags if enabled
983
+ // --allow-file-access-from-files: allows file:// URLs to read other file:// URLs via XHR/fetch
984
+ // --allow-file-access: allows the browser to access local files in general
985
+ const fileAccessArgs = options.allowFileAccess
986
+ ? ['--allow-file-access-from-files', '--allow-file-access']
987
+ : [];
988
+ // Add anti-detection args
989
+ const antiDetectionArgs = [
990
+ '--disable-blink-features=AutomationControlled',
991
+ '--disable-dev-shm-usage',
992
+ '--no-sandbox',
993
+ '--disable-gpu',
994
+ '--disable-software-rasterizer',
995
+ '--enable-features=WebGL',
996
+ '--ignore-gpu-blacklist',
997
+ '--use-gl=desktop',
998
+ '--enable-gpu-compositing',
999
+ ];
1000
+ const baseArgs = options.args
1001
+ ? [...fileAccessArgs, ...antiDetectionArgs, ...options.args]
1002
+ : [...fileAccessArgs, ...antiDetectionArgs];
1003
+ let context;
1004
+ if (hasExtensions) {
1005
+ // Extensions require persistent context in a temp directory
1006
+ const extPaths = options.extensions.join(',');
1007
+ const session = process.env.AGENT_BROWSER_SESSION || 'default';
1008
+ // Combine extension args with custom args and file access args
1009
+ const extArgs = [`--disable-extensions-except=${extPaths}`, `--load-extension=${extPaths}`];
1010
+ const allArgs = baseArgs ? [...extArgs, ...baseArgs] : extArgs;
1011
+ context = await launcher.launchPersistentContext(path.join(os.tmpdir(), `agent-browser-ext-${session}`), {
1012
+ headless: false,
1013
+ executablePath: options.executablePath,
1014
+ args: allArgs,
1015
+ viewport,
1016
+ extraHTTPHeaders: options.headers,
1017
+ userAgent: options.userAgent,
1018
+ ...(options.proxy && { proxy: options.proxy }),
1019
+ ignoreHTTPSErrors: options.ignoreHTTPSErrors ?? false,
1020
+ });
1021
+ this.isPersistentContext = true;
1022
+ }
1023
+ else if (hasProfile) {
1024
+ // Profile uses persistent context for durable cookies/storage
1025
+ // Expand ~ to home directory since it won't be shell-expanded
1026
+ const profilePath = options.profile.replace(/^~\//, os.homedir() + '/');
1027
+ context = await launcher.launchPersistentContext(profilePath, {
1028
+ headless: options.headless ?? true,
1029
+ executablePath: options.executablePath,
1030
+ args: baseArgs,
1031
+ viewport,
1032
+ extraHTTPHeaders: options.headers,
1033
+ userAgent: options.userAgent,
1034
+ ...(options.proxy && { proxy: options.proxy }),
1035
+ ignoreHTTPSErrors: options.ignoreHTTPSErrors ?? false,
1036
+ });
1037
+ this.isPersistentContext = true;
1038
+ }
1039
+ else {
1040
+ // Regular ephemeral browser
1041
+ this.browser = await launcher.launch({
1042
+ headless: options.headless ?? true,
1043
+ executablePath: options.executablePath,
1044
+ args: baseArgs,
1045
+ });
1046
+ this.cdpEndpoint = null;
1047
+ context = await this.browser.newContext({
1048
+ viewport,
1049
+ extraHTTPHeaders: options.headers,
1050
+ userAgent: options.userAgent,
1051
+ ...(options.proxy && { proxy: options.proxy }),
1052
+ ignoreHTTPSErrors: options.ignoreHTTPSErrors ?? false,
1053
+ ...(options.storageState && { storageState: options.storageState }),
1054
+ });
1055
+ }
1056
+ // Add anti-bot detection evasion script
1057
+ await context.addInitScript(() => {
1058
+ // 1. Simulate window.chrome object
1059
+ if (!window.chrome) {
1060
+ window.chrome = {
1061
+ runtime: {},
1062
+ loadTimes: function () { },
1063
+ csi: function () { },
1064
+ app: {},
1065
+ };
1066
+ }
1067
+ // 2. Simulate navigator.plugins
1068
+ Object.defineProperty(navigator, 'plugins', {
1069
+ get: () => [
1070
+ {
1071
+ name: 'Chrome PDF Plugin',
1072
+ filename: 'internal-pdf-viewer',
1073
+ description: 'Portable Document Format',
1074
+ },
1075
+ {
1076
+ name: 'Chrome PDF Viewer',
1077
+ filename: 'mhjfbmdgcfjbbpaeojofohoefgiehjai',
1078
+ description: '',
1079
+ },
1080
+ {
1081
+ name: 'Native Client',
1082
+ filename: 'internal-nacl-plugin',
1083
+ description: '',
1084
+ },
1085
+ ],
1086
+ });
1087
+ // 3. Simulate navigator.mimeTypes
1088
+ Object.defineProperty(navigator, 'mimeTypes', {
1089
+ get: () => [
1090
+ {
1091
+ type: 'application/pdf',
1092
+ suffixes: 'pdf',
1093
+ description: 'Portable Document Format',
1094
+ },
1095
+ {
1096
+ type: 'application/x-google-chrome-pdf',
1097
+ suffixes: 'pdf',
1098
+ description: 'Portable Document Format',
1099
+ },
1100
+ ],
1101
+ });
1102
+ });
1103
+ context.setDefaultTimeout(60000);
1104
+ this.contexts.push(context);
1105
+ this.setupContextTracking(context);
1106
+ // Set up context tracking to catch window.open() popups
1107
+ this.setupContextTracking(context);
1108
+ const page = context.pages()[0] ?? (await context.newPage());
1109
+ // Only add if not already tracked (setupContextTracking may have already added it via 'page' event)
1110
+ if (!this.pages.includes(page)) {
1111
+ this.pages.push(page);
1112
+ this.setupPageTracking(page);
1113
+ }
1114
+ this.activePageIndex = this.pages.length > 0 ? this.pages.length - 1 : 0;
1115
+ }
1116
+ /**
1117
+ * Connect to a running browser via CDP (Chrome DevTools Protocol)
1118
+ * @param cdpEndpoint Either a port number (as string) or a full WebSocket URL (ws:// or wss://)
1119
+ */
1120
+ async connectViaCDP(cdpEndpoint) {
1121
+ if (!cdpEndpoint) {
1122
+ throw new Error('CDP endpoint is required for CDP connection');
1123
+ }
1124
+ // Determine the connection URL:
1125
+ // - If it starts with ws://, wss://, http://, or https://, use it directly
1126
+ // - If it's a numeric string (e.g., "9222"), treat as port for localhost
1127
+ // - Otherwise, treat it as a port number for localhost
1128
+ let cdpUrl;
1129
+ if (cdpEndpoint.startsWith('ws://') ||
1130
+ cdpEndpoint.startsWith('wss://') ||
1131
+ cdpEndpoint.startsWith('http://') ||
1132
+ cdpEndpoint.startsWith('https://')) {
1133
+ cdpUrl = cdpEndpoint;
1134
+ }
1135
+ else if (/^\d+$/.test(cdpEndpoint)) {
1136
+ // Numeric string - treat as port number (handles JSON serialization quirks)
1137
+ cdpUrl = `http://localhost:${cdpEndpoint}`;
1138
+ }
1139
+ else {
1140
+ // Unknown format - still try as port for backward compatibility
1141
+ cdpUrl = `http://localhost:${cdpEndpoint}`;
1142
+ }
1143
+ const browser = await chromium.connectOverCDP(cdpUrl).catch(() => {
1144
+ throw new Error(`Failed to connect via CDP to ${cdpUrl}. ` +
1145
+ (cdpUrl.includes('localhost')
1146
+ ? `Make sure the app is running with --remote-debugging-port=${cdpEndpoint}`
1147
+ : 'Make sure the remote browser is accessible and the URL is correct.'));
1148
+ });
1149
+ // Validate and set up state, cleaning up browser connection if anything fails
1150
+ try {
1151
+ const contexts = browser.contexts();
1152
+ if (contexts.length === 0) {
1153
+ throw new Error('No browser context found. Make sure the app has an open window.');
1154
+ }
1155
+ // Filter out pages with empty URLs, which can cause Playwright to hang
1156
+ let allPages = contexts.flatMap((context) => context.pages()).filter((page) => page.url());
1157
+ // If no pages exist, create one in the first context
1158
+ if (allPages.length === 0) {
1159
+ const newPage = await contexts[0].newPage();
1160
+ allPages = [newPage];
1161
+ }
1162
+ // All validation passed - commit state
1163
+ this.browser = browser;
1164
+ this.cdpEndpoint = cdpEndpoint;
1165
+ for (const context of contexts) {
1166
+ context.setDefaultTimeout(30000);
1167
+ this.contexts.push(context);
1168
+ this.setupContextTracking(context);
1169
+ }
1170
+ for (const page of allPages) {
1171
+ this.pages.push(page);
1172
+ this.setupPageTracking(page);
1173
+ }
1174
+ this.activePageIndex = 0;
1175
+ }
1176
+ catch (error) {
1177
+ // Clean up browser connection if validation or setup failed
1178
+ await browser.close().catch(() => { });
1179
+ throw error;
1180
+ }
1181
+ }
1182
+ /**
1183
+ * Set up console, error, and close tracking for a page
1184
+ */
1185
+ setupPageTracking(page) {
1186
+ page.on('console', (msg) => {
1187
+ this.consoleMessages.push({
1188
+ type: msg.type(),
1189
+ text: msg.text(),
1190
+ timestamp: Date.now(),
1191
+ });
1192
+ });
1193
+ page.on('pageerror', (error) => {
1194
+ this.pageErrors.push({
1195
+ message: error.message,
1196
+ timestamp: Date.now(),
1197
+ });
1198
+ });
1199
+ page.on('load', async () => {
1200
+ // Trigger navigation event callback
1201
+ const callbacks = getEventCallbacks();
1202
+ callbacks.onNavigation?.({
1203
+ url: page.url(),
1204
+ title: await page.title().catch(() => ''),
1205
+ });
1206
+ });
1207
+ page.on('close', () => {
1208
+ const index = this.pages.indexOf(page);
1209
+ if (index !== -1) {
1210
+ const url = page.url();
1211
+ this.pages.splice(index, 1);
1212
+ if (this.activePageIndex >= this.pages.length) {
1213
+ this.activePageIndex = Math.max(0, this.pages.length - 1);
1214
+ }
1215
+ // Trigger tab closed event callback
1216
+ const callbacks = getEventCallbacks();
1217
+ callbacks.onTabClosed?.({
1218
+ index,
1219
+ remainingTabs: this.pages.length,
1220
+ });
1221
+ }
1222
+ });
1223
+ }
1224
+ /**
1225
+ * Set up tracking for new pages in a context (for CDP connections and popups/new tabs)
1226
+ * This handles pages created externally (e.g., via target="_blank" links, window.open)
1227
+ */
1228
+ async setupContextTracking(context) {
1229
+ context.on('page', async (page) => {
1230
+ // Only add if not already tracked (avoids duplicates when newTab() creates pages)
1231
+ if (!this.pages.includes(page)) {
1232
+ this.pages.push(page);
1233
+ this.setupPageTracking(page);
1234
+ }
1235
+ const callbacks = getEventCallbacks();
1236
+ if (callbacks.onTabCreated) {
1237
+ const index = this.pages.length - 1;
1238
+ callbacks.onTabCreated({
1239
+ index,
1240
+ url: page.url(),
1241
+ title: await page.title().catch(() => ''),
1242
+ });
1243
+ }
1244
+ // Auto-switch to the newly opened tab so subsequent commands target it.
1245
+ // For tabs created via newTab()/newWindow(), this is redundant (they set activePageIndex after),
1246
+ // but for externally opened tabs (window.open, target="_blank"), this ensures the active tab
1247
+ // stays in sync with the browser.
1248
+ const newIndex = this.pages.indexOf(page);
1249
+ if (newIndex !== -1 && newIndex !== this.activePageIndex) {
1250
+ this.activePageIndex = newIndex;
1251
+ // Invalidate CDP session since the active page changed
1252
+ this.invalidateCDPSession().catch(() => { });
1253
+ }
1254
+ });
1255
+ }
1256
+ /**
1257
+ * Create a new tab in the current context
1258
+ */
1259
+ async newTab() {
1260
+ if (!this.browser || this.contexts.length === 0) {
1261
+ throw new Error('Browser not launched');
1262
+ }
1263
+ // Invalidate CDP session since we're switching to a new page
1264
+ await this.invalidateCDPSession();
1265
+ const context = this.contexts[0]; // Use first context for tabs
1266
+ const page = await context.newPage();
1267
+ // Only add if not already tracked (setupContextTracking may have already added it via 'page' event)
1268
+ if (!this.pages.includes(page)) {
1269
+ this.pages.push(page);
1270
+ this.setupPageTracking(page);
1271
+ }
1272
+ this.activePageIndex = this.pages.length - 1;
1273
+ // Set up tracking for the new page
1274
+ this.setupPageTracking(page);
1275
+ // Trigger tab created event callback
1276
+ const callbacks = getEventCallbacks();
1277
+ if (callbacks.onTabCreated) {
1278
+ const index = this.pages.length - 1;
1279
+ callbacks.onTabCreated({
1280
+ index,
1281
+ url: page.url(),
1282
+ title: await page.title().catch(() => ''),
1283
+ });
1284
+ }
1285
+ return { index: this.activePageIndex, total: this.pages.length };
1286
+ }
1287
+ /**
1288
+ * Create a new window (new context)
1289
+ */
1290
+ async newWindow(viewport) {
1291
+ if (!this.browser) {
1292
+ throw new Error('Browser not launched');
1293
+ }
1294
+ const context = await this.browser.newContext({
1295
+ viewport: viewport ?? { width: 1280, height: 720 },
1296
+ });
1297
+ context.setDefaultTimeout(60000);
1298
+ this.contexts.push(context);
1299
+ this.setupContextTracking(context);
1300
+ const page = await context.newPage();
1301
+ // Only add if not already tracked (setupContextTracking may have already added it via 'page' event)
1302
+ if (!this.pages.includes(page)) {
1303
+ this.pages.push(page);
1304
+ this.setupPageTracking(page);
1305
+ }
1306
+ this.activePageIndex = this.pages.length - 1;
1307
+ // Set up tracking for the new page
1308
+ this.setupPageTracking(page);
1309
+ // Trigger tab created event callback
1310
+ const callbacks = getEventCallbacks();
1311
+ if (callbacks.onTabCreated) {
1312
+ const index = this.pages.length - 1;
1313
+ callbacks.onTabCreated({
1314
+ index,
1315
+ url: page.url(),
1316
+ title: await page.title().catch(() => ''),
1317
+ });
1318
+ }
1319
+ return { index: this.activePageIndex, total: this.pages.length };
1320
+ }
1321
+ /**
1322
+ * Invalidate the current CDP session (must be called before switching pages)
1323
+ * This ensures screencast and input injection work correctly after tab switch
1324
+ */
1325
+ async invalidateCDPSession() {
1326
+ const shouldRestart = this.screencastShouldBeActive;
1327
+ const savedCallback = this.frameCallback;
1328
+ const savedOptions = this.lastScreencastOptions;
1329
+ if (this.screencastActive) {
1330
+ await this.stopScreencastInternal();
1331
+ }
1332
+ if (this.cdpSession) {
1333
+ await this.cdpSession.detach().catch(() => { });
1334
+ this.cdpSession = null;
1335
+ }
1336
+ if (shouldRestart && savedCallback) {
1337
+ try {
1338
+ await this.startScreencast(savedCallback, savedOptions ?? undefined);
1339
+ }
1340
+ catch {
1341
+ // Ignore errors when restarting screencast on new page
1342
+ }
1343
+ }
1344
+ }
1345
+ /**
1346
+ * Switch to a specific tab/page by index
1347
+ */
1348
+ async switchTo(index) {
1349
+ if (index < 0 || index >= this.pages.length) {
1350
+ throw new Error(`Invalid tab index: ${index}. Available: 0-${this.pages.length - 1}`);
1351
+ }
1352
+ // Invalidate CDP session before switching (it's page-specific)
1353
+ if (index !== this.activePageIndex) {
1354
+ await this.invalidateCDPSession();
1355
+ }
1356
+ const previousIndex = this.activePageIndex;
1357
+ this.activePageIndex = index;
1358
+ const page = this.pages[index];
1359
+ // Record tab_switch if recording
1360
+ if (this.recorderSessionId && previousIndex !== index) {
1361
+ this.recorderSteps.push({
1362
+ id: `step-${Date.now()}`,
1363
+ timestamp: Date.now(),
1364
+ action: 'tab_switch',
1365
+ index: index,
1366
+ });
1367
+ }
1368
+ // Trigger tab switched event callback
1369
+ const callbacks = getEventCallbacks();
1370
+ callbacks.onTabSwitched?.({
1371
+ fromIndex: previousIndex,
1372
+ toIndex: index,
1373
+ });
1374
+ return {
1375
+ index: this.activePageIndex,
1376
+ url: page.url(),
1377
+ title: '', // Title requires async, will be fetched separately
1378
+ };
1379
+ }
1380
+ /**
1381
+ * Close a specific tab/page
1382
+ */
1383
+ async closeTab(index) {
1384
+ const targetIndex = index ?? this.activePageIndex;
1385
+ if (targetIndex < 0 || targetIndex >= this.pages.length) {
1386
+ throw new Error(`Invalid tab index: ${targetIndex}`);
1387
+ }
1388
+ if (this.pages.length === 1) {
1389
+ throw new Error('Cannot close the last tab. Use "close" to close the browser.');
1390
+ }
1391
+ // Record tab_close if recording
1392
+ if (this.recorderSessionId) {
1393
+ this.recorderSteps.push({
1394
+ id: `step-${Date.now()}`,
1395
+ timestamp: Date.now(),
1396
+ action: 'tab_close',
1397
+ index: targetIndex,
1398
+ });
1399
+ }
1400
+ // If closing the active tab, invalidate CDP session first
1401
+ if (targetIndex === this.activePageIndex) {
1402
+ await this.invalidateCDPSession();
1403
+ }
1404
+ const page = this.pages[targetIndex];
1405
+ await page.close();
1406
+ this.pages.splice(targetIndex, 1);
1407
+ // Adjust active index if needed
1408
+ if (this.activePageIndex >= this.pages.length) {
1409
+ this.activePageIndex = this.pages.length - 1;
1410
+ }
1411
+ else if (this.activePageIndex > targetIndex) {
1412
+ this.activePageIndex--;
1413
+ }
1414
+ return { closed: targetIndex, remaining: this.pages.length };
1415
+ }
1416
+ /**
1417
+ * List all tabs with their info
1418
+ */
1419
+ async listTabs() {
1420
+ const tabs = await Promise.all(this.pages.map(async (page, index) => ({
1421
+ index,
1422
+ url: page.url(),
1423
+ title: await page.title().catch(() => ''),
1424
+ active: index === this.activePageIndex,
1425
+ })));
1426
+ return tabs;
1427
+ }
1428
+ /**
1429
+ * Get or create a CDP session for the current page
1430
+ * Only works with Chromium-based browsers
1431
+ */
1432
+ async getCDPSession() {
1433
+ if (this.cdpSession) {
1434
+ return this.cdpSession;
1435
+ }
1436
+ const page = this.getPage();
1437
+ const context = page.context();
1438
+ // Create a new CDP session attached to the page
1439
+ this.cdpSession = await context.newCDPSession(page);
1440
+ return this.cdpSession;
1441
+ }
1442
+ /**
1443
+ * Check if screencast is currently active
1444
+ */
1445
+ isScreencasting() {
1446
+ return this.screencastActive;
1447
+ }
1448
+ /**
1449
+ * Start screencast - streams viewport frames via CDP
1450
+ * @param callback Function called for each frame
1451
+ * @param options Screencast options
1452
+ */
1453
+ async startScreencast(callback, options) {
1454
+ if (this.screencastActive) {
1455
+ throw new Error('Screencast already active');
1456
+ }
1457
+ const cdp = await this.getCDPSession();
1458
+ this.frameCallback = callback;
1459
+ this.screencastActive = true;
1460
+ this.screencastShouldBeActive = true;
1461
+ this.lastScreencastOptions = options ?? null;
1462
+ this.screencastFrameHandler = async (params) => {
1463
+ const frame = {
1464
+ data: params.data,
1465
+ metadata: params.metadata,
1466
+ sessionId: params.sessionId,
1467
+ };
1468
+ await cdp.send('Page.screencastFrameAck', { sessionId: params.sessionId });
1469
+ if (this.frameCallback) {
1470
+ this.frameCallback(frame);
1471
+ }
1472
+ };
1473
+ cdp.on('Page.screencastFrame', this.screencastFrameHandler);
1474
+ await cdp.send('Page.startScreencast', {
1475
+ format: options?.format ?? 'jpeg',
1476
+ quality: options?.quality ?? 80,
1477
+ maxWidth: options?.maxWidth ?? 1280,
1478
+ maxHeight: options?.maxHeight ?? 720,
1479
+ everyNthFrame: options?.everyNthFrame ?? 1,
1480
+ });
1481
+ }
1482
+ /**
1483
+ * Stop screencast (user initiated - will not auto-restart)
1484
+ */
1485
+ async stopScreencast() {
1486
+ this.screencastShouldBeActive = false;
1487
+ await this.stopScreencastInternal();
1488
+ }
1489
+ /**
1490
+ * Internal method to stop screencast without changing the shouldBeActive flag
1491
+ */
1492
+ async stopScreencastInternal() {
1493
+ if (!this.screencastActive) {
1494
+ return;
1495
+ }
1496
+ try {
1497
+ const cdp = await this.getCDPSession();
1498
+ await cdp.send('Page.stopScreencast');
1499
+ if (this.screencastFrameHandler) {
1500
+ cdp.off('Page.screencastFrame', this.screencastFrameHandler);
1501
+ }
1502
+ }
1503
+ catch {
1504
+ // Ignore errors when stopping
1505
+ }
1506
+ this.screencastActive = false;
1507
+ this.frameCallback = null;
1508
+ this.screencastFrameHandler = null;
1509
+ }
1510
+ /**
1511
+ * Inject a mouse event via CDP
1512
+ */
1513
+ async injectMouseEvent(params) {
1514
+ const cdp = await this.getCDPSession();
1515
+ const cdpButton = params.button === 'left'
1516
+ ? 'left'
1517
+ : params.button === 'right'
1518
+ ? 'right'
1519
+ : params.button === 'middle'
1520
+ ? 'middle'
1521
+ : 'none';
1522
+ await cdp.send('Input.dispatchMouseEvent', {
1523
+ type: params.type,
1524
+ x: params.x,
1525
+ y: params.y,
1526
+ button: cdpButton,
1527
+ clickCount: params.clickCount ?? 1,
1528
+ deltaX: params.deltaX ?? 0,
1529
+ deltaY: params.deltaY ?? 0,
1530
+ modifiers: params.modifiers ?? 0,
1531
+ });
1532
+ }
1533
+ /**
1534
+ * Inject a keyboard event via CDP
1535
+ */
1536
+ async injectKeyboardEvent(params) {
1537
+ const cdp = await this.getCDPSession();
1538
+ await cdp.send('Input.dispatchKeyEvent', {
1539
+ type: params.type,
1540
+ key: params.key,
1541
+ code: params.code,
1542
+ text: params.text,
1543
+ modifiers: params.modifiers ?? 0,
1544
+ });
1545
+ }
1546
+ /**
1547
+ * Inject touch event via CDP (for mobile emulation)
1548
+ */
1549
+ async injectTouchEvent(params) {
1550
+ const cdp = await this.getCDPSession();
1551
+ await cdp.send('Input.dispatchTouchEvent', {
1552
+ type: params.type,
1553
+ touchPoints: params.touchPoints.map((tp, i) => ({
1554
+ x: tp.x,
1555
+ y: tp.y,
1556
+ id: tp.id ?? i,
1557
+ })),
1558
+ modifiers: params.modifiers ?? 0,
1559
+ });
1560
+ }
1561
+ /**
1562
+ * Insert text directly via CDP (for IME input, paste, etc.)
1563
+ */
1564
+ async insertText(text) {
1565
+ const cdp = await this.getCDPSession();
1566
+ await cdp.send('Input.insertText', { text });
1567
+ }
1568
+ /**
1569
+ * Check if video recording is currently active
1570
+ */
1571
+ isRecording() {
1572
+ return this.recordingContext !== null;
1573
+ }
1574
+ isRecordingSession() {
1575
+ return this.recorderSessionId !== null;
1576
+ }
1577
+ async injectRecorderIfNeeded() {
1578
+ if (!this.recorderSessionId)
1579
+ return;
1580
+ const page = this.getPage();
1581
+ if (!page)
1582
+ return;
1583
+ try {
1584
+ // 先重置状态标志
1585
+ await page.evaluate(() => {
1586
+ window.xyzActive = true;
1587
+ window.xyzStopped = false;
1588
+ window.xyzInited = false;
1589
+ });
1590
+ const injectScript = this.getRecorderInjectScript(false, this.recorderBindingName || 'xyzTrack', this.recorderSessionId);
1591
+ // 使用 page.evaluate 执行字符串脚本
1592
+ await page.evaluate(injectScript);
1593
+ }
1594
+ catch (e) { }
1595
+ }
1596
+ /**
1597
+ * Whether recording is temporarily paused (e.g., during replay)
1598
+ */
1599
+ recorderPaused = false;
1600
+ /**
1601
+ * Pause recording temporarily
1602
+ */
1603
+ pauseRecording() {
1604
+ this.recorderPaused = true;
1605
+ }
1606
+ /**
1607
+ * Resume recording
1608
+ */
1609
+ resumeRecording() {
1610
+ this.recorderPaused = false;
1611
+ }
1612
+ recordStep(step) {
1613
+ if (this.recorderSessionId && !this.recorderPaused) {
1614
+ this.recorderSteps.push({
1615
+ id: `step-${Date.now()}`,
1616
+ timestamp: Date.now(),
1617
+ action: step.action,
1618
+ index: step.index,
1619
+ key: step.key,
1620
+ code: step.code,
1621
+ ctrlKey: step.ctrlKey,
1622
+ metaKey: step.metaKey,
1623
+ altKey: step.altKey,
1624
+ shiftKey: step.shiftKey,
1625
+ selector: step.selector,
1626
+ value: step.value,
1627
+ });
1628
+ }
1629
+ }
1630
+ /**
1631
+ * Start recording to a video file using Playwright's native video recording.
1632
+ * Creates a fresh browser context with video recording enabled.
1633
+ * Automatically captures current URL and transfers cookies/storage if no URL provided.
1634
+ *
1635
+ * @param outputPath - Path to the output video file (will be .webm)
1636
+ * @param url - Optional URL to navigate to (defaults to current page URL)
1637
+ */
1638
+ async startRecording(outputPath, url) {
1639
+ if (this.recordingContext) {
1640
+ throw new Error("Recording already in progress. Run 'record stop' first, or use 'record restart' to stop and start a new recording.");
1641
+ }
1642
+ if (!this.browser) {
1643
+ throw new Error('Browser not launched. Call launch first.');
1644
+ }
1645
+ // Check if output file already exists
1646
+ if (existsSync(outputPath)) {
1647
+ throw new Error(`Output file already exists: ${outputPath}`);
1648
+ }
1649
+ // Validate output path is .webm (Playwright native format)
1650
+ if (!outputPath.endsWith('.webm')) {
1651
+ throw new Error('Playwright native recording only supports WebM format. Please use a .webm extension.');
1652
+ }
1653
+ // Auto-capture current URL if none provided
1654
+ const currentPage = this.pages.length > 0 ? this.pages[this.activePageIndex] : null;
1655
+ const currentContext = this.contexts.length > 0 ? this.contexts[0] : null;
1656
+ if (!url && currentPage) {
1657
+ const currentUrl = currentPage.url();
1658
+ if (currentUrl && currentUrl !== 'about:blank') {
1659
+ url = currentUrl;
1660
+ }
1661
+ }
1662
+ // Capture state from current context (cookies + storage)
1663
+ let storageState;
1664
+ if (currentContext) {
1665
+ try {
1666
+ storageState = await currentContext.storageState();
1667
+ }
1668
+ catch {
1669
+ // Ignore errors - context might be closed or invalid
1670
+ }
1671
+ }
1672
+ // Create a temp directory for video recording
1673
+ const session = process.env.AGENT_BROWSER_SESSION || 'default';
1674
+ this.recordingTempDir = path.join(os.tmpdir(), `agent-browser-recording-${session}-${Date.now()}`);
1675
+ mkdirSync(this.recordingTempDir, { recursive: true });
1676
+ this.recordingOutputPath = outputPath;
1677
+ // Create a new context with video recording enabled and restored state
1678
+ const viewport = { width: 1280, height: 720 };
1679
+ this.recordingContext = await this.browser.newContext({
1680
+ viewport,
1681
+ recordVideo: {
1682
+ dir: this.recordingTempDir,
1683
+ size: viewport,
1684
+ },
1685
+ storageState,
1686
+ });
1687
+ this.recordingContext.setDefaultTimeout(10000);
1688
+ // Create a page in the recording context
1689
+ this.recordingPage = await this.recordingContext.newPage();
1690
+ // Add the recording context and page to our managed lists
1691
+ this.contexts.push(this.recordingContext);
1692
+ this.pages.push(this.recordingPage);
1693
+ this.activePageIndex = this.pages.length - 1;
1694
+ // Set up page tracking
1695
+ this.setupPageTracking(this.recordingPage);
1696
+ // Invalidate CDP session since we switched pages
1697
+ await this.invalidateCDPSession();
1698
+ // Navigate to URL if provided or captured
1699
+ if (url) {
1700
+ await this.recordingPage.goto(url, { waitUntil: 'load' });
1701
+ }
1702
+ }
1703
+ /**
1704
+ * Stop recording and save the video file
1705
+ * @returns Recording result with path
1706
+ */
1707
+ async stopRecording() {
1708
+ if (!this.recordingContext || !this.recordingPage) {
1709
+ return { path: '', frames: 0, error: 'No recording in progress' };
1710
+ }
1711
+ const outputPath = this.recordingOutputPath;
1712
+ try {
1713
+ // Get the video object before closing the page
1714
+ const video = this.recordingPage.video();
1715
+ // Remove recording page/context from our managed lists before closing
1716
+ const pageIndex = this.pages.indexOf(this.recordingPage);
1717
+ if (pageIndex !== -1) {
1718
+ this.pages.splice(pageIndex, 1);
1719
+ }
1720
+ const contextIndex = this.contexts.indexOf(this.recordingContext);
1721
+ if (contextIndex !== -1) {
1722
+ this.contexts.splice(contextIndex, 1);
1723
+ }
1724
+ // Close the page to finalize the video
1725
+ await this.recordingPage.close();
1726
+ // Save the video to the desired output path
1727
+ if (video) {
1728
+ await video.saveAs(outputPath);
1729
+ }
1730
+ // Clean up temp directory
1731
+ if (this.recordingTempDir) {
1732
+ rmSync(this.recordingTempDir, { recursive: true, force: true });
1733
+ }
1734
+ // Close the recording context
1735
+ await this.recordingContext.close();
1736
+ // Reset recording state
1737
+ this.recordingContext = null;
1738
+ this.recordingPage = null;
1739
+ this.recordingOutputPath = '';
1740
+ this.recordingTempDir = '';
1741
+ // Adjust active page index
1742
+ if (this.pages.length > 0) {
1743
+ this.activePageIndex = Math.min(this.activePageIndex, this.pages.length - 1);
1744
+ }
1745
+ else {
1746
+ this.activePageIndex = 0;
1747
+ }
1748
+ // Invalidate CDP session since we may have switched pages
1749
+ await this.invalidateCDPSession();
1750
+ return { path: outputPath, frames: 0 }; // Playwright doesn't expose frame count
1751
+ }
1752
+ catch (error) {
1753
+ // Clean up temp directory on error
1754
+ if (this.recordingTempDir) {
1755
+ rmSync(this.recordingTempDir, { recursive: true, force: true });
1756
+ }
1757
+ // Reset state on error
1758
+ this.recordingContext = null;
1759
+ this.recordingPage = null;
1760
+ this.recordingOutputPath = '';
1761
+ this.recordingTempDir = '';
1762
+ const message = error instanceof Error ? error.message : String(error);
1763
+ return { path: outputPath, frames: 0, error: message };
1764
+ }
1765
+ }
1766
+ /**
1767
+ * Restart recording - stops current recording (if any) and starts a new one.
1768
+ * Convenience method that combines stopRecording and startRecording.
1769
+ *
1770
+ * @param outputPath - Path to the output video file (must be .webm)
1771
+ * @param url - Optional URL to navigate to (defaults to current page URL)
1772
+ * @returns Result from stopping the previous recording (if any)
1773
+ */
1774
+ async restartRecording(outputPath, url) {
1775
+ let previousPath;
1776
+ let stopped = false;
1777
+ // Stop current recording if active
1778
+ if (this.recordingContext) {
1779
+ const result = await this.stopRecording();
1780
+ previousPath = result.path;
1781
+ stopped = true;
1782
+ }
1783
+ // Start new recording
1784
+ await this.startRecording(outputPath, url);
1785
+ return { previousPath, stopped };
1786
+ }
1787
+ // ========== User Interaction Recorder ==========
1788
+ getPageIndex(page) {
1789
+ return this.pages.indexOf(page);
1790
+ }
1791
+ getRecorderInjectScript(hide = false, bindingName = 'xyzTrack', sessionId) {
1792
+ const injectScriptPath = path.join(__dirname, 'recorder', 'inject.js');
1793
+ let script = readFileSync(injectScriptPath, 'utf-8');
1794
+ // 在脚本开头注入配置(使用 xyz 前缀)
1795
+ // 注意:xyzInjectedSessionId 必须在脚本开头设置,以便 inject.js 可以读取它
1796
+ // 使用 window.xyzInjectedSessionId = 'xxx' 的形式,让 inject.js 可以读取
1797
+ const config = `window.xyzHide = ${hide}; window.xyzBindingName = '${bindingName}'; window.xyzInjectedSessionId = '${sessionId || ''}';`;
1798
+ const fullScript = config + '\n' + script;
1799
+ return fullScript;
1800
+ }
1801
+ async startRecorder(url, hide = false) {
1802
+ console.log('[BrowserManager] startRecorder called, url:', url, 'hide:', hide);
1803
+ // 检查是否已经在录制中
1804
+ if (this.recorderSessionId) {
1805
+ throw new Error(`Recording already in progress (session: ${this.recorderSessionId}). Use 'recorder stop' to stop current recording first.`);
1806
+ }
1807
+ const page = this.getPage();
1808
+ if (!page) {
1809
+ throw new Error('No page available. Launch browser first.');
1810
+ }
1811
+ this.recorderSessionId = 'recorder-' + Date.now();
1812
+ this.recorderStartTime = Date.now();
1813
+ this.recorderSteps = [];
1814
+ this.recorderPages = [];
1815
+ this.navigationHistory = [];
1816
+ this.navigationHistoryIndex = -1;
1817
+ this.lastNavigationUrl = '';
1818
+ this.lastNavigationTime = 0;
1819
+ const context = page.context();
1820
+ // 使用 Playwright 的 exposeBinding,自动处理所有导航和新标签页
1821
+ // 使用唯一的绑定名称,避免绑定冲突问题
1822
+ const bindingName = `xyzTrack_${this.recorderSessionId}`;
1823
+ this.recorderBindingName = bindingName;
1824
+ // 传递 hide 参数和绑定名称给注入脚本
1825
+ // 同时传递会话 ID 用于验证录制会话是否仍然活跃
1826
+ const injectScript = this.getRecorderInjectScript(hide, bindingName, this.recorderSessionId);
1827
+ // For CDP connections, we need to ensure the debugger is attached to the page
1828
+ // before calling exposeBinding. Creating a CDP session will attach the debugger.
1829
+ if (this.cdpEndpoint !== null) {
1830
+ await this.getCDPSession();
1831
+ }
1832
+ try {
1833
+ await context.exposeBinding(bindingName, async (source, payload) => {
1834
+ // 如果录制会话已停止,返回 false 表示无效
1835
+ if (!this.recorderSessionId) {
1836
+ return false;
1837
+ }
1838
+ if (!payload)
1839
+ return true;
1840
+ const targetPage = source.page;
1841
+ try {
1842
+ const step = JSON.parse(payload);
1843
+ if (step && step.action) {
1844
+ if (step.action === 'xyzPoll') {
1845
+ await targetPage
1846
+ ?.evaluate((steps) => {
1847
+ window.xyzQueue = steps;
1848
+ window.dispatchEvent(new CustomEvent('xyzEvt', { detail: steps }));
1849
+ }, this.recorderSteps)
1850
+ .catch(() => { });
1851
+ }
1852
+ else if (step.action === 'xyzClear') {
1853
+ this.recorderSteps = [];
1854
+ }
1855
+ else if (step.action === 'xyzUpdate') {
1856
+ // Handle update operations (e.g., adding annotations)
1857
+ if (step.id && step.data) {
1858
+ const updateIndex = this.recorderSteps.findIndex((s) => s.id === step.id);
1859
+ if (updateIndex >= 0) {
1860
+ // Merge the update data into the existing step
1861
+ this.recorderSteps[updateIndex] = {
1862
+ ...this.recorderSteps[updateIndex],
1863
+ ...step.data,
1864
+ };
1865
+ // Sync the updated steps back to the frontend
1866
+ await targetPage
1867
+ ?.evaluate((steps) => {
1868
+ window.xyzQueue = steps;
1869
+ window.dispatchEvent(new CustomEvent('xyzEvt', { detail: steps }));
1870
+ }, this.recorderSteps)
1871
+ .catch(() => { });
1872
+ }
1873
+ }
1874
+ }
1875
+ else {
1876
+ // Regular step addition
1877
+ this.recorderSteps.push(step);
1878
+ await targetPage
1879
+ ?.evaluate((steps) => {
1880
+ window.xyzQueue = steps;
1881
+ window.dispatchEvent(new CustomEvent('xyzEvt', { detail: steps }));
1882
+ }, this.recorderSteps)
1883
+ .catch(() => { });
1884
+ }
1885
+ }
1886
+ }
1887
+ catch (e) { }
1888
+ return true;
1889
+ });
1890
+ }
1891
+ catch (e) {
1892
+ // Binding 已存在,忽略错误继续使用
1893
+ }
1894
+ // 在当前页面设置录制会话激活标志
1895
+ // 使用 xyz 前缀
1896
+ try {
1897
+ await page.evaluate((sessionId) => {
1898
+ window.xyzActive = true;
1899
+ // 清除停止标志(允许重新开始录制)
1900
+ window.xyzStopped = false;
1901
+ // 清除已初始化标志(允许重新注入脚本)
1902
+ window.xyzInited = false;
1903
+ // 设置当前会话 ID
1904
+ window.xyzSessionId = sessionId;
1905
+ }, this.recorderSessionId);
1906
+ }
1907
+ catch (e) { }
1908
+ // 设置录制会话激活标志(用于新页面)
1909
+ // 注意:addInitScript 执行顺序是后添加的先执行
1910
+ // 所以我们先添加 injectScript,再添加状态设置脚本
1911
+ // 这样状态设置脚本会先执行
1912
+ // 注入录制器脚本到所有新页面
1913
+ // 注意:这个会第二个执行(后添加的先执行)
1914
+ await context.addInitScript(injectScript);
1915
+ // 设置录制会话激活标志(用于新页面)
1916
+ // 这个会第一个执行(后添加的先执行)
1917
+ // 注意:必须设置 xyzSessionId,否则 inject.js 会跳过初始化
1918
+ // 使用时间戳来确保只有最新的会话 ID 被设置
1919
+ const sessionIdTimestamp = parseInt(this.recorderSessionId.replace('recorder-', '')) || Date.now();
1920
+ await context.addInitScript({
1921
+ content: `
1922
+ // 只有当新的会话 ID 更新时才设置
1923
+ const currentTimestamp = parseInt((window.xyzSessionId || '').replace('recorder-', '')) || 0;
1924
+ const newTimestamp = ${sessionIdTimestamp};
1925
+ if (newTimestamp > currentTimestamp) {
1926
+ window.xyzActive = true;
1927
+ window.xyzStopped = false;
1928
+ window.xyzInited = false;
1929
+ window.xyzSessionId = '${this.recorderSessionId}';
1930
+ }
1931
+ `,
1932
+ });
1933
+ // 在当前页面设置状态,再注入脚本
1934
+ try {
1935
+ await page.evaluate(`
1936
+ // 只有当新的会话 ID 更新时才设置
1937
+ const currentTimestamp = parseInt((window.xyzSessionId || '').replace('recorder-', '')) || 0;
1938
+ const newTimestamp = ${sessionIdTimestamp};
1939
+ if (newTimestamp > currentTimestamp) {
1940
+ window.xyzActive = true;
1941
+ window.xyzStopped = false;
1942
+ window.xyzInited = false;
1943
+ window.xyzSessionId = '${this.recorderSessionId}';
1944
+ // 清空旧的录制队列,避免状态干扰
1945
+ window.xyzQueue = [];
1946
+ }
1947
+ `);
1948
+ }
1949
+ catch (e) { }
1950
+ // 在当前页面注入录制器脚本
1951
+ // 注意:这里需要手动注入,因为 addInitScript 只对新页面生效
1952
+ try {
1953
+ await page.addScriptTag({ content: injectScript, type: 'text/javascript' });
1954
+ }
1955
+ catch (e) {
1956
+ try {
1957
+ await page.evaluate((scriptContent) => {
1958
+ const script = document.createElement('script');
1959
+ script.textContent = scriptContent;
1960
+ script.type = 'text/javascript';
1961
+ (document.head || document.documentElement).appendChild(script);
1962
+ }, injectScript);
1963
+ }
1964
+ catch (e2) { }
1965
+ }
1966
+ // 处理导航事件(用于记录 back/forward)
1967
+ this.recorderNavigatedHandler = async (frame) => {
1968
+ if (!this.recorderSessionId)
1969
+ return;
1970
+ if (frame !== page.mainFrame())
1971
+ return;
1972
+ const currentUrl = frame.url();
1973
+ const now = Date.now();
1974
+ if (currentUrl === this.lastNavigationUrl)
1975
+ return;
1976
+ const timeSinceLastNav = now - this.lastNavigationTime;
1977
+ if (timeSinceLastNav < 300 && currentUrl === this.lastNavigationUrl) {
1978
+ this.recorderSteps.push({
1979
+ id: `step-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
1980
+ timestamp: now,
1981
+ action: 'reload',
1982
+ });
1983
+ return;
1984
+ }
1985
+ const existingIndex = this.navigationHistory.indexOf(currentUrl);
1986
+ if (existingIndex !== -1 && existingIndex < this.navigationHistoryIndex) {
1987
+ this.recorderSteps.push({
1988
+ id: `step-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
1989
+ timestamp: now,
1990
+ action: 'back',
1991
+ from: this.navigationHistory[this.navigationHistoryIndex],
1992
+ to: currentUrl,
1993
+ });
1994
+ this.navigationHistoryIndex = existingIndex;
1995
+ }
1996
+ else if (existingIndex !== -1 && existingIndex > this.navigationHistoryIndex) {
1997
+ this.recorderSteps.push({
1998
+ id: `step-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
1999
+ timestamp: now,
2000
+ action: 'forward',
2001
+ from: this.navigationHistory[this.navigationHistoryIndex],
2002
+ to: currentUrl,
2003
+ });
2004
+ this.navigationHistoryIndex = existingIndex;
2005
+ }
2006
+ else {
2007
+ if (this.navigationHistoryIndex >= 0 &&
2008
+ this.navigationHistoryIndex < this.navigationHistory.length - 1) {
2009
+ this.navigationHistory = this.navigationHistory.slice(0, this.navigationHistoryIndex + 1);
2010
+ }
2011
+ this.navigationHistory.push(currentUrl);
2012
+ this.navigationHistoryIndex = this.navigationHistory.length - 1;
2013
+ }
2014
+ this.lastNavigationUrl = currentUrl;
2015
+ this.lastNavigationTime = now;
2016
+ };
2017
+ page.on('framenavigated', this.recorderNavigatedHandler);
2018
+ // 处理 iframe 附加和导航事件 - 向 iframe 注入录制器脚本
2019
+ const injectScriptToFrame = async (frame) => {
2020
+ if (!this.recorderSessionId)
2021
+ return;
2022
+ // 跳过主框架
2023
+ if (frame === page.mainFrame())
2024
+ return;
2025
+ try {
2026
+ // 检查是否已经注入过
2027
+ const alreadyInjected = await frame
2028
+ .evaluate(() => {
2029
+ return !!window.xyzInjectedSessionId;
2030
+ })
2031
+ .catch(() => false);
2032
+ if (alreadyInjected)
2033
+ return;
2034
+ // 向 iframe 注入录制器脚本
2035
+ const injectScript = this.getRecorderInjectScript(false, this.recorderBindingName || 'xyzTrack', this.recorderSessionId);
2036
+ // 使用 evaluate 在 iframe 上下文中执行脚本
2037
+ await frame.evaluate(injectScript).catch((e) => {
2038
+ // 可能是跨域 iframe,忽略错误
2039
+ });
2040
+ }
2041
+ catch (e) {
2042
+ // 忽略错误,可能是跨域 iframe
2043
+ }
2044
+ };
2045
+ // 向所有现有 iframe 注入脚本
2046
+ const injectToAllFrames = async () => {
2047
+ const frames = page.frames();
2048
+ for (const frame of frames) {
2049
+ await injectScriptToFrame(frame);
2050
+ }
2051
+ };
2052
+ // 立即向现有 iframe 注入
2053
+ await injectToAllFrames();
2054
+ // 监听 frameattached 事件
2055
+ this.recorderFrameAttachedHandler = async (frame) => {
2056
+ // 等待一小段时间让 iframe 初始化
2057
+ await new Promise((resolve) => setTimeout(resolve, 100));
2058
+ await injectScriptToFrame(frame);
2059
+ };
2060
+ page.on('frameattached', this.recorderFrameAttachedHandler);
2061
+ // 处理新标签页
2062
+ this.recorderPageHandler = async (newPage) => {
2063
+ if (this.recorderSessionId) {
2064
+ const previousActiveIndex = this.activePageIndex;
2065
+ const pageIndex = this.getPageIndex(newPage);
2066
+ const newTabIndex = pageIndex >= 0 ? pageIndex : this.pages.length;
2067
+ this.recorderSteps.push({
2068
+ id: this.recorderSteps.length + 1,
2069
+ timestamp: Date.now(),
2070
+ action: 'tab_new',
2071
+ url: newPage.url(),
2072
+ index: newTabIndex,
2073
+ });
2074
+ setTimeout(() => {
2075
+ if (this.recorderSessionId && this.activePageIndex !== previousActiveIndex) {
2076
+ this.recorderSteps.push({
2077
+ id: this.recorderSteps.length + 1,
2078
+ timestamp: Date.now(),
2079
+ action: 'tab_switch',
2080
+ index: this.activePageIndex,
2081
+ });
2082
+ }
2083
+ }, 100);
2084
+ newPage.on('close', () => {
2085
+ if (this.recorderSessionId) {
2086
+ const closeIndex = this.getPageIndex(newPage);
2087
+ this.recorderSteps.push({
2088
+ id: this.recorderSteps.length + 1,
2089
+ timestamp: Date.now(),
2090
+ action: 'tab_close',
2091
+ index: closeIndex >= 0 ? closeIndex : -1,
2092
+ });
2093
+ }
2094
+ });
2095
+ await newPage.waitForLoadState('domcontentloaded').catch(() => { });
2096
+ // 注入录制器脚本到新页面
2097
+ try {
2098
+ const injectScript = this.getRecorderInjectScript(false, 'xyzTrack', this.recorderSessionId);
2099
+ await newPage.evaluate(injectScript);
2100
+ }
2101
+ catch (e) {
2102
+ console.log('[recorderPageHandler] Error injecting script:', e);
2103
+ }
2104
+ await newPage
2105
+ .evaluate((steps) => {
2106
+ window.__recorderSteps = steps;
2107
+ window.dispatchEvent(new CustomEvent('recorder:steps', { detail: steps }));
2108
+ }, this.recorderSteps)
2109
+ .catch(() => { });
2110
+ this.recorderPages.push({
2111
+ url: newPage.url(),
2112
+ title: await newPage.title().catch(() => ''),
2113
+ firstVisitTime: Date.now(),
2114
+ });
2115
+ }
2116
+ };
2117
+ context.on('page', this.recorderPageHandler);
2118
+ if (url) {
2119
+ await page.goto(url, { waitUntil: 'load' });
2120
+ }
2121
+ this.recorderPages.push({
2122
+ url: page.url(),
2123
+ title: await page.title(),
2124
+ firstVisitTime: Date.now(),
2125
+ });
2126
+ return { started: true, sessionId: this.recorderSessionId };
2127
+ }
2128
+ async stopRecorder() {
2129
+ // 检查是否在录制中
2130
+ if (!this.recorderSessionId) {
2131
+ console.log('[stopRecorder] No active recording session');
2132
+ return { yaml: '', steps: 0, wasRecording: false };
2133
+ }
2134
+ const page = this.getPage();
2135
+ if (page) {
2136
+ try {
2137
+ const result = await page.evaluate(() => {
2138
+ const win = window;
2139
+ // 先检查是否有待处理的 fill,在设置 xyzStopped 之前调用
2140
+ const hasPanel = !!document.getElementById('xyzPnl');
2141
+ const hasCloseFunc = typeof win.xyzClose === 'function';
2142
+ const hasFlushFunc = typeof win.xyzFlushPending === 'function';
2143
+ console.log('[stopRecorder] hasFlushFunc:', hasFlushFunc, 'hasCloseFunc:', hasCloseFunc, 'hasPanel:', hasPanel);
2144
+ // 重要:先调用 xyzFlushPending,再设置 xyzStopped
2145
+ // 因为 recordStep 会检查 xyzStopped,如果为 true 就不记录
2146
+ if (hasFlushFunc) {
2147
+ console.log('[stopRecorder] Calling xyzFlushPending');
2148
+ win.xyzFlushPending();
2149
+ }
2150
+ else {
2151
+ console.log('[stopRecorder] xyzFlushPending not found');
2152
+ }
2153
+ // 然后再设置停止标志
2154
+ win.xyzActive = false;
2155
+ win.xyzStopped = true;
2156
+ // 重置初始化标志,允许新的录制会话重新初始化
2157
+ win.xyzInited = false;
2158
+ win.xyzInitializedSessionId = undefined;
2159
+ // 注意:不要清除 xyzSessionId,因为旧的监听器需要用它来检查是否应该跳过
2160
+ // 新的录制会话会设置新的 xyzSessionId,旧的监听器会检测到时间戳更新并跳过
2161
+ // win.xyzSessionId = undefined;
2162
+ if (hasCloseFunc) {
2163
+ win.xyzClose();
2164
+ }
2165
+ return {
2166
+ hadPanel: hasPanel,
2167
+ hadCloseFunc: hasCloseFunc,
2168
+ stillHasPanel: !!document.getElementById('xyzPnl'),
2169
+ };
2170
+ });
2171
+ console.log('[stopRecorder] Result:', result);
2172
+ }
2173
+ catch (e) {
2174
+ console.error('[stopRecorder] Error:', e);
2175
+ }
2176
+ if (this.recorderNavigatedHandler) {
2177
+ page.off('framenavigated', this.recorderNavigatedHandler);
2178
+ this.recorderNavigatedHandler = null;
2179
+ }
2180
+ if (this.recorderFrameAttachedHandler) {
2181
+ page.off('frameattached', this.recorderFrameAttachedHandler);
2182
+ this.recorderFrameAttachedHandler = null;
2183
+ }
2184
+ if (this.recorderPageHandler) {
2185
+ page.context().off('page', this.recorderPageHandler);
2186
+ this.recorderPageHandler = null;
2187
+ }
2188
+ // 移除 xyzTrack binding(覆盖为空函数)
2189
+ try {
2190
+ await page.context().exposeBinding(this.recorderBindingName || 'xyzTrack', () => { });
2191
+ }
2192
+ catch (e) {
2193
+ // 忽略错误,可能 binding 已经被移除或其他问题
2194
+ }
2195
+ }
2196
+ // 等待一下,确保所有步骤都被处理
2197
+ await new Promise((resolve) => setTimeout(resolve, 100));
2198
+ // 在 xyzFlushPending 之后生成 YAML
2199
+ const yaml = this.generateRecorderYaml();
2200
+ const steps = this.recorderSteps.length;
2201
+ this.recorderSessionId = null;
2202
+ this.recorderSteps = [];
2203
+ this.navigationHistory = [];
2204
+ this.navigationHistoryIndex = -1;
2205
+ this.lastNavigationUrl = '';
2206
+ this.lastNavigationTime = 0;
2207
+ return { yaml, steps };
2208
+ }
2209
+ getRecorderStatus() {
2210
+ return {
2211
+ isRecording: this.recorderSessionId !== null,
2212
+ sessionId: this.recorderSessionId || undefined,
2213
+ steps: this.recorderSteps.length,
2214
+ };
2215
+ }
2216
+ generateRecorderYaml() {
2217
+ const lines = [];
2218
+ // 格式化时间为 HH:MM:SS
2219
+ const formatTime = (ts) => {
2220
+ if (!ts)
2221
+ return 'unknown';
2222
+ const d = new Date(ts);
2223
+ return d.toTimeString().split(' ')[0]; // HH:MM:SS
2224
+ };
2225
+ lines.push('session:');
2226
+ lines.push(` id: ${this.recorderSessionId || 'unknown'}`);
2227
+ lines.push(` startTime: ${formatTime(this.recorderStartTime)}`);
2228
+ lines.push(` endTime: ${formatTime(Date.now())}`);
2229
+ lines.push(` steps: ${this.recorderSteps.length}`);
2230
+ lines.push('');
2231
+ if (this.recorderPages.length > 0) {
2232
+ lines.push('pages:');
2233
+ for (const page of this.recorderPages) {
2234
+ lines.push(` - url: ${page.url}`);
2235
+ lines.push(` title: ${page.title || 'N/A'}`);
2236
+ lines.push(` firstVisitTime: ${formatTime(page.firstVisitTime)}`);
2237
+ }
2238
+ lines.push('');
2239
+ }
2240
+ // 需要携带 URL 的操作类型
2241
+ const urlRequiredActions = [
2242
+ 'open',
2243
+ 'goto',
2244
+ 'back',
2245
+ 'forward',
2246
+ 'reload',
2247
+ 'tab_new',
2248
+ 'tab_switch',
2249
+ 'link_click',
2250
+ ];
2251
+ lines.push('steps:');
2252
+ for (const step of this.recorderSteps) {
2253
+ lines.push(` - id: ${step.id}`);
2254
+ lines.push(` time: ${formatTime(step.timestamp)}`);
2255
+ lines.push(` action: ${step.action}`);
2256
+ if (step.selector)
2257
+ lines.push(` selector: "${step.selector}"`);
2258
+ if (step.xpath)
2259
+ lines.push(` xpath: "${step.xpath}"`);
2260
+ if (step.value)
2261
+ lines.push(` value: "${step.value}"`);
2262
+ // 轨迹点 - 同时生成可执行的 CLI 命令
2263
+ if (step.points && Array.isArray(step.points) && step.points.length > 0) {
2264
+ lines.push(` points: ${JSON.stringify(step.points)}`);
2265
+ // 生成可执行的 CLI 命令
2266
+ const trajectoryCmd = this.generateStepCliCommand(step);
2267
+ if (trajectoryCmd) {
2268
+ lines.push(` # Replay: ${trajectoryCmd}`);
2269
+ }
2270
+ }
2271
+ if (step.x !== undefined)
2272
+ lines.push(` x: ${step.x}`);
2273
+ if (step.y !== undefined)
2274
+ lines.push(` y: ${step.y}`);
2275
+ if (step.from && typeof step.from === 'string') {
2276
+ lines.push(` from: "${step.from}"`);
2277
+ }
2278
+ else if (step.from) {
2279
+ lines.push(` from: { width: ${step.from.width}, height: ${step.from.height} }`);
2280
+ }
2281
+ if (step.to && typeof step.to === 'string') {
2282
+ lines.push(` to: "${step.to}"`);
2283
+ }
2284
+ else if (step.to) {
2285
+ lines.push(` to: { width: ${step.to.width}, height: ${step.to.height} }`);
2286
+ }
2287
+ // 备注信息 - 添加重点提示
2288
+ if (step.annotation) {
2289
+ lines.push(` annotation:`);
2290
+ lines.push(` type: ${step.annotation.type}`);
2291
+ lines.push(` label: "${step.annotation.label}"`);
2292
+ // 完整属性生成
2293
+ if (step.annotation.selector) {
2294
+ lines.push(` selector: "${step.annotation.selector}"`);
2295
+ }
2296
+ if (step.annotation.itemSelector) {
2297
+ lines.push(` itemSelector: "${step.annotation.itemSelector}"`);
2298
+ }
2299
+ if (step.annotation.nextSelector) {
2300
+ lines.push(` nextSelector: "${step.annotation.nextSelector}"`);
2301
+ }
2302
+ if (step.annotation.fields && step.annotation.fields.length > 0) {
2303
+ lines.push(` fields: [${step.annotation.fields.map((f) => `"${f}"`).join(', ')}]`);
2304
+ }
2305
+ if (step.annotation.waitTimeout !== undefined) {
2306
+ lines.push(` waitTimeout: ${step.annotation.waitTimeout}`);
2307
+ }
2308
+ if (step.annotation.customNote) {
2309
+ lines.push(` customNote: "${step.annotation.customNote}"`);
2310
+ }
2311
+ lines.push(` # ⚠️ IMPORTANT: This step requires special attention`);
2312
+ lines.push(` # User marked this as: "${step.annotation.label}"`);
2313
+ }
2314
+ // 只在特定操作类型时携带 URL
2315
+ if (step.url && urlRequiredActions.includes(step.action)) {
2316
+ lines.push(` url: "${step.url}"`);
2317
+ }
2318
+ if (step.index !== undefined)
2319
+ lines.push(` index: ${step.index}`);
2320
+ if (step.key)
2321
+ lines.push(` key: "${step.key}"`);
2322
+ if (step.code)
2323
+ lines.push(` code: "${step.code}"`);
2324
+ if (step.ctrlKey)
2325
+ lines.push(` ctrlKey: true`);
2326
+ if (step.metaKey)
2327
+ lines.push(` metaKey: true`);
2328
+ if (step.altKey)
2329
+ lines.push(` altKey: true`);
2330
+ if (step.shiftKey)
2331
+ lines.push(` shiftKey: true`);
2332
+ lines.push('');
2333
+ }
2334
+ // ═══════════════════════════════════════════════════════════
2335
+ // CLI Commands Section - 生成可执行的 CLI 命令
2336
+ // ═══════════════════════════════════════════════════════════
2337
+ lines.push('# ═══════════════════════════════════════════════════════════');
2338
+ lines.push('# CLI Commands (Copy & Execute)');
2339
+ lines.push('# ═══════════════════════════════════════════════════════════');
2340
+ lines.push('');
2341
+ lines.push('# 启用模拟人类鼠标移动(推荐)');
2342
+ lines.push('# Enable human-like mouse movement (recommended)');
2343
+ lines.push('export AGENT_BROWSER_HUMAN=bezier');
2344
+ lines.push('');
2345
+ for (const step of this.recorderSteps) {
2346
+ const cmd = this.generateStepCliCommand(step);
2347
+ if (cmd) {
2348
+ lines.push(`# ${step.id}: ${step.action}`);
2349
+ lines.push(cmd);
2350
+ lines.push('');
2351
+ }
2352
+ }
2353
+ return lines.join('\n');
2354
+ }
2355
+ /**
2356
+ * Generate CLI command for a single recorder step
2357
+ */
2358
+ generateStepCliCommand(step) {
2359
+ const escapeShell = (str) => {
2360
+ return str.replace(/"/g, '\\"').replace(/\$/g, '\\$').replace(/`/g, '\\`');
2361
+ };
2362
+ const formatKeyCombo = (s) => {
2363
+ const parts = [];
2364
+ if (s.ctrlKey)
2365
+ parts.push('Control');
2366
+ if (s.metaKey)
2367
+ parts.push('Meta');
2368
+ if (s.altKey)
2369
+ parts.push('Alt');
2370
+ if (s.shiftKey &&
2371
+ !['Shift', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(s.key)) {
2372
+ parts.push('Shift');
2373
+ }
2374
+ if (s.key)
2375
+ parts.push(s.key);
2376
+ return parts.join('+');
2377
+ };
2378
+ switch (step.action) {
2379
+ case 'click':
2380
+ case 'link_click':
2381
+ if (step.selector) {
2382
+ return `agent-browser click "${escapeShell(step.selector)}"`;
2383
+ }
2384
+ if (step.xpath) {
2385
+ return `agent-browser click "xpath=${escapeShell(step.xpath)}"`;
2386
+ }
2387
+ return null;
2388
+ case 'fill':
2389
+ if (step.value !== undefined) {
2390
+ if (step.selector) {
2391
+ return `agent-browser fill "${escapeShell(step.selector)}" "${escapeShell(String(step.value))}"`;
2392
+ }
2393
+ if (step.xpath) {
2394
+ return `agent-browser fill "xpath=${escapeShell(step.xpath)}" "${escapeShell(String(step.value))}"`;
2395
+ }
2396
+ }
2397
+ return null;
2398
+ case 'select':
2399
+ if (step.value !== undefined) {
2400
+ if (step.selector) {
2401
+ return `agent-browser select "${escapeShell(step.selector)}" "${escapeShell(String(step.value))}"`;
2402
+ }
2403
+ if (step.xpath) {
2404
+ return `agent-browser select "xpath=${escapeShell(step.xpath)}" "${escapeShell(String(step.value))}"`;
2405
+ }
2406
+ }
2407
+ return null;
2408
+ case 'keyboard':
2409
+ const key = formatKeyCombo(step);
2410
+ if (key) {
2411
+ return `agent-browser press "${key}"`;
2412
+ }
2413
+ return null;
2414
+ case 'scroll':
2415
+ if (step.x !== undefined && step.y !== undefined) {
2416
+ return `agent-browser mouse wheel ${step.y} ${step.x}`;
2417
+ }
2418
+ return null;
2419
+ case 'trajectory':
2420
+ if (step.points && Array.isArray(step.points) && step.points.length > 0) {
2421
+ // 简化轨迹点,最多5个
2422
+ const maxPoints = 5;
2423
+ let sampled;
2424
+ if (step.points.length <= maxPoints) {
2425
+ sampled = step.points;
2426
+ }
2427
+ else {
2428
+ // 均匀采样
2429
+ sampled = [];
2430
+ const step_size = (step.points.length - 1) / (maxPoints - 1);
2431
+ for (let i = 0; i < maxPoints; i++) {
2432
+ const idx = Math.round(i * step_size);
2433
+ sampled.push(step.points[idx]);
2434
+ }
2435
+ }
2436
+ // 格式化为 x:y:delay 字符串
2437
+ const segments = sampled.map((p, i) => {
2438
+ const x = Math.round(p.x);
2439
+ const y = Math.round(p.y);
2440
+ const delay = i === 0 ? 0 : Math.round(p.t - sampled[i - 1].t);
2441
+ return `${x}:${y}:${delay}`;
2442
+ });
2443
+ return `AGENT_BROWSER_HUMAN=bezier agent-browser mouse trajectory "${segments.join(';')}"`;
2444
+ }
2445
+ return null;
2446
+ case 'open':
2447
+ case 'goto':
2448
+ if (step.url) {
2449
+ return `agent-browser open "${step.url}"`;
2450
+ }
2451
+ return null;
2452
+ case 'back':
2453
+ return 'agent-browser back';
2454
+ case 'forward':
2455
+ return 'agent-browser forward';
2456
+ case 'reload':
2457
+ return 'agent-browser reload';
2458
+ case 'tab_new':
2459
+ if (step.url) {
2460
+ return `agent-browser tab new "${step.url}"`;
2461
+ }
2462
+ return 'agent-browser tab new';
2463
+ case 'tab_switch':
2464
+ if (step.index !== undefined) {
2465
+ return `agent-browser tab ${step.index}`;
2466
+ }
2467
+ return null;
2468
+ case 'resize':
2469
+ if (step.to && typeof step.to === 'object') {
2470
+ return `agent-browser set viewport ${step.to.width} ${step.to.height}`;
2471
+ }
2472
+ return null;
2473
+ case 'hover':
2474
+ if (step.xpath) {
2475
+ return `agent-browser hover "xpath=${escapeShell(step.xpath)}"`;
2476
+ }
2477
+ if (step.selector) {
2478
+ return `agent-browser hover "${escapeShell(step.selector)}"`;
2479
+ }
2480
+ return null;
2481
+ default:
2482
+ return null;
2483
+ }
2484
+ }
2485
+ /**
2486
+ * Close the browser and clean up
2487
+ */
2488
+ async close() {
2489
+ // Stop recording if active (saves video)
2490
+ if (this.recordingContext) {
2491
+ await this.stopRecording();
2492
+ }
2493
+ // Stop screencast if active
2494
+ if (this.screencastActive) {
2495
+ await this.stopScreencast();
2496
+ }
2497
+ // Remove recorder event listeners
2498
+ const page = this.pages.length > 0 ? this.getPage() : null;
2499
+ if (page) {
2500
+ if (this.recorderNavigatedHandler) {
2501
+ page.off('framenavigated', this.recorderNavigatedHandler);
2502
+ this.recorderNavigatedHandler = null;
2503
+ }
2504
+ if (this.recorderFrameAttachedHandler) {
2505
+ page.off('frameattached', this.recorderFrameAttachedHandler);
2506
+ this.recorderFrameAttachedHandler = null;
2507
+ }
2508
+ if (this.recorderPageHandler) {
2509
+ page.context().off('page', this.recorderPageHandler);
2510
+ this.recorderPageHandler = null;
2511
+ }
2512
+ }
2513
+ // Clean up navigation state
2514
+ this.navigationHistory = [];
2515
+ this.navigationHistoryIndex = -1;
2516
+ this.lastNavigationUrl = '';
2517
+ this.lastNavigationTime = 0;
2518
+ // Clean up CDP session
2519
+ if (this.cdpSession) {
2520
+ await this.cdpSession.detach().catch(() => { });
2521
+ this.cdpSession = null;
2522
+ }
2523
+ // Helper function to close pages
2524
+ const closePages = async () => {
2525
+ for (const page of this.pages) {
2526
+ await page.close().catch(() => { });
2527
+ }
2528
+ };
2529
+ // Helper function to close browser
2530
+ const closeBrowser = async () => {
2531
+ if (this.browser) {
2532
+ await this.browser.close().catch(() => { });
2533
+ this.browser = null;
2534
+ }
2535
+ };
2536
+ if (this.browserbaseSessionId && this.browserbaseApiKey) {
2537
+ await this.closeBrowserbaseSession(this.browserbaseSessionId, this.browserbaseApiKey).catch((error) => {
2538
+ console.error('Failed to close Browserbase session:', error);
2539
+ });
2540
+ this.browser = null;
2541
+ }
2542
+ else if (this.browserUseSessionId && this.browserUseApiKey) {
2543
+ await this.closeBrowserUseSession(this.browserUseSessionId, this.browserUseApiKey).catch((error) => {
2544
+ console.error('Failed to close Browser Use session:', error);
2545
+ });
2546
+ this.browser = null;
2547
+ }
2548
+ else if (this.kernelSessionId && this.kernelApiKey) {
2549
+ await this.closeKernelSession(this.kernelSessionId, this.kernelApiKey).catch((error) => {
2550
+ console.error('Failed to close Kernel session:', error);
2551
+ });
2552
+ this.browser = null;
2553
+ }
2554
+ else if (this.cdpEndpoint !== null) {
2555
+ console.log('[DEBUG close] CDP endpoint detected:', this.cdpEndpoint);
2556
+ console.log('[DEBUG close] browser exists:', !!this.browser);
2557
+ if (this.browser) {
2558
+ try {
2559
+ // CDP 连接:只关闭我们打开的页面,然后断开连接
2560
+ // 注意:browser.close() 对于 CDP 连接只会断开连接,不会关闭远程浏览器
2561
+ console.log('[DEBUG close] CDP connection - closing pages and disconnecting');
2562
+ await closePages();
2563
+ await this.browser.close();
2564
+ console.log('[DEBUG close] CDP connection closed');
2565
+ }
2566
+ catch (e) {
2567
+ console.log('[DEBUG close] CDP disconnect failed:', e);
2568
+ }
2569
+ finally {
2570
+ this.browser = null;
2571
+ }
2572
+ }
2573
+ }
2574
+ else {
2575
+ // Regular browser: close everything
2576
+ await closePages();
2577
+ for (const context of this.contexts) {
2578
+ await context.close().catch(() => { });
2579
+ }
2580
+ await closeBrowser();
2581
+ }
2582
+ // Clean up all references
2583
+ this.pages = [];
2584
+ this.contexts = [];
2585
+ this.cdpEndpoint = null;
2586
+ this.browserbaseSessionId = null;
2587
+ this.browserbaseApiKey = null;
2588
+ this.browserUseSessionId = null;
2589
+ this.browserUseApiKey = null;
2590
+ this.kernelSessionId = null;
2591
+ this.kernelApiKey = null;
2592
+ this.isPersistentContext = false;
2593
+ this.activePageIndex = 0;
2594
+ this.refMap = {};
2595
+ this.lastSnapshot = '';
2596
+ this.frameCallback = null;
2597
+ }
2598
+ }
2599
+ //# sourceMappingURL=browser.js.map