@pyrokine/mcp-chrome 2.4.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/README.md +546 -192
  2. package/README_zh.md +490 -192
  3. package/dist/anti-detection/behavior.js +1 -1
  4. package/dist/anti-detection/behavior.js.map +1 -1
  5. package/dist/anti-detection/injection.d.ts.map +1 -1
  6. package/dist/anti-detection/injection.js +5 -4
  7. package/dist/anti-detection/injection.js.map +1 -1
  8. package/dist/cdp/client.d.ts +2 -2
  9. package/dist/cdp/client.d.ts.map +1 -1
  10. package/dist/cdp/client.js +24 -10
  11. package/dist/cdp/client.js.map +1 -1
  12. package/dist/cdp/launcher.d.ts +2 -3
  13. package/dist/cdp/launcher.d.ts.map +1 -1
  14. package/dist/cdp/launcher.js +84 -24
  15. package/dist/cdp/launcher.js.map +1 -1
  16. package/dist/core/auto-wait.d.ts +3 -3
  17. package/dist/core/auto-wait.d.ts.map +1 -1
  18. package/dist/core/auto-wait.js +45 -20
  19. package/dist/core/auto-wait.js.map +1 -1
  20. package/dist/core/browser-driver.d.ts +104 -14
  21. package/dist/core/browser-driver.d.ts.map +1 -1
  22. package/dist/core/browser-driver.js +1 -0
  23. package/dist/core/browser-driver.js.map +1 -1
  24. package/dist/core/errors.d.ts +25 -0
  25. package/dist/core/errors.d.ts.map +1 -1
  26. package/dist/core/errors.js +93 -1
  27. package/dist/core/errors.js.map +1 -1
  28. package/dist/core/locator.d.ts.map +1 -1
  29. package/dist/core/locator.js +6 -4
  30. package/dist/core/locator.js.map +1 -1
  31. package/dist/core/os-mouse.d.ts +78 -0
  32. package/dist/core/os-mouse.d.ts.map +1 -0
  33. package/dist/core/os-mouse.js +378 -0
  34. package/dist/core/os-mouse.js.map +1 -0
  35. package/dist/core/session.d.ts +46 -21
  36. package/dist/core/session.d.ts.map +1 -1
  37. package/dist/core/session.js +724 -175
  38. package/dist/core/session.js.map +1 -1
  39. package/dist/core/types.d.ts +12 -0
  40. package/dist/core/types.d.ts.map +1 -1
  41. package/dist/core/types.js +2 -0
  42. package/dist/core/types.js.map +1 -1
  43. package/dist/core/unified-session.d.ts +117 -21
  44. package/dist/core/unified-session.d.ts.map +1 -1
  45. package/dist/core/unified-session.js +619 -129
  46. package/dist/core/unified-session.js.map +1 -1
  47. package/dist/core/utils.d.ts +5 -0
  48. package/dist/core/utils.d.ts.map +1 -1
  49. package/dist/core/utils.js +475 -54
  50. package/dist/core/utils.js.map +1 -1
  51. package/dist/extension/bridge.d.ts +61 -35
  52. package/dist/extension/bridge.d.ts.map +1 -1
  53. package/dist/extension/bridge.js +290 -106
  54. package/dist/extension/bridge.js.map +1 -1
  55. package/dist/extension/http-server.d.ts +3 -0
  56. package/dist/extension/http-server.d.ts.map +1 -1
  57. package/dist/extension/http-server.js +25 -3
  58. package/dist/extension/http-server.js.map +1 -1
  59. package/dist/index.js +7 -0
  60. package/dist/index.js.map +1 -1
  61. package/dist/tools/browse.d.ts +1 -1
  62. package/dist/tools/browse.d.ts.map +1 -1
  63. package/dist/tools/browse.js +291 -175
  64. package/dist/tools/browse.js.map +1 -1
  65. package/dist/tools/challenge.d.ts +153 -0
  66. package/dist/tools/challenge.d.ts.map +1 -0
  67. package/dist/tools/challenge.js +611 -0
  68. package/dist/tools/challenge.js.map +1 -0
  69. package/dist/tools/cookies.d.ts.map +1 -1
  70. package/dist/tools/cookies.js +13 -7
  71. package/dist/tools/cookies.js.map +1 -1
  72. package/dist/tools/diagnostics.d.ts +5 -5
  73. package/dist/tools/diagnostics.d.ts.map +1 -1
  74. package/dist/tools/diagnostics.js +39 -20
  75. package/dist/tools/diagnostics.js.map +1 -1
  76. package/dist/tools/evaluate.d.ts.map +1 -1
  77. package/dist/tools/evaluate.js +106 -23
  78. package/dist/tools/evaluate.js.map +1 -1
  79. package/dist/tools/extract.d.ts.map +1 -1
  80. package/dist/tools/extract.js +199 -208
  81. package/dist/tools/extract.js.map +1 -1
  82. package/dist/tools/input.d.ts +1 -1
  83. package/dist/tools/input.d.ts.map +1 -1
  84. package/dist/tools/input.js +523 -175
  85. package/dist/tools/input.js.map +1 -1
  86. package/dist/tools/logs.d.ts.map +1 -1
  87. package/dist/tools/logs.js +7 -7
  88. package/dist/tools/logs.js.map +1 -1
  89. package/dist/tools/manage.d.ts.map +1 -1
  90. package/dist/tools/manage.js +400 -64
  91. package/dist/tools/manage.js.map +1 -1
  92. package/dist/tools/network-sanitizer.d.ts.map +1 -1
  93. package/dist/tools/network-sanitizer.js +1 -0
  94. package/dist/tools/network-sanitizer.js.map +1 -1
  95. package/dist/tools/page-context.d.ts +17 -0
  96. package/dist/tools/page-context.d.ts.map +1 -0
  97. package/dist/tools/page-context.js +103 -0
  98. package/dist/tools/page-context.js.map +1 -0
  99. package/dist/tools/png.d.ts +5 -0
  100. package/dist/tools/png.d.ts.map +1 -1
  101. package/dist/tools/png.js +89 -22
  102. package/dist/tools/png.js.map +1 -1
  103. package/dist/tools/post-condition.d.ts.map +1 -1
  104. package/dist/tools/post-condition.js +17 -5
  105. package/dist/tools/post-condition.js.map +1 -1
  106. package/dist/tools/schema.d.ts +9 -0
  107. package/dist/tools/schema.d.ts.map +1 -1
  108. package/dist/tools/schema.js +15 -0
  109. package/dist/tools/schema.js.map +1 -1
  110. package/dist/tools/target-diagnostics.d.ts +7 -0
  111. package/dist/tools/target-diagnostics.d.ts.map +1 -1
  112. package/dist/tools/target-diagnostics.js +47 -17
  113. package/dist/tools/target-diagnostics.js.map +1 -1
  114. package/dist/tools/wait.d.ts.map +1 -1
  115. package/dist/tools/wait.js +52 -56
  116. package/dist/tools/wait.js.map +1 -1
  117. package/extension/dist/assets/content.ts-C4imZ6A9.js +13 -0
  118. package/extension/dist/assets/content.ts-loader-CnJuCGhl.js +13 -0
  119. package/extension/dist/assets/{index.ts-GG6dPUPX.js → index.ts-GeHNZBml.js} +2156 -1950
  120. package/extension/dist/assets/page-scripts-CMIY1zhd.js +1379 -0
  121. package/extension/dist/assets/{popup.html-B81xccfq.js → popup.html-CgtWL6Py.js} +48 -1
  122. package/extension/dist/manifest.json +4 -3
  123. package/extension/dist/service-worker-loader.js +1 -1
  124. package/extension/dist/src/popup/popup.html +54 -44
  125. package/package.json +11 -8
  126. package/scripts/start-chrome.ps1 +58 -0
  127. package/dist/extension/native-host-installer.d.ts +0 -21
  128. package/dist/extension/native-host-installer.d.ts.map +0 -1
  129. package/dist/extension/native-host-installer.js +0 -147
  130. package/dist/extension/native-host-installer.js.map +0 -1
  131. package/dist/extension/socket-server.d.ts +0 -32
  132. package/dist/extension/socket-server.d.ts.map +0 -1
  133. package/dist/extension/socket-server.js +0 -177
  134. package/dist/extension/socket-server.js.map +0 -1
  135. package/dist/extension/ws-server.d.ts +0 -40
  136. package/dist/extension/ws-server.d.ts.map +0 -1
  137. package/dist/extension/ws-server.js +0 -246
  138. package/dist/extension/ws-server.js.map +0 -1
  139. package/dist/native-host/index.js +0 -280
  140. package/dist/native-host/mcp-chrome-host +0 -2
  141. package/extension/dist/assets/content.ts-Cj_iiU2s.js +0 -25
@@ -7,13 +7,16 @@
7
7
  * - 页面状态
8
8
  * - 日志收集
9
9
  */
10
+ import { randomUUID } from 'node:crypto';
10
11
  import { BehaviorSimulator, getAntiDetectionScript } from '../anti-detection/index.js';
12
+ import { assertScreenshotBase64Budget, assertScreenshotBudget } from '../tools/png.js';
11
13
  import { BrowserLauncher, CDPClient, getBrowserWSEndpoint, getTargets } from '../cdp/index.js';
12
14
  import { AutoWait } from './auto-wait.js';
13
15
  import { DriverCapabilityError, } from './browser-driver.js';
14
- import { NavigationError, NavigationTimeoutError, SessionNotFoundError, TargetNotFoundError } from './errors.js';
16
+ import { CDPError, creationError, StructuredToolError, NavigationError, NavigationTimeoutError, PagePreconditionError, SessionNotFoundError, TargetNotFoundError, TimeoutError, } from './errors.js';
15
17
  import { Locator } from './locator.js';
16
18
  import { DEFAULT_TIMEOUT, extractCdpValue, formatCdpException, MODIFIER_KEYS, } from './types.js';
19
+ import { remainingNavigationTimeout, waitForNavigationQueue, withNavigationBudget } from './utils.js';
17
20
  function wildcardSegmentMatches(value, segment, index) {
18
21
  if (index + segment.length > value.length) {
19
22
  return false;
@@ -54,6 +57,12 @@ function matchesUrlPattern(url, pattern) {
54
57
  }
55
58
  return true;
56
59
  }
60
+ function isCloudflareChallenge(headers) {
61
+ if (!headers) {
62
+ return false;
63
+ }
64
+ return Object.entries(headers).some(([name, value]) => name.toLowerCase() === 'cf-mitigated' && String(value).toLowerCase() === 'challenge');
65
+ }
57
66
  /**
58
67
  * 会话管理器(单例)
59
68
  */
@@ -67,6 +76,9 @@ class SessionManager {
67
76
  sessionId = null;
68
77
  currentTargetId = null;
69
78
  state = null;
79
+ revisionEpoch = randomUUID();
80
+ revisions = new Map();
81
+ pendingPageCondition = null;
70
82
  behaviorSimulator = new BehaviorSimulator();
71
83
  stealthMode = 'safe';
72
84
  /** 当前按下的修饰键位掩码 */
@@ -75,6 +87,12 @@ class SessionManager {
75
87
  operationLock = Promise.resolve();
76
88
  consoleLogs = [];
77
89
  networkRequests = [];
90
+ nextConsoleLogSequence = 0;
91
+ nextNetworkRequestSequence = 0;
92
+ challengeRequired = false;
93
+ runtimeEnabled = false;
94
+ mainFrameId = null;
95
+ mainFrameLoaderId = null;
78
96
  requestMap = new Map();
79
97
  // 监听器安装标志(防止重复安装)
80
98
  listenersInstalled = false;
@@ -130,6 +148,7 @@ class SessionManager {
130
148
  return {
131
149
  ...newTarget,
132
150
  reused: true,
151
+ targetCreated: true,
133
152
  };
134
153
  }
135
154
  return {
@@ -138,6 +157,7 @@ class SessionManager {
138
157
  url: pageTarget.url,
139
158
  title: pageTarget.title,
140
159
  reused: true,
160
+ targetCreated: false,
141
161
  };
142
162
  }
143
163
  catch {
@@ -205,10 +225,10 @@ class SessionManager {
205
225
  /**
206
226
  * 列出所有可用页面
207
227
  */
208
- async listTargets() {
228
+ async listTargets(timeout) {
209
229
  this.ensureConnected();
210
230
  // 从 CDP 获取 targets
211
- const { targetInfos } = (await this.cdp.send('Target.getTargets'));
231
+ const { targetInfos } = (await this.sendBrowserCommand('Target.getTargets', undefined, timeout));
212
232
  return targetInfos
213
233
  .filter((t) => t.type === 'page')
214
234
  .map((t) => ({
@@ -217,7 +237,7 @@ class SessionManager {
217
237
  url: t.url,
218
238
  title: t.title,
219
239
  type: t.type,
220
- active: t.targetId === this.currentTargetId,
240
+ revision: `${this.revisionEpoch}:${this.revisions.get(t.targetId) ?? 0}`,
221
241
  }));
222
242
  }
223
243
  /**
@@ -230,28 +250,33 @@ class SessionManager {
230
250
  * 导航到 URL
231
251
  */
232
252
  async navigate(url, options = {}) {
253
+ const deadline = Date.now() + (options.timeout ?? DEFAULT_TIMEOUT);
233
254
  return this.withLock(async () => {
234
255
  this.ensureSession();
235
- const { wait = 'load', timeout = DEFAULT_TIMEOUT } = options;
236
- // networkidle:先注册监听器再 navigate,避免 navigate 返回和监听器注册之间的竞态窗口
237
- // noinspection ES6MissingAwait — 故意不 await,Promise 在 navigate 完成后才消费
238
- const networkIdlePromise = wait === 'networkidle' ? this.startNetworkIdleWatcher(timeout) : null;
239
- // 导航(传 timeout 防止 CDP 默认 30s 截断用户预算)
240
- const { errorText } = (await this.send('Page.navigate', { url }, timeout));
241
- if (errorText) {
242
- throw new NavigationError(url, errorText);
243
- }
244
- // 根据 wait 类型等待
245
- if (networkIdlePromise) {
246
- await networkIdlePromise;
256
+ const { wait = 'load' } = options;
257
+ const abortController = new AbortController();
258
+ const navigationWait = this.startNavigationWait(wait, remainingNavigationTimeout(deadline), abortController.signal, false);
259
+ navigationWait.promise.catch(() => { });
260
+ navigationWait.markActionStarted();
261
+ try {
262
+ const { frameId, loaderId, errorText } = (await this.send('Page.navigate', { url }, remainingNavigationTimeout(deadline)));
263
+ if (errorText) {
264
+ throw new NavigationError(url, errorText);
265
+ }
266
+ if (loaderId) {
267
+ navigationWait.setExpectedLoader(frameId, loaderId);
268
+ }
269
+ else {
270
+ navigationWait.setExpectedSameDocument(frameId);
271
+ }
247
272
  }
248
- else {
249
- const eventName = wait === 'domcontentloaded' ? 'Page.domContentEventFired' : 'Page.loadEventFired';
250
- await this.cdp.waitForEvent(eventName, undefined, timeout);
273
+ catch (error) {
274
+ abortController.abort(error);
275
+ throw error;
251
276
  }
252
- // 更新状态
253
- await this.updateState();
254
- });
277
+ await navigationWait.promise;
278
+ await this.updateState(remainingNavigationTimeout(deadline));
279
+ }, deadline);
255
280
  }
256
281
  /**
257
282
  * 等待网络空闲(无进行中的请求且持续指定时间)
@@ -267,60 +292,71 @@ class SessionManager {
267
292
  */
268
293
  async waitForNavigation(timeout = DEFAULT_TIMEOUT) {
269
294
  this.ensureSession();
270
- await this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument'], timeout);
295
+ await this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument', 'Page.frameNavigated'], timeout);
271
296
  }
272
297
  /**
273
298
  * 后退
274
299
  */
275
300
  async goBack(timeout = DEFAULT_TIMEOUT) {
301
+ const deadline = Date.now() + timeout;
276
302
  return this.withLock(async () => {
277
303
  this.ensureSession();
278
- const { currentIndex, entries } = await this.send('Page.getNavigationHistory', undefined, timeout);
304
+ const { currentIndex, entries } = await this.send('Page.getNavigationHistory', undefined, remainingNavigationTimeout(deadline));
279
305
  if (currentIndex <= 0) {
280
306
  return { navigated: false };
281
307
  }
282
- // 跨文档导航触发 loadEventFired,同文档导航(hash/pushState)触发 navigatedWithinDocument
283
- const waitPromise = this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument'], timeout);
308
+ // 跨文档加载、主 frame BFCache 恢复和同文档导航分别提供完成事件
309
+ const waitPromise = this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument', 'Page.frameNavigated'], remainingNavigationTimeout(deadline));
284
310
  // 预注册 rejection handler:若 send() 抛错导致 waitPromise 永远不被 await,
285
311
  // 其 timer reject 不会成为 unhandled rejection(Node 20 默认会退出进程)
286
312
  waitPromise.catch(() => { });
287
- await this.send('Page.navigateToHistoryEntry', { entryId: entries[currentIndex - 1].id }, timeout);
313
+ await this.send('Page.navigateToHistoryEntry', { entryId: entries[currentIndex - 1].id }, remainingNavigationTimeout(deadline));
288
314
  await waitPromise;
289
- await this.updateState();
315
+ await this.updateState(remainingNavigationTimeout(deadline));
290
316
  return { navigated: true };
291
- });
317
+ }, deadline);
292
318
  }
293
319
  /**
294
320
  * 前进
295
321
  */
296
322
  async goForward(timeout = DEFAULT_TIMEOUT) {
323
+ const deadline = Date.now() + timeout;
297
324
  return this.withLock(async () => {
298
325
  this.ensureSession();
299
- const { currentIndex, entries } = await this.send('Page.getNavigationHistory', undefined, timeout);
326
+ const { currentIndex, entries } = await this.send('Page.getNavigationHistory', undefined, remainingNavigationTimeout(deadline));
300
327
  if (currentIndex >= entries.length - 1) {
301
328
  return { navigated: false };
302
329
  }
303
- // 跨文档导航触发 loadEventFired,同文档导航(hash/pushState)触发 navigatedWithinDocument
304
- const waitPromise = this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument'], timeout);
330
+ // 跨文档加载、主 frame BFCache 恢复和同文档导航分别提供完成事件
331
+ const waitPromise = this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument', 'Page.frameNavigated'], remainingNavigationTimeout(deadline));
305
332
  waitPromise.catch(() => { });
306
- await this.send('Page.navigateToHistoryEntry', { entryId: entries[currentIndex + 1].id }, timeout);
333
+ await this.send('Page.navigateToHistoryEntry', { entryId: entries[currentIndex + 1].id }, remainingNavigationTimeout(deadline));
307
334
  await waitPromise;
308
- await this.updateState();
335
+ await this.updateState(remainingNavigationTimeout(deadline));
309
336
  return { navigated: true };
310
- });
337
+ }, deadline);
311
338
  }
312
339
  /**
313
340
  * 刷新
314
341
  */
315
- async reload(ignoreCache = false, _waitUntil, timeout = DEFAULT_TIMEOUT) {
342
+ async reload(ignoreCache = false, waitUntil = 'load', timeout = DEFAULT_TIMEOUT) {
343
+ const deadline = Date.now() + timeout;
316
344
  return this.withLock(async () => {
317
345
  this.ensureSession();
318
- const waitPromise = this.cdp.waitForEvent('Page.loadEventFired', undefined, timeout);
319
- waitPromise.catch(() => { });
320
- await this.send('Page.reload', { ignoreCache }, timeout);
321
- await waitPromise;
322
- await this.updateState();
323
- });
346
+ const abortController = new AbortController();
347
+ const navigationWait = this.startNavigationWait(waitUntil, remainingNavigationTimeout(deadline), abortController.signal, true);
348
+ navigationWait.promise.catch(() => { });
349
+ navigationWait.markActionStarted();
350
+ try {
351
+ await this.send('Page.reload', { ignoreCache }, remainingNavigationTimeout(deadline));
352
+ }
353
+ catch (error) {
354
+ abortController.abort(error);
355
+ throw error;
356
+ }
357
+ await navigationWait.promise;
358
+ await this.updateState(remainingNavigationTimeout(deadline));
359
+ }, deadline);
324
360
  }
325
361
  /**
326
362
  * 创建定位器
@@ -349,7 +385,7 @@ class SessionManager {
349
385
  /**
350
386
  * 鼠标移动
351
387
  */
352
- async mouseMove(x, y) {
388
+ async mouseMove(x, y, timeout) {
353
389
  this.ensureSession();
354
390
  // 整数点位:避免 sub-pixel 渲染时坐标命中元素边界外的情况(与 Playwright 一致)
355
391
  const ix = Math.round(x);
@@ -359,7 +395,7 @@ class SessionManager {
359
395
  x: ix,
360
396
  y: iy,
361
397
  modifiers: this.modifiers,
362
- });
398
+ }, timeout);
363
399
  this.behaviorSimulator.setCurrentPosition({ x: ix, y: iy });
364
400
  }
365
401
  /**
@@ -413,13 +449,11 @@ class SessionManager {
413
449
  */
414
450
  async keyDown(key, commands, options) {
415
451
  this.ensureSession();
416
- if (MODIFIER_KEYS[key]) {
417
- this.modifiers |= MODIFIER_KEYS[key];
418
- }
452
+ const nextModifiers = MODIFIER_KEYS[key] ? this.modifiers | MODIFIER_KEYS[key] : this.modifiers;
419
453
  const keyDefinition = getKeyDefinition(key);
420
454
  const params = {
421
455
  type: options?.rawKeyDown ? 'rawKeyDown' : 'keyDown',
422
- modifiers: this.modifiers,
456
+ modifiers: nextModifiers,
423
457
  ...keyDefinition,
424
458
  };
425
459
  if (commands && commands.length > 0) {
@@ -430,6 +464,7 @@ class SessionManager {
430
464
  params.autoRepeat = true;
431
465
  }
432
466
  await this.send('Input.dispatchKeyEvent', params);
467
+ this.modifiers = nextModifiers;
433
468
  }
434
469
  /**
435
470
  * 键盘释放
@@ -448,8 +483,16 @@ class SessionManager {
448
483
  /**
449
484
  * 输入文本
450
485
  */
451
- async type(text, delay = 0) {
486
+ async type(text, delay = 0, timeout = DEFAULT_TIMEOUT) {
452
487
  this.ensureSession();
488
+ const deadline = Date.now() + timeout;
489
+ const remainingTimeout = () => {
490
+ const remaining = deadline - Date.now();
491
+ if (remaining <= 0) {
492
+ throw new TimeoutError('input timeout during typing');
493
+ }
494
+ return remaining;
495
+ };
453
496
  // 归一化换行:\r\n 和 \r 都视作单个 \n
454
497
  const normalized = text.replace(/\r\n?/g, '\n');
455
498
  for (const char of normalized) {
@@ -462,36 +505,29 @@ class SessionManager {
462
505
  nativeVirtualKeyCode: 13,
463
506
  modifiers: this.modifiers,
464
507
  };
465
- await this.send('Input.dispatchKeyEvent', {
466
- type: 'keyDown',
467
- ...enterParams,
468
- });
469
- await this.send('Input.dispatchKeyEvent', {
470
- type: 'char',
471
- text: '\r',
472
- ...enterParams,
473
- });
474
- await this.send('Input.dispatchKeyEvent', {
475
- type: 'keyUp',
476
- ...enterParams,
477
- });
508
+ const keyDownTimeout = remainingTimeout();
509
+ try {
510
+ await this.send('Input.dispatchKeyEvent', { type: 'keyDown', ...enterParams }, keyDownTimeout);
511
+ await this.send('Input.dispatchKeyEvent', { type: 'char', text: '\r', ...enterParams }, remainingTimeout());
512
+ }
513
+ finally {
514
+ await this.send('Input.dispatchKeyEvent', { type: 'keyUp', ...enterParams }, Math.max(1, deadline - Date.now()));
515
+ }
478
516
  }
479
517
  else {
480
- await this.send('Input.dispatchKeyEvent', {
481
- type: 'keyDown',
482
- modifiers: this.modifiers,
483
- text: char,
484
- });
485
- await this.send('Input.dispatchKeyEvent', {
486
- type: 'keyUp',
487
- modifiers: this.modifiers,
488
- text: char,
489
- });
518
+ const keyDownTimeout = remainingTimeout();
519
+ try {
520
+ await this.send('Input.dispatchKeyEvent', { type: 'keyDown', modifiers: this.modifiers, text: char }, keyDownTimeout);
521
+ }
522
+ finally {
523
+ await this.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: this.modifiers, text: char }, Math.max(1, deadline - Date.now()));
524
+ }
490
525
  }
491
526
  if (delay > 0) {
492
- await new Promise((r) => setTimeout(r, delay));
527
+ await new Promise((r) => setTimeout(r, Math.min(delay, remainingTimeout())));
493
528
  }
494
529
  }
530
+ remainingTimeout();
495
531
  }
496
532
  /**
497
533
  * 触屏开始
@@ -545,6 +581,7 @@ class SessionManager {
545
581
  catch {
546
582
  throw new Error(`screenshot: 无法解析页面尺寸: ${result.value}`);
547
583
  }
584
+ assertScreenshotBudget(width, height, scale ?? 1);
548
585
  // 设置视口
549
586
  await this.send('Emulation.setDeviceMetricsOverride', {
550
587
  width,
@@ -554,6 +591,7 @@ class SessionManager {
554
591
  });
555
592
  try {
556
593
  const { data } = (await this.send('Page.captureScreenshot', captureParams));
594
+ assertScreenshotBase64Budget(data);
557
595
  return { data, format: effectiveFormat };
558
596
  }
559
597
  finally {
@@ -565,7 +603,19 @@ class SessionManager {
565
603
  }
566
604
  }
567
605
  }
606
+ if (clip) {
607
+ assertScreenshotBudget(clip.width, clip.height, scale ?? 1);
608
+ }
609
+ else {
610
+ const metrics = (await this.send('Page.getLayoutMetrics'));
611
+ const viewport = metrics.cssVisualViewport ?? metrics.cssLayoutViewport;
612
+ if (!viewport) {
613
+ throw new Error('screenshot: 浏览器未返回 CSS 视口尺寸,未执行截图');
614
+ }
615
+ assertScreenshotBudget(viewport.clientWidth, viewport.clientHeight, 1);
616
+ }
568
617
  const { data } = (await this.send('Page.captureScreenshot', captureParams));
618
+ assertScreenshotBase64Budget(data);
569
619
  return { data, format: effectiveFormat };
570
620
  }
571
621
  /**
@@ -633,15 +683,18 @@ class SessionManager {
633
683
  async getPageText(selector) {
634
684
  this.ensureSession();
635
685
  if (selector) {
636
- return this.evaluate(`(s => document.querySelector(s)?.textContent || '')`, [selector]);
686
+ return this.evaluate(`(s => {
687
+ const element = document.querySelector(s);
688
+ return element instanceof HTMLElement ? element.innerText : (element?.textContent ?? '');
689
+ })`, [selector]);
637
690
  }
638
691
  return this.evaluate('document.body.innerText');
639
692
  }
640
693
  // ==================== IBrowserDriver: 页面读取 ====================
641
694
  /** Extension readPage 等价物:CDP 通过页面 DOM 构造 pageContent 和 interactiveElements */
642
- async readPage(_options) {
695
+ async readPage(options) {
643
696
  const state = await this.getPageState();
644
- const interactiveElements = await this.collectInteractiveElements();
697
+ const interactiveElements = await this.collectInteractiveElements(options?.depth);
645
698
  const lines = interactiveElements.map((e) => {
646
699
  let line = e.role;
647
700
  if (e.name) {
@@ -655,8 +708,10 @@ class SessionManager {
655
708
  interactiveElements,
656
709
  };
657
710
  }
658
- async collectInteractiveElements() {
711
+ async collectInteractiveElements(depth) {
712
+ const maxDepth = Number.isInteger(depth) && depth !== undefined && depth >= 0 ? depth : 15;
659
713
  return this.evaluate(`(() => {
714
+ var maxDepth = ${maxDepth};
660
715
  function selectorFor(el) {
661
716
  if (!(el instanceof Element)) return '';
662
717
  if (el.id) return '#' + CSS.escape(el.id);
@@ -665,11 +720,16 @@ class SessionManager {
665
720
  while (current && current.nodeType === Node.ELEMENT_NODE && parts.length < 4) {
666
721
  var part = current.tagName.toLowerCase();
667
722
  if (current.classList && current.classList.length) {
668
- part += '.' + Array.from(current.classList).slice(0, 2).map(function(cls) { return CSS.escape(cls); }).join('.');
723
+ part += '.' + Array.from(current.classList)
724
+ .slice(0, 2)
725
+ .map(function(cls) { return CSS.escape(cls); })
726
+ .join('.');
669
727
  }
670
728
  var parent = current.parentElement;
671
729
  if (parent) {
672
- var siblings = Array.from(parent.children).filter(function(child) { return child.tagName === current.tagName; });
730
+ var siblings = Array.from(parent.children).filter(function(child) {
731
+ return child.tagName === current.tagName;
732
+ });
673
733
  if (siblings.length > 1) part += ':nth-of-type(' + (siblings.indexOf(current) + 1) + ')';
674
734
  }
675
735
  parts.unshift(part);
@@ -677,6 +737,15 @@ class SessionManager {
677
737
  }
678
738
  return parts.join(' > ');
679
739
  }
740
+ function depthFor(el) {
741
+ var depth = 0;
742
+ var current = el;
743
+ while (current.parentElement) {
744
+ depth += 1;
745
+ current = current.parentElement;
746
+ }
747
+ return depth;
748
+ }
680
749
  function roleFor(el) {
681
750
  var explicit = el.getAttribute('role');
682
751
  if (explicit) return explicit;
@@ -684,7 +753,9 @@ class SessionManager {
684
753
  var type = (el.getAttribute('type') || '').toLowerCase();
685
754
  if (tag === 'button' || type === 'button' || type === 'submit' || type === 'reset') return 'button';
686
755
  if (tag === 'a' && el.hasAttribute('href')) return 'link';
687
- if (tag === 'textarea' || tag === 'input' && !['checkbox', 'radio', 'range'].includes(type)) return 'textbox';
756
+ if (tag === 'textarea' || (tag === 'input' && !['checkbox', 'radio', 'range'].includes(type))) {
757
+ return 'textbox';
758
+ }
688
759
  if (type === 'checkbox') return 'checkbox';
689
760
  if (type === 'radio') return 'radio';
690
761
  if (tag === 'select') return 'combobox';
@@ -693,15 +764,28 @@ class SessionManager {
693
764
  return tag;
694
765
  }
695
766
  function nameFor(el) {
696
- return (el.getAttribute('aria-label') || el.getAttribute('title') || el.getAttribute('placeholder') || el.textContent || '').replace(new RegExp('\\s+', 'g'), ' ').trim().slice(0, 160);
767
+ return (
768
+ el.getAttribute('aria-label') ||
769
+ el.getAttribute('title') ||
770
+ el.getAttribute('placeholder') ||
771
+ el.textContent ||
772
+ ''
773
+ ).replace(/\\s+/g, ' ').trim().slice(0, 160);
697
774
  }
698
- var selector = 'button,a[href],input,textarea,select,[role],[contenteditable="true"],[tabindex]:not([tabindex="-1"])';
699
- return Array.from(document.querySelectorAll(selector)).slice(0, 100).map(function(el, index) {
775
+ var selector = [
776
+ 'button,a[href],input,textarea,select,[role]',
777
+ '[contenteditable="true"],[tabindex]:not([tabindex="-1"])'
778
+ ].join(',');
779
+ return Array.from(document.querySelectorAll(selector)).filter(function(el) {
780
+ return depthFor(el) <= maxDepth;
781
+ }).slice(0, 100).map(function(el, index) {
700
782
  var rect = el.getBoundingClientRect();
701
783
  var cx = rect.left + rect.width / 2;
702
784
  var cy = rect.top + rect.height / 2;
703
785
  var top = rect.width > 0 && rect.height > 0 ? document.elementFromPoint(cx, cy) : null;
704
- var visible = rect.width > 0 && rect.height > 0 && getComputedStyle(el).visibility !== 'hidden' && getComputedStyle(el).display !== 'none';
786
+ var style = getComputedStyle(el);
787
+ var visible = rect.width > 0 && rect.height > 0 &&
788
+ style.visibility !== 'hidden' && style.display !== 'none';
705
789
  return {
706
790
  refId: 'cdp-' + index,
707
791
  role: roleFor(el),
@@ -725,12 +809,12 @@ class SessionManager {
725
809
  frames.push({
726
810
  index,
727
811
  frameId: node.frame.id,
728
- parentFrameId: node.frame.parentId ?? parentFrameId,
812
+ parentFrameId: node.frame.parentId ?? parentFrameId ?? null,
729
813
  url: node.frame.url,
730
- title: index === 0 ? this.state?.title : undefined,
731
- name: node.frame.name,
732
- selector: undefined,
733
- rect: undefined,
814
+ title: index === 0 ? (this.state?.title ?? null) : null,
815
+ name: node.frame.name ?? null,
816
+ selector: null,
817
+ rect: null,
734
818
  mimeType: node.frame.mimeType,
735
819
  });
736
820
  for (const child of node.childFrames ?? []) {
@@ -801,6 +885,7 @@ class SessionManager {
801
885
  feeds.push({href: l.href, type: l.getAttribute('type'), title: l.getAttribute('title') || undefined});
802
886
  });
803
887
  return {
888
+ url: location.href,
804
889
  title: document.title,
805
890
  description: meta('description'),
806
891
  canonical: (document.querySelector('link[rel="canonical"]') || {}).href || undefined,
@@ -934,8 +1019,12 @@ class SessionManager {
934
1019
  await this.send('Input.dispatchKeyEvent', params);
935
1020
  }
936
1021
  /** CDP 通用 inputMouse 接口实现:直接转发 Input.dispatchMouseEvent */
937
- async inputMouse(type, x, y, options = {}) {
1022
+ async inputMouse(type, x, y, options = {}, timeout) {
1023
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
938
1024
  this.ensureSession();
1025
+ if (deadline !== undefined) {
1026
+ remainingNavigationTimeout(deadline);
1027
+ }
939
1028
  const params = {
940
1029
  type,
941
1030
  x: Math.round(x),
@@ -956,7 +1045,39 @@ class SessionManager {
956
1045
  if (options.modifiers !== undefined) {
957
1046
  params.modifiers = options.modifiers;
958
1047
  }
959
- await this.send('Input.dispatchMouseEvent', params);
1048
+ if (type === 'mousePressed' && options.releaseAfterPress) {
1049
+ const cdp = this.cdp;
1050
+ const sessionId = this.sessionId ?? undefined;
1051
+ let failed = false;
1052
+ let failure;
1053
+ try {
1054
+ await withNavigationBudget(() => this.send('Input.dispatchMouseEvent', params, deadline === undefined ? undefined : remainingNavigationTimeout(deadline)), deadline);
1055
+ }
1056
+ catch (error) {
1057
+ failed = true;
1058
+ failure = error;
1059
+ }
1060
+ finally {
1061
+ try {
1062
+ await cdp.send('Input.dispatchMouseEvent', { ...params, type: 'mouseReleased' }, sessionId, 1000);
1063
+ }
1064
+ catch (error) {
1065
+ if (failed) {
1066
+ console.warn('[MCP] 鼠标释放清理失败,请检查原目标会话的鼠标状态');
1067
+ }
1068
+ else {
1069
+ failed = true;
1070
+ failure = error;
1071
+ }
1072
+ }
1073
+ }
1074
+ if (failed) {
1075
+ throw failure;
1076
+ }
1077
+ }
1078
+ else {
1079
+ await this.send('Input.dispatchMouseEvent', params, timeout);
1080
+ }
960
1081
  // mouseMoved 同步坐标到 BehaviorSimulator,与 mouseMove 方法保持一致
961
1082
  if (type === 'mouseMoved') {
962
1083
  this.behaviorSimulator.setCurrentPosition({ x: Math.round(x), y: Math.round(y) });
@@ -968,8 +1089,8 @@ class SessionManager {
968
1089
  await this.dispatchTouch({ type, touchPoints });
969
1090
  }
970
1091
  /** CDP inputType 接口实现:直接复用现有 type 方法 */
971
- inputType(text, delay = 0) {
972
- return this.type(text, delay);
1092
+ inputType(text, delay = 0, timeout) {
1093
+ return this.type(text, delay, timeout);
973
1094
  }
974
1095
  // ==================== IBrowserDriver: Stealth(CDP 不支持) ====================
975
1096
  stealthKey(_key, _type, _modifiers) {
@@ -988,9 +1109,9 @@ class SessionManager {
988
1109
  return Promise.reject(new DriverCapabilityError('CDP 模式 stealth 脚本在 connect/launch 时通过 stealth 参数自动注入,不支持后续手动注入'));
989
1110
  }
990
1111
  // ==================== IBrowserDriver: 日志启用 ====================
991
- /** CDP 模式:Network/Runtime 域已在 attach 时启用,no-op */
992
- consoleEnable() {
993
- return Promise.resolve();
1112
+ /** Runtime.enable 会暴露 CDP,只在需要 console 事件时再开 */
1113
+ async consoleEnable() {
1114
+ await this.ensureRuntimeEnabled();
994
1115
  }
995
1116
  /** CDP 模式:Network 域已在 attach 时启用,no-op */
996
1117
  networkEnable() {
@@ -1003,13 +1124,53 @@ class SessionManager {
1003
1124
  await this.activateTarget(targetId);
1004
1125
  }
1005
1126
  /** IBrowserDriver 接口:选择操作目标(attach 即可) */
1006
- async selectPage(targetId) {
1007
- await this.attachToTarget(targetId);
1127
+ async selectPage(targetId, timeout) {
1128
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
1129
+ await this.withLock(() => this.attachToTargetInternal(targetId, deadline), deadline);
1008
1130
  }
1009
1131
  /** IBrowserDriver 接口:获取当前操作目标 ID */
1010
1132
  getCurrentTargetId() {
1011
1133
  return this.currentTargetId;
1012
1134
  }
1135
+ async deselectPage(timeout) {
1136
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
1137
+ try {
1138
+ if (this.sessionId && this.cdp?.isConnected) {
1139
+ await this.cdp.send('Target.detachFromTarget', { sessionId: this.sessionId }, undefined, deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
1140
+ }
1141
+ }
1142
+ finally {
1143
+ this.clearAttachedTargetState();
1144
+ }
1145
+ }
1146
+ async getPageSnapshot(targetId, timeout) {
1147
+ this.ensureConnected();
1148
+ const { targetInfo } = await this.sendBrowserCommand('Target.getTargetInfo', { targetId }, timeout);
1149
+ if (targetInfo.type !== 'page' || targetInfo.targetId !== targetId) {
1150
+ throw new TargetNotFoundError(targetId);
1151
+ }
1152
+ return {
1153
+ targetId,
1154
+ url: targetInfo.url ?? '',
1155
+ revision: `${this.revisionEpoch}:${this.revisions.get(targetId) ?? 0}`,
1156
+ };
1157
+ }
1158
+ setPageCondition(condition) {
1159
+ this.pendingPageCondition = condition;
1160
+ }
1161
+ async assertPageCondition(targetId, expectedUrl, expectedRevision, timeout) {
1162
+ const snapshot = await this.getPageSnapshot(targetId, timeout);
1163
+ if ((expectedUrl !== undefined && snapshot.url !== expectedUrl) ||
1164
+ (expectedRevision !== undefined && snapshot.revision !== expectedRevision)) {
1165
+ throw new PagePreconditionError({
1166
+ targetId,
1167
+ expectedUrl: expectedUrl ?? null,
1168
+ expectedRevision: expectedRevision ?? null,
1169
+ actualUrl: snapshot.url,
1170
+ actualRevision: snapshot.revision,
1171
+ });
1172
+ }
1173
+ }
1013
1174
  /** IBrowserDriver 接口:设置当前操作目标 ID(attach 到指定 target) */
1014
1175
  setCurrentTargetId(targetId) {
1015
1176
  // CDP 路径不支持同步 setCurrentTargetId(attach 是异步的);
@@ -1045,12 +1206,30 @@ class SessionManager {
1045
1206
  * tabId 在 CDP 模式下忽略(CDP 单 session 概念不区分 tab);
1046
1207
  * browser-level 域(Target/Browser/SystemInfo/DeviceAccess/IO)走 sendBrowserCommand
1047
1208
  */
1048
- debuggerSend(method, params, _tabId, timeout) {
1209
+ async debuggerSend(method, params, _tabId, timeout) {
1049
1210
  const domain = method.split('.')[0];
1050
1211
  const browserLevelDomains = ['Target', 'Browser', 'SystemInfo', 'DeviceAccess', 'IO'];
1051
1212
  if (browserLevelDomains.includes(domain)) {
1213
+ if (this.pendingPageCondition) {
1214
+ throw new DriverCapabilityError('浏览器级 CDP 命令不支持页面条件,未执行动作');
1215
+ }
1052
1216
  return this.sendBrowserCommand(method, params);
1053
1217
  }
1218
+ if (this.pendingPageCondition) {
1219
+ const condition = this.pendingPageCondition;
1220
+ if (condition.targetId !== this.currentTargetId) {
1221
+ throw new PagePreconditionError({ targetId: condition.targetId, actualTargetId: this.currentTargetId });
1222
+ }
1223
+ await this.assertPageCondition(condition.targetId, condition.expectedUrl, condition.expectedRevision);
1224
+ this.pendingPageCondition = null;
1225
+ if (this.currentTargetId &&
1226
+ method !== 'Runtime.evaluate' &&
1227
+ method !== 'Runtime.callFunctionOn' &&
1228
+ !method.startsWith('Input.') &&
1229
+ !method.startsWith('Emulation.')) {
1230
+ this.revisions.set(this.currentTargetId, (this.revisions.get(this.currentTargetId) ?? 0) + 1);
1231
+ }
1232
+ }
1054
1233
  return this.send(method, params, timeout);
1055
1234
  }
1056
1235
  /**
@@ -1115,9 +1294,9 @@ class SessionManager {
1115
1294
  }
1116
1295
  async clearCookies(filter) {
1117
1296
  this.ensureSession();
1118
- // Driver 级护栏:禁止无过滤的全站清除,必须带 url/domain/name 至少一项
1119
- if (!filter || (!filter.url && !filter.domain && !filter.name)) {
1120
- throw new Error('clearCookies 必须带 url/domain/name 至少一个过滤参数(防止误清全站 cookies)');
1297
+ // Driver 级护栏:必须按 URL 或域名限定范围,name 只能进一步缩小范围
1298
+ if (!filter || (!filter.url && !filter.domain)) {
1299
+ throw new Error('clearCookies 必须带 url 或 domain 过滤参数,name 只能在该范围内进一步过滤(防止跨站误清同名 cookie)');
1121
1300
  }
1122
1301
  const urls = filter.url ? [filter.url] : undefined;
1123
1302
  const { cookies } = (await this.send('Network.getCookies', urls ? { urls } : {}));
@@ -1153,7 +1332,7 @@ class SessionManager {
1153
1332
  const lp = pattern.toLowerCase();
1154
1333
  logs = logs.filter((l) => l.text.toLowerCase().includes(lp));
1155
1334
  }
1156
- const result = logs.slice(-100);
1335
+ const result = logs;
1157
1336
  if (clear) {
1158
1337
  this.consoleLogs = [];
1159
1338
  }
@@ -1165,13 +1344,16 @@ class SessionManager {
1165
1344
  if (urlPattern) {
1166
1345
  requests = requests.filter((r) => matchesUrlPattern(String(r.url ?? ''), urlPattern));
1167
1346
  }
1168
- const result = requests.slice(-100);
1347
+ const result = requests;
1169
1348
  if (clear) {
1170
1349
  this.networkRequests = [];
1171
1350
  this.requestMap.clear();
1172
1351
  }
1173
1352
  return result;
1174
1353
  }
1354
+ async getChallengeState() {
1355
+ return this.challengeRequired;
1356
+ }
1175
1357
  /**
1176
1358
  * 清除日志
1177
1359
  */
@@ -1189,7 +1371,7 @@ class SessionManager {
1189
1371
  const CDP_MARGIN = 5000;
1190
1372
  const sendTimeout = timeout !== undefined ? timeout + CDP_MARGIN : undefined;
1191
1373
  // 有参数时使用 callFunctionOn:避免大 payload 字符串拼接,参数通过协议结构化传递
1192
- if (args && args.length > 0) {
1374
+ if (args !== undefined) {
1193
1375
  const { result: globalResult } = (await this.send('Runtime.evaluate', {
1194
1376
  expression: 'globalThis',
1195
1377
  returnByValue: false,
@@ -1272,10 +1454,26 @@ class SessionManager {
1272
1454
  *
1273
1455
  * IBrowserDriver 接口:可选 url 参数,url 提供时新建后立即导航
1274
1456
  */
1275
- async newPage(url, _timeout) {
1457
+ async newPage(url, timeout, options = {}) {
1458
+ if (Object.values(options).some((value) => value !== undefined)) {
1459
+ throw new DriverCapabilityError('CDP 模式不支持 Chrome UI 的 newPage 配置参数,未创建页面;请使用 Extension 模式');
1460
+ }
1276
1461
  const target = await this.withLock(async () => this.newPageInternal());
1277
1462
  if (url) {
1278
- await this.navigate(url);
1463
+ try {
1464
+ await this.navigate(url, { timeout });
1465
+ }
1466
+ catch (error) {
1467
+ throw creationError(error, {
1468
+ action: 'newPage',
1469
+ createdTargetId: target.targetId,
1470
+ targetId: target.targetId,
1471
+ managed: false,
1472
+ actionExecuted: true,
1473
+ actionStatus: 'partial',
1474
+ failureStage: 'navigation',
1475
+ });
1476
+ }
1279
1477
  return {
1280
1478
  targetId: target.targetId,
1281
1479
  url: this.state?.url ?? url,
@@ -1302,18 +1500,29 @@ class SessionManager {
1302
1500
  * 关闭页面
1303
1501
  */
1304
1502
  async closePage(targetId) {
1503
+ if (!targetId) {
1504
+ throw new TargetNotFoundError('targetId is required');
1505
+ }
1305
1506
  return this.withLock(async () => {
1306
1507
  this.ensureConnected();
1307
- const id = targetId ?? this.currentTargetId;
1308
- if (!id) {
1309
- throw new TargetNotFoundError('unknown');
1508
+ const targets = await this.listTargets();
1509
+ if (!targets.some((target) => target.targetId === targetId)) {
1510
+ throw new TargetNotFoundError(targetId);
1310
1511
  }
1311
- await this.cdp.send('Target.closeTarget', { targetId: id });
1512
+ const id = targetId;
1513
+ if (this.pendingPageCondition) {
1514
+ const condition = this.pendingPageCondition;
1515
+ await this.assertPageCondition(id, condition.expectedUrl, condition.expectedRevision);
1516
+ this.pendingPageCondition = null;
1517
+ }
1518
+ const result = (await this.cdp.send('Target.closeTarget', { targetId: id }));
1519
+ if (!result.success) {
1520
+ throw new TargetNotFoundError(targetId);
1521
+ }
1522
+ this.revisions.delete(id);
1312
1523
  // 如果关闭的是当前页面,清除会话状态
1313
1524
  if (id === this.currentTargetId) {
1314
- this.sessionId = null;
1315
- this.currentTargetId = null;
1316
- this.state = null;
1525
+ this.clearAttachedTargetState();
1317
1526
  }
1318
1527
  });
1319
1528
  }
@@ -1341,6 +1550,19 @@ class SessionManager {
1341
1550
  getState() {
1342
1551
  return this.state;
1343
1552
  }
1553
+ async getLiveState(timeout) {
1554
+ if (!this.currentTargetId) {
1555
+ return this.state;
1556
+ }
1557
+ this.ensureConnected();
1558
+ const { targetInfo } = await this.sendBrowserCommand('Target.getTargetInfo', { targetId: this.currentTargetId }, timeout);
1559
+ this.state = {
1560
+ url: targetInfo.url ?? '',
1561
+ title: targetInfo.title ?? '',
1562
+ targetId: this.currentTargetId,
1563
+ };
1564
+ return this.state;
1565
+ }
1344
1566
  /**
1345
1567
  * 是否已连接
1346
1568
  */
@@ -1354,17 +1576,40 @@ class SessionManager {
1354
1576
  * 多步操作(type 循环、fullPage 截图等)的 await 间隙可能被 close() 打断,
1355
1577
  * ensureSession() 确保在当前 tick 内 this.cdp 非空
1356
1578
  */
1357
- send(method, params, timeout) {
1579
+ async send(method, params, timeout) {
1580
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
1358
1581
  this.ensureSession();
1359
- return this.cdp.send(method, params, this.sessionId ?? undefined, timeout);
1582
+ const mutation = method === 'Page.navigate' ||
1583
+ method === 'Page.navigateToHistoryEntry' ||
1584
+ method === 'Page.reload' ||
1585
+ method === 'Runtime.evaluate' ||
1586
+ method === 'Runtime.callFunctionOn' ||
1587
+ method.startsWith('Input.') ||
1588
+ method.startsWith('Emulation.');
1589
+ const condition = mutation ? this.pendingPageCondition : null;
1590
+ if (condition) {
1591
+ if (condition.targetId !== this.currentTargetId) {
1592
+ throw new PagePreconditionError({
1593
+ targetId: condition.targetId,
1594
+ actualTargetId: this.currentTargetId,
1595
+ });
1596
+ }
1597
+ await this.assertPageCondition(condition.targetId, condition.expectedUrl, condition.expectedRevision, timeout);
1598
+ this.pendingPageCondition = null;
1599
+ }
1600
+ const remaining = deadline === undefined ? undefined : remainingNavigationTimeout(deadline);
1601
+ if (mutation && this.currentTargetId) {
1602
+ this.revisions.set(this.currentTargetId, (this.revisions.get(this.currentTargetId) ?? 0) + 1);
1603
+ }
1604
+ return this.cdp.send(method, params, this.sessionId ?? undefined, remaining);
1360
1605
  }
1361
1606
  /**
1362
1607
  * 发送 browser-level CDP 命令(不携带 sessionId)
1363
1608
  * 用于 Target.*、Browser.* 等浏览器级命令
1364
1609
  */
1365
- sendBrowserCommand(method, params) {
1610
+ sendBrowserCommand(method, params, timeout) {
1366
1611
  this.ensureConnected();
1367
- return this.cdp.send(method, params);
1612
+ return this.cdp.send(method, params, undefined, timeout);
1368
1613
  }
1369
1614
  /**
1370
1615
  * 派发 CDP Input.dispatchTouchEvent,临时启用 touch 模拟避免命令挂起
@@ -1383,13 +1628,189 @@ class SessionManager {
1383
1628
  }
1384
1629
  }
1385
1630
  }
1386
- /**
1387
- * 在调用 navigate 之前注册网络空闲监听器,返回等待 idle 的 Promise
1388
- * 预先注册避免 Page.navigate 返回和监听器注册之间遗漏早期请求
1389
- */
1390
- startNetworkIdleWatcher(timeout, idleTime = 500) {
1631
+ /** 在触发导航前注册相应等待器,并按主 frame loader 过滤生命周期事件 */
1632
+ startNavigationWait(wait, timeout, signal, bindFromFrameNavigation) {
1391
1633
  this.ensureSession();
1392
- return this.buildNetworkIdlePromise(this.cdp, timeout, idleTime);
1634
+ const cdp = this.cdp;
1635
+ const sessionId = this.sessionId;
1636
+ const baselineLoaderId = this.mainFrameLoaderId;
1637
+ const lifecycleName = wait === 'domcontentloaded' ? 'DOMContentLoaded' : wait === 'load' ? 'load' : 'networkIdle';
1638
+ const seenLifecycle = new Set();
1639
+ const seenSameDocumentFrames = new Set();
1640
+ const sameDocumentPendingRequests = new Set();
1641
+ let actionStarted = false;
1642
+ let expectedFrameId = null;
1643
+ let expectedLoaderId = null;
1644
+ let expectedSameDocumentFrameId = null;
1645
+ let sameDocumentIdleTimer = null;
1646
+ let settled = false;
1647
+ let finish = () => { };
1648
+ let fail = () => { };
1649
+ const lifecycleKey = (frameId, loaderId, name) => JSON.stringify([frameId, loaderId, name]);
1650
+ const completeIfSeen = () => {
1651
+ if (expectedFrameId !== null &&
1652
+ expectedLoaderId !== null &&
1653
+ seenLifecycle.has(lifecycleKey(expectedFrameId, expectedLoaderId, lifecycleName))) {
1654
+ finish();
1655
+ }
1656
+ };
1657
+ const checkSameDocumentIdle = () => {
1658
+ if (settled ||
1659
+ expectedSameDocumentFrameId === null ||
1660
+ !seenSameDocumentFrames.has(expectedSameDocumentFrameId)) {
1661
+ return;
1662
+ }
1663
+ if (sameDocumentPendingRequests.size > 0) {
1664
+ if (sameDocumentIdleTimer !== null) {
1665
+ clearTimeout(sameDocumentIdleTimer);
1666
+ sameDocumentIdleTimer = null;
1667
+ }
1668
+ return;
1669
+ }
1670
+ if (sameDocumentIdleTimer === null) {
1671
+ sameDocumentIdleTimer = setTimeout(() => finish(), 500);
1672
+ }
1673
+ };
1674
+ const completeSameDocumentIfSeen = () => {
1675
+ if (expectedSameDocumentFrameId === null || !seenSameDocumentFrames.has(expectedSameDocumentFrameId)) {
1676
+ return;
1677
+ }
1678
+ if (wait === 'networkidle') {
1679
+ checkSameDocumentIdle();
1680
+ }
1681
+ else {
1682
+ finish();
1683
+ }
1684
+ };
1685
+ const setExpectedLoader = (frameId, loaderId) => {
1686
+ if (settled || !loaderId) {
1687
+ return;
1688
+ }
1689
+ expectedSameDocumentFrameId = null;
1690
+ if (sameDocumentIdleTimer !== null) {
1691
+ clearTimeout(sameDocumentIdleTimer);
1692
+ sameDocumentIdleTimer = null;
1693
+ }
1694
+ expectedFrameId = frameId;
1695
+ expectedLoaderId = loaderId;
1696
+ completeIfSeen();
1697
+ };
1698
+ const setExpectedSameDocument = (frameId) => {
1699
+ if (settled) {
1700
+ return;
1701
+ }
1702
+ expectedSameDocumentFrameId = frameId;
1703
+ completeSameDocumentIfSeen();
1704
+ };
1705
+ const promise = new Promise((resolve, reject) => {
1706
+ const cleanup = () => {
1707
+ clearTimeout(timeoutId);
1708
+ if (sameDocumentIdleTimer !== null) {
1709
+ clearTimeout(sameDocumentIdleTimer);
1710
+ sameDocumentIdleTimer = null;
1711
+ }
1712
+ signal?.removeEventListener('abort', onAbort);
1713
+ cdp.offEvent('Page.frameNavigated', onFrameNavigated);
1714
+ cdp.offEvent('Page.lifecycleEvent', onLifecycleEvent);
1715
+ cdp.offEvent('Page.navigatedWithinDocument', onNavigatedWithinDocument);
1716
+ cdp.offEvent('Network.requestWillBeSent', onRequestStarted);
1717
+ cdp.offEvent('Network.loadingFinished', onRequestFinished);
1718
+ cdp.offEvent('Network.loadingFailed', onRequestFinished);
1719
+ cdp.removeListener('disconnected', onDisconnected);
1720
+ };
1721
+ finish = () => {
1722
+ if (settled) {
1723
+ return;
1724
+ }
1725
+ settled = true;
1726
+ cleanup();
1727
+ resolve();
1728
+ };
1729
+ fail = (error) => {
1730
+ if (settled) {
1731
+ return;
1732
+ }
1733
+ settled = true;
1734
+ cleanup();
1735
+ reject(error);
1736
+ };
1737
+ const onFrameNavigated = (params, eventSessionId) => {
1738
+ if (!actionStarted || !bindFromFrameNavigation || eventSessionId !== sessionId) {
1739
+ return;
1740
+ }
1741
+ const frame = params.frame;
1742
+ if (frame?.id && !frame.parentId && frame.loaderId && frame.loaderId !== baselineLoaderId) {
1743
+ setExpectedLoader(frame.id, frame.loaderId);
1744
+ }
1745
+ };
1746
+ const onLifecycleEvent = (params, eventSessionId) => {
1747
+ if (!actionStarted || eventSessionId !== sessionId) {
1748
+ return;
1749
+ }
1750
+ const event = params;
1751
+ if (!event.frameId || !event.loaderId || !event.name) {
1752
+ return;
1753
+ }
1754
+ seenLifecycle.add(lifecycleKey(event.frameId, event.loaderId, event.name));
1755
+ completeIfSeen();
1756
+ };
1757
+ const onNavigatedWithinDocument = (params, eventSessionId) => {
1758
+ if (!actionStarted || eventSessionId !== sessionId) {
1759
+ return;
1760
+ }
1761
+ const frameId = params.frameId;
1762
+ if (frameId && frameId === this.mainFrameId) {
1763
+ seenSameDocumentFrames.add(frameId);
1764
+ completeSameDocumentIfSeen();
1765
+ }
1766
+ };
1767
+ const onRequestStarted = (params, eventSessionId) => {
1768
+ if (!actionStarted || eventSessionId !== sessionId) {
1769
+ return;
1770
+ }
1771
+ const requestId = params.requestId;
1772
+ if (requestId) {
1773
+ sameDocumentPendingRequests.add(requestId);
1774
+ checkSameDocumentIdle();
1775
+ }
1776
+ };
1777
+ const onRequestFinished = (params, eventSessionId) => {
1778
+ if (!actionStarted || eventSessionId !== sessionId) {
1779
+ return;
1780
+ }
1781
+ const requestId = params.requestId;
1782
+ if (requestId) {
1783
+ sameDocumentPendingRequests.delete(requestId);
1784
+ checkSameDocumentIdle();
1785
+ }
1786
+ };
1787
+ const onAbort = () => {
1788
+ fail(signal?.reason instanceof Error ? signal.reason : new Error('导航等待已取消'));
1789
+ };
1790
+ const onDisconnected = () => fail(new Error('CDP 连接已关闭'));
1791
+ const timeoutId = setTimeout(() => fail(new NavigationTimeoutError(wait, timeout)), timeout);
1792
+ cdp.onEvent('Page.frameNavigated', onFrameNavigated);
1793
+ cdp.onEvent('Page.lifecycleEvent', onLifecycleEvent);
1794
+ cdp.onEvent('Page.navigatedWithinDocument', onNavigatedWithinDocument);
1795
+ if (wait === 'networkidle') {
1796
+ cdp.onEvent('Network.requestWillBeSent', onRequestStarted);
1797
+ cdp.onEvent('Network.loadingFinished', onRequestFinished);
1798
+ cdp.onEvent('Network.loadingFailed', onRequestFinished);
1799
+ }
1800
+ cdp.once('disconnected', onDisconnected);
1801
+ signal?.addEventListener('abort', onAbort, { once: true });
1802
+ if (signal?.aborted) {
1803
+ onAbort();
1804
+ }
1805
+ });
1806
+ return {
1807
+ promise,
1808
+ markActionStarted: () => {
1809
+ actionStarted = true;
1810
+ },
1811
+ setExpectedLoader,
1812
+ setExpectedSameDocument,
1813
+ };
1393
1814
  }
1394
1815
  /**
1395
1816
  * 核心网络空闲等待逻辑
@@ -1397,8 +1818,9 @@ class SessionManager {
1397
1818
  * 捕获 cdp 引用防止 close() 并发置 null,用局部 Set 追踪请求避免污染成员变量
1398
1819
  * close() 时通过 'disconnected' 信号立即 reject
1399
1820
  */
1400
- buildNetworkIdlePromise(cdp, timeout, idleTime) {
1821
+ buildNetworkIdlePromise(cdp, timeout, idleTime, signal) {
1401
1822
  const localPendingRequests = new Set();
1823
+ const sessionId = this.sessionId;
1402
1824
  return new Promise((resolve, reject) => {
1403
1825
  let idleTimer = null;
1404
1826
  let timeoutTimer = null;
@@ -1418,12 +1840,18 @@ class SessionManager {
1418
1840
  }
1419
1841
  }
1420
1842
  };
1421
- const onRequestStart = (params) => {
1843
+ const onRequestStart = (params, eventSessionId) => {
1844
+ if (eventSessionId !== sessionId) {
1845
+ return;
1846
+ }
1422
1847
  const { requestId } = params;
1423
1848
  localPendingRequests.add(requestId);
1424
1849
  checkIdle();
1425
1850
  };
1426
- const onRequestEnd = (params) => {
1851
+ const onRequestEnd = (params, eventSessionId) => {
1852
+ if (eventSessionId !== sessionId) {
1853
+ return;
1854
+ }
1427
1855
  const { requestId } = params;
1428
1856
  localPendingRequests.delete(requestId);
1429
1857
  checkIdle();
@@ -1435,11 +1863,16 @@ class SessionManager {
1435
1863
  if (timeoutTimer !== null) {
1436
1864
  clearTimeout(timeoutTimer);
1437
1865
  }
1866
+ signal?.removeEventListener('abort', onAbort);
1438
1867
  cdp.offEvent('Network.requestWillBeSent', onRequestStart);
1439
1868
  cdp.offEvent('Network.loadingFinished', onRequestEnd);
1440
1869
  cdp.offEvent('Network.loadingFailed', onRequestEnd);
1441
1870
  cdp.removeListener('disconnected', onDisconnected);
1442
1871
  };
1872
+ const onAbort = () => {
1873
+ cleanup();
1874
+ reject(signal?.reason instanceof Error ? signal.reason : new Error('网络空闲等待已取消'));
1875
+ };
1443
1876
  timeoutTimer = setTimeout(() => {
1444
1877
  cleanup();
1445
1878
  reject(new NavigationTimeoutError('networkidle', timeout));
@@ -1452,13 +1885,18 @@ class SessionManager {
1452
1885
  cdp.onEvent('Network.requestWillBeSent', onRequestStart);
1453
1886
  cdp.onEvent('Network.loadingFinished', onRequestEnd);
1454
1887
  cdp.onEvent('Network.loadingFailed', onRequestEnd);
1888
+ signal?.addEventListener('abort', onAbort, { once: true });
1889
+ if (signal?.aborted) {
1890
+ onAbort();
1891
+ return;
1892
+ }
1455
1893
  checkIdle();
1456
1894
  });
1457
1895
  }
1458
1896
  /**
1459
1897
  * 附加到指定页面(内部版本,不加锁,供 launch/connect 等已持锁方法调用)
1460
1898
  */
1461
- async attachToTargetInternal(targetId) {
1899
+ async attachToTargetInternal(targetId, deadline) {
1462
1900
  this.ensureConnected();
1463
1901
  // 如果已经附加到同一个 target,跳过
1464
1902
  if (this.currentTargetId === targetId && this.sessionId) {
@@ -1467,23 +1905,24 @@ class SessionManager {
1467
1905
  // 如果有之前的 session,先分离
1468
1906
  if (this.sessionId) {
1469
1907
  try {
1470
- await this.cdp.send('Target.detachFromTarget', {
1908
+ await this.sendBrowserCommand('Target.detachFromTarget', {
1471
1909
  sessionId: this.sessionId,
1472
- });
1910
+ }, deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
1473
1911
  }
1474
1912
  catch {
1475
1913
  // 忽略分离错误
1476
1914
  }
1477
1915
  }
1916
+ this.clearAttachedTargetState();
1478
1917
  // 附加到目标
1479
- const { sessionId } = (await this.cdp.send('Target.attachToTarget', {
1918
+ const { sessionId } = (await this.sendBrowserCommand('Target.attachToTarget', {
1480
1919
  targetId,
1481
1920
  flatten: true,
1482
- }));
1921
+ }, deadline === undefined ? undefined : remainingNavigationTimeout(deadline)));
1483
1922
  this.sessionId = sessionId;
1484
1923
  this.currentTargetId = targetId;
1485
1924
  // 初始化会话
1486
- await this.initSession();
1925
+ await this.initSession(deadline);
1487
1926
  }
1488
1927
  /**
1489
1928
  * 新建页面(内部版本,不加锁,供 launch 等已持锁方法调用)
@@ -1492,8 +1931,30 @@ class SessionManager {
1492
1931
  this.ensureConnected();
1493
1932
  const { targetId } = (await this.cdp.send('Target.createTarget', {
1494
1933
  url: 'about:blank',
1934
+ }).catch((error) => {
1935
+ throw creationError(error, {
1936
+ action: 'newPage',
1937
+ createdTargetId: null,
1938
+ managed: null,
1939
+ actionExecuted: 'unknown',
1940
+ actionStatus: 'unknown',
1941
+ failureStage: 'create',
1942
+ });
1495
1943
  }));
1496
- await this.attachToTargetInternal(targetId);
1944
+ try {
1945
+ await this.attachToTargetInternal(targetId);
1946
+ }
1947
+ catch (error) {
1948
+ throw creationError(error, {
1949
+ action: 'newPage',
1950
+ createdTargetId: targetId,
1951
+ targetId,
1952
+ managed: false,
1953
+ actionExecuted: true,
1954
+ actionStatus: 'partial',
1955
+ failureStage: 'attach',
1956
+ });
1957
+ }
1497
1958
  return {
1498
1959
  targetId,
1499
1960
  type: 'page',
@@ -1501,6 +1962,20 @@ class SessionManager {
1501
1962
  title: '',
1502
1963
  };
1503
1964
  }
1965
+ clearAttachedTargetState() {
1966
+ this.clearLogs();
1967
+ this.challengeRequired = false;
1968
+ this.runtimeEnabled = false;
1969
+ this.mainFrameId = null;
1970
+ this.mainFrameLoaderId = null;
1971
+ this.modifiers = 0;
1972
+ this.sessionId = null;
1973
+ this.currentTargetId = null;
1974
+ this.state = null;
1975
+ }
1976
+ isCurrentSessionEvent(eventSessionId) {
1977
+ return this.sessionId !== null && eventSessionId === this.sessionId;
1978
+ }
1504
1979
  /**
1505
1980
  * 重置所有状态(同步,不加锁)
1506
1981
  *
@@ -1516,43 +1991,62 @@ class SessionManager {
1516
1991
  this.launcher.close();
1517
1992
  this.launcher = null;
1518
1993
  }
1519
- this.clearLogs();
1520
- this.modifiers = 0;
1994
+ this.clearAttachedTargetState();
1995
+ this.revisionEpoch = randomUUID();
1996
+ this.revisions.clear();
1997
+ this.pendingPageCondition = null;
1521
1998
  this.behaviorSimulator.setCurrentPosition({ x: 0, y: 0 });
1522
- this.sessionId = null;
1523
- this.currentTargetId = null;
1524
- this.state = null;
1525
1999
  this.listenersInstalled = false;
1526
2000
  this.connectedPort = 0;
1527
2001
  }
1528
2002
  /**
1529
2003
  * 串行执行操作(防止并发竞态)
1530
2004
  */
1531
- async withLock(fn) {
2005
+ async withLock(fn, deadline) {
1532
2006
  const previousLock = this.operationLock;
1533
2007
  let releaseLock;
1534
2008
  this.operationLock = new Promise((resolve) => {
1535
2009
  releaseLock = resolve;
1536
2010
  });
2011
+ let acquired = false;
1537
2012
  try {
1538
- await previousLock;
2013
+ await waitForNavigationQueue(previousLock, deadline);
2014
+ acquired = true;
1539
2015
  return await fn();
1540
2016
  }
2017
+ catch (error) {
2018
+ if (deadline !== undefined) {
2019
+ const context = { actionExecuted: 'unknown', actionStatus: 'unknown', retryable: false };
2020
+ if (error instanceof CDPError && error.message.startsWith('CDP 命令超时: ')) {
2021
+ throw new StructuredToolError('TIMEOUT', error.message, '请回读实际页面,勿自动重放导航', context);
2022
+ }
2023
+ if (error instanceof TimeoutError || error instanceof NavigationTimeoutError) {
2024
+ Object.assign(error.context, context);
2025
+ }
2026
+ }
2027
+ throw error;
2028
+ }
1541
2029
  finally {
1542
- releaseLock();
2030
+ if (acquired) {
2031
+ releaseLock();
2032
+ }
2033
+ else {
2034
+ void previousLock.then(releaseLock, releaseLock);
2035
+ }
1543
2036
  }
1544
2037
  }
1545
2038
  /**
1546
2039
  * 等待多个事件中的任一个触发
1547
2040
  *
1548
- * 用于同时监听跨文档导航 (loadEventFired) 和同文档导航 (navigatedWithinDocument),
1549
- * 任一事件触发后清理所有监听器和超时定时器
2041
+ * 监听当前 session 的加载完成、主 frame BFCache 恢复和同文档导航,
2042
+ * 接受完成事件后清理所有监听器和超时定时器
1550
2043
  * close() 时通过 'disconnected' 信号立即 reject,不必等 timer 超时
1551
2044
  */
1552
2045
  waitForAnyEvent(events, timeout) {
1553
2046
  // 捕获当前 cdp 引用,防止 close() 并发置 null 导致回调崩溃
1554
2047
  const cdp = this.cdp;
1555
- if (!cdp) {
2048
+ const sessionId = this.sessionId;
2049
+ if (!cdp || !sessionId) {
1556
2050
  return Promise.reject(new Error('CDP 连接已关闭'));
1557
2051
  }
1558
2052
  return new Promise((resolve, reject) => {
@@ -1574,7 +2068,22 @@ class SessionManager {
1574
2068
  };
1575
2069
  cdp.once('disconnected', onDisconnected);
1576
2070
  for (const event of events) {
1577
- const listener = () => {
2071
+ const listener = (params, eventSessionId) => {
2072
+ if (eventSessionId !== sessionId) {
2073
+ return;
2074
+ }
2075
+ if (event === 'Page.frameNavigated') {
2076
+ const navigation = params;
2077
+ if (navigation.type !== 'BackForwardCacheRestore' ||
2078
+ navigation.frame?.id !== this.mainFrameId ||
2079
+ navigation.frame.parentId) {
2080
+ return;
2081
+ }
2082
+ }
2083
+ if (event === 'Page.navigatedWithinDocument' &&
2084
+ params.frameId !== this.mainFrameId) {
2085
+ return;
2086
+ }
1578
2087
  cleanup();
1579
2088
  resolve();
1580
2089
  };
@@ -1586,30 +2095,30 @@ class SessionManager {
1586
2095
  /**
1587
2096
  * 初始化会话
1588
2097
  */
1589
- async initSession() {
2098
+ async initSession(deadline) {
2099
+ const remaining = () => (deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
1590
2100
  // 启用必要的域
1591
2101
  await Promise.all([
1592
- this.send('Page.enable'),
1593
- this.send('DOM.enable'),
1594
- this.send('Runtime.enable'),
1595
- this.send('Network.enable'),
1596
- this.send('Log.enable'),
2102
+ this.send('Page.enable', undefined, remaining()),
2103
+ this.send('DOM.enable', undefined, remaining()),
2104
+ this.send('Network.enable', undefined, remaining()),
2105
+ this.send('Log.enable', undefined, remaining()),
1597
2106
  ]);
1598
- // 根据 stealth 模式注入反检测脚本
2107
+ await this.send('Page.setLifecycleEventsEnabled', { enabled: true }, remaining());
2108
+ const { frameTree } = await this.send('Page.getFrameTree', undefined, remaining());
2109
+ this.mainFrameId = frameTree.frame.id;
2110
+ this.mainFrameLoaderId = frameTree.frame.loaderId ?? null;
2111
+ // 根据 stealth 模式注入反检测脚本。不在当前文档 Runtime.evaluate,避免干扰 Cloudflare JS Challenge
1599
2112
  if (this.stealthMode !== 'off') {
1600
2113
  const script = getAntiDetectionScript(this.stealthMode);
1601
2114
  await this.send('Page.addScriptToEvaluateOnNewDocument', {
1602
2115
  source: script,
1603
- });
1604
- // 对当前页面立即执行反检测脚本
1605
- await this.send('Runtime.evaluate', {
1606
- expression: script,
1607
- });
2116
+ }, remaining());
1608
2117
  }
1609
2118
  // 监听事件
1610
2119
  this.setupEventListeners();
1611
2120
  // 更新状态
1612
- await this.updateState();
2121
+ await this.updateState(remaining());
1613
2122
  }
1614
2123
  /**
1615
2124
  * 设置事件监听(幂等,只安装一次)
@@ -1619,10 +2128,32 @@ class SessionManager {
1619
2128
  return;
1620
2129
  }
1621
2130
  this.listenersInstalled = true;
2131
+ this.cdp.onEvent('Page.frameNavigated', (params, eventSessionId) => {
2132
+ if (!this.isCurrentSessionEvent(eventSessionId)) {
2133
+ return;
2134
+ }
2135
+ const frame = params.frame;
2136
+ if (frame?.id && !frame.parentId) {
2137
+ this.mainFrameId = frame.id;
2138
+ this.mainFrameLoaderId = frame.loaderId ?? null;
2139
+ if (this.currentTargetId) {
2140
+ this.revisions.set(this.currentTargetId, (this.revisions.get(this.currentTargetId) ?? 0) + 1);
2141
+ }
2142
+ }
2143
+ });
2144
+ this.cdp.onEvent('Page.navigatedWithinDocument', (_params, eventSessionId) => {
2145
+ if (this.isCurrentSessionEvent(eventSessionId) && this.currentTargetId) {
2146
+ this.revisions.set(this.currentTargetId, (this.revisions.get(this.currentTargetId) ?? 0) + 1);
2147
+ }
2148
+ });
1622
2149
  // 控制台日志
1623
- this.cdp.onEvent('Runtime.consoleAPICalled', (params) => {
2150
+ this.cdp.onEvent('Runtime.consoleAPICalled', (params, eventSessionId) => {
2151
+ if (!this.isCurrentSessionEvent(eventSessionId)) {
2152
+ return;
2153
+ }
1624
2154
  const p = params;
1625
2155
  this.consoleLogs.push({
2156
+ sequence: ++this.nextConsoleLogSequence,
1626
2157
  level: p.type,
1627
2158
  text: p.args.map((a) => a.value ?? a.description ?? '').join(' '),
1628
2159
  timestamp: Math.round(p.timestamp), // Runtime.Timestamp 已是 epoch 毫秒
@@ -1635,24 +2166,38 @@ class SessionManager {
1635
2166
  }
1636
2167
  });
1637
2168
  // 网络请求
1638
- this.cdp.onEvent('Network.requestWillBeSent', (params) => {
2169
+ this.cdp.onEvent('Network.requestWillBeSent', (params, eventSessionId) => {
2170
+ if (!this.isCurrentSessionEvent(eventSessionId)) {
2171
+ return;
2172
+ }
1639
2173
  const p = params;
1640
2174
  this.requestMap.set(p.requestId, {
1641
2175
  url: p.request.url,
1642
2176
  method: p.request.method,
1643
2177
  type: p.type,
1644
2178
  timestamp: Math.round(p.wallTime * 1000), // wallTime 是 epoch 秒 → epoch 毫秒
2179
+ frameId: p.frameId,
1645
2180
  _monotonic: p.timestamp, // MonotonicTime 用于 duration 计算
1646
2181
  });
1647
2182
  });
1648
- this.cdp.onEvent('Network.responseReceived', (params) => {
2183
+ this.cdp.onEvent('Network.responseReceived', (params, eventSessionId) => {
2184
+ if (!this.isCurrentSessionEvent(eventSessionId)) {
2185
+ return;
2186
+ }
1649
2187
  const p = params;
1650
2188
  const request = this.requestMap.get(p.requestId);
1651
2189
  if (request) {
1652
- const { _monotonic, ...requestData } = request;
2190
+ const { _monotonic, frameId, ...requestData } = request;
2191
+ const challenge = isCloudflareChallenge(p.response.headers);
2192
+ if (requestData.type.toLowerCase() === 'document' && frameId === this.mainFrameId) {
2193
+ // 仅新的主文档响应可以解除已知 Challenge,清空日志不能解除该状态
2194
+ this.challengeRequired = challenge;
2195
+ }
1653
2196
  this.networkRequests.push({
2197
+ sequence: ++this.nextNetworkRequestSequence,
1654
2198
  ...requestData,
1655
2199
  status: p.response.status,
2200
+ challenge,
1656
2201
  duration: Math.round((p.timestamp - _monotonic) * 1000),
1657
2202
  });
1658
2203
  // 环形缓冲区:批量裁剪到 800 条,均摊 O(n) 开销
@@ -1663,12 +2208,17 @@ class SessionManager {
1663
2208
  }
1664
2209
  });
1665
2210
  // 网络请求失败时写入日志再清理 requestMap,防止 diagnostics 丢失失败请求
1666
- this.cdp.onEvent('Network.loadingFailed', (params) => {
2211
+ this.cdp.onEvent('Network.loadingFailed', (params, eventSessionId) => {
2212
+ if (!this.isCurrentSessionEvent(eventSessionId)) {
2213
+ return;
2214
+ }
1667
2215
  const p = params;
1668
2216
  const request = this.requestMap.get(p.requestId);
1669
2217
  if (request) {
1670
2218
  const { _monotonic, ...requestData } = request;
2219
+ delete requestData.frameId;
1671
2220
  this.networkRequests.push({
2221
+ sequence: ++this.nextNetworkRequestSequence,
1672
2222
  ...requestData,
1673
2223
  type: p.type ?? requestData.type,
1674
2224
  errorText: p.errorText,
@@ -1684,17 +2234,16 @@ class SessionManager {
1684
2234
  /**
1685
2235
  * 更新页面状态
1686
2236
  */
1687
- async updateState() {
1688
- const result = (await this.send('Runtime.evaluate', {
1689
- expression: 'JSON.stringify({ url: location.href, title: document.title })',
1690
- returnByValue: true,
1691
- }));
1692
- const { url, title } = JSON.parse(result.result.value);
1693
- this.state = {
1694
- url,
1695
- title,
1696
- targetId: this.currentTargetId,
1697
- };
2237
+ async updateState(timeout) {
2238
+ await this.getLiveState(timeout);
2239
+ }
2240
+ async ensureRuntimeEnabled() {
2241
+ if (this.runtimeEnabled) {
2242
+ return;
2243
+ }
2244
+ this.ensureSession();
2245
+ await this.send('Runtime.enable');
2246
+ this.runtimeEnabled = true;
1698
2247
  }
1699
2248
  /**
1700
2249
  * 确保已连接