@pyrokine/mcp-chrome 2.4.4 → 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 (116) hide show
  1. package/README.md +401 -102
  2. package/README_zh.md +319 -79
  3. package/dist/anti-detection/injection.js +3 -3
  4. package/dist/cdp/client.d.ts +1 -1
  5. package/dist/cdp/client.d.ts.map +1 -1
  6. package/dist/cdp/client.js +18 -7
  7. package/dist/cdp/client.js.map +1 -1
  8. package/dist/cdp/launcher.d.ts +2 -3
  9. package/dist/cdp/launcher.d.ts.map +1 -1
  10. package/dist/cdp/launcher.js +84 -24
  11. package/dist/cdp/launcher.js.map +1 -1
  12. package/dist/core/auto-wait.d.ts +3 -3
  13. package/dist/core/auto-wait.d.ts.map +1 -1
  14. package/dist/core/auto-wait.js +45 -20
  15. package/dist/core/auto-wait.js.map +1 -1
  16. package/dist/core/browser-driver.d.ts +101 -12
  17. package/dist/core/browser-driver.d.ts.map +1 -1
  18. package/dist/core/browser-driver.js.map +1 -1
  19. package/dist/core/errors.d.ts +16 -0
  20. package/dist/core/errors.d.ts.map +1 -1
  21. package/dist/core/errors.js +77 -0
  22. package/dist/core/errors.js.map +1 -1
  23. package/dist/core/locator.d.ts.map +1 -1
  24. package/dist/core/locator.js +6 -4
  25. package/dist/core/locator.js.map +1 -1
  26. package/dist/core/os-mouse.d.ts +15 -2
  27. package/dist/core/os-mouse.d.ts.map +1 -1
  28. package/dist/core/os-mouse.js +52 -8
  29. package/dist/core/os-mouse.js.map +1 -1
  30. package/dist/core/session.d.ts +34 -19
  31. package/dist/core/session.d.ts.map +1 -1
  32. package/dist/core/session.js +574 -130
  33. package/dist/core/session.js.map +1 -1
  34. package/dist/core/types.d.ts +2 -0
  35. package/dist/core/types.d.ts.map +1 -1
  36. package/dist/core/types.js.map +1 -1
  37. package/dist/core/unified-session.d.ts +95 -20
  38. package/dist/core/unified-session.d.ts.map +1 -1
  39. package/dist/core/unified-session.js +489 -117
  40. package/dist/core/unified-session.js.map +1 -1
  41. package/dist/core/utils.d.ts +5 -0
  42. package/dist/core/utils.d.ts.map +1 -1
  43. package/dist/core/utils.js +475 -54
  44. package/dist/core/utils.js.map +1 -1
  45. package/dist/extension/bridge.d.ts +46 -36
  46. package/dist/extension/bridge.d.ts.map +1 -1
  47. package/dist/extension/bridge.js +269 -112
  48. package/dist/extension/bridge.js.map +1 -1
  49. package/dist/extension/http-server.d.ts +3 -0
  50. package/dist/extension/http-server.d.ts.map +1 -1
  51. package/dist/extension/http-server.js +19 -2
  52. package/dist/extension/http-server.js.map +1 -1
  53. package/dist/index.js +7 -0
  54. package/dist/index.js.map +1 -1
  55. package/dist/tools/browse.d.ts.map +1 -1
  56. package/dist/tools/browse.js +241 -171
  57. package/dist/tools/browse.js.map +1 -1
  58. package/dist/tools/challenge.d.ts +1 -1
  59. package/dist/tools/challenge.d.ts.map +1 -1
  60. package/dist/tools/challenge.js +75 -37
  61. package/dist/tools/challenge.js.map +1 -1
  62. package/dist/tools/cookies.d.ts.map +1 -1
  63. package/dist/tools/cookies.js +5 -3
  64. package/dist/tools/cookies.js.map +1 -1
  65. package/dist/tools/diagnostics.d.ts +3 -3
  66. package/dist/tools/diagnostics.d.ts.map +1 -1
  67. package/dist/tools/diagnostics.js +13 -12
  68. package/dist/tools/diagnostics.js.map +1 -1
  69. package/dist/tools/evaluate.d.ts.map +1 -1
  70. package/dist/tools/evaluate.js +57 -26
  71. package/dist/tools/evaluate.js.map +1 -1
  72. package/dist/tools/extract.d.ts.map +1 -1
  73. package/dist/tools/extract.js +107 -175
  74. package/dist/tools/extract.js.map +1 -1
  75. package/dist/tools/input.d.ts +1 -1
  76. package/dist/tools/input.d.ts.map +1 -1
  77. package/dist/tools/input.js +380 -158
  78. package/dist/tools/input.js.map +1 -1
  79. package/dist/tools/logs.d.ts.map +1 -1
  80. package/dist/tools/logs.js +5 -5
  81. package/dist/tools/logs.js.map +1 -1
  82. package/dist/tools/manage.d.ts.map +1 -1
  83. package/dist/tools/manage.js +380 -57
  84. package/dist/tools/manage.js.map +1 -1
  85. package/dist/tools/page-context.d.ts +17 -0
  86. package/dist/tools/page-context.d.ts.map +1 -0
  87. package/dist/tools/page-context.js +103 -0
  88. package/dist/tools/page-context.js.map +1 -0
  89. package/dist/tools/png.d.ts +5 -0
  90. package/dist/tools/png.d.ts.map +1 -1
  91. package/dist/tools/png.js +84 -19
  92. package/dist/tools/png.js.map +1 -1
  93. package/dist/tools/post-condition.d.ts.map +1 -1
  94. package/dist/tools/post-condition.js +5 -2
  95. package/dist/tools/post-condition.js.map +1 -1
  96. package/dist/tools/schema.d.ts +9 -0
  97. package/dist/tools/schema.d.ts.map +1 -1
  98. package/dist/tools/schema.js +15 -0
  99. package/dist/tools/schema.js.map +1 -1
  100. package/dist/tools/target-diagnostics.d.ts.map +1 -1
  101. package/dist/tools/target-diagnostics.js +32 -19
  102. package/dist/tools/target-diagnostics.js.map +1 -1
  103. package/dist/tools/wait.d.ts.map +1 -1
  104. package/dist/tools/wait.js +19 -25
  105. package/dist/tools/wait.js.map +1 -1
  106. package/extension/dist/assets/content.ts-C4imZ6A9.js +13 -0
  107. package/extension/dist/assets/content.ts-loader-CnJuCGhl.js +13 -0
  108. package/extension/dist/assets/{index.ts-Bqcu2qiN.js → index.ts-GeHNZBml.js} +2040 -2111
  109. package/extension/dist/assets/page-scripts-CMIY1zhd.js +1379 -0
  110. package/extension/dist/assets/{popup.html-B81xccfq.js → popup.html-CgtWL6Py.js} +48 -1
  111. package/extension/dist/manifest.json +4 -3
  112. package/extension/dist/service-worker-loader.js +1 -1
  113. package/extension/dist/src/popup/popup.html +11 -1
  114. package/package.json +9 -7
  115. package/scripts/start-chrome.ps1 +58 -0
  116. 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;
@@ -73,6 +76,9 @@ class SessionManager {
73
76
  sessionId = null;
74
77
  currentTargetId = null;
75
78
  state = null;
79
+ revisionEpoch = randomUUID();
80
+ revisions = new Map();
81
+ pendingPageCondition = null;
76
82
  behaviorSimulator = new BehaviorSimulator();
77
83
  stealthMode = 'safe';
78
84
  /** 当前按下的修饰键位掩码 */
@@ -86,6 +92,7 @@ class SessionManager {
86
92
  challengeRequired = false;
87
93
  runtimeEnabled = false;
88
94
  mainFrameId = null;
95
+ mainFrameLoaderId = null;
89
96
  requestMap = new Map();
90
97
  // 监听器安装标志(防止重复安装)
91
98
  listenersInstalled = false;
@@ -141,6 +148,7 @@ class SessionManager {
141
148
  return {
142
149
  ...newTarget,
143
150
  reused: true,
151
+ targetCreated: true,
144
152
  };
145
153
  }
146
154
  return {
@@ -149,6 +157,7 @@ class SessionManager {
149
157
  url: pageTarget.url,
150
158
  title: pageTarget.title,
151
159
  reused: true,
160
+ targetCreated: false,
152
161
  };
153
162
  }
154
163
  catch {
@@ -216,10 +225,10 @@ class SessionManager {
216
225
  /**
217
226
  * 列出所有可用页面
218
227
  */
219
- async listTargets() {
228
+ async listTargets(timeout) {
220
229
  this.ensureConnected();
221
230
  // 从 CDP 获取 targets
222
- const { targetInfos } = (await this.cdp.send('Target.getTargets'));
231
+ const { targetInfos } = (await this.sendBrowserCommand('Target.getTargets', undefined, timeout));
223
232
  return targetInfos
224
233
  .filter((t) => t.type === 'page')
225
234
  .map((t) => ({
@@ -228,7 +237,7 @@ class SessionManager {
228
237
  url: t.url,
229
238
  title: t.title,
230
239
  type: t.type,
231
- active: t.targetId === this.currentTargetId,
240
+ revision: `${this.revisionEpoch}:${this.revisions.get(t.targetId) ?? 0}`,
232
241
  }));
233
242
  }
234
243
  /**
@@ -241,28 +250,33 @@ class SessionManager {
241
250
  * 导航到 URL
242
251
  */
243
252
  async navigate(url, options = {}) {
253
+ const deadline = Date.now() + (options.timeout ?? DEFAULT_TIMEOUT);
244
254
  return this.withLock(async () => {
245
255
  this.ensureSession();
246
- const { wait = 'load', timeout = DEFAULT_TIMEOUT } = options;
247
- // networkidle:先注册监听器再 navigate,避免 navigate 返回和监听器注册之间的竞态窗口
248
- // noinspection ES6MissingAwait — 故意不 await,Promise 在 navigate 完成后才消费
249
- const networkIdlePromise = wait === 'networkidle' ? this.startNetworkIdleWatcher(timeout) : null;
250
- // 导航(传 timeout 防止 CDP 默认 30s 截断用户预算)
251
- const { errorText } = (await this.send('Page.navigate', { url }, timeout));
252
- if (errorText) {
253
- throw new NavigationError(url, errorText);
254
- }
255
- // 根据 wait 类型等待
256
- if (networkIdlePromise) {
257
- 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
+ }
258
272
  }
259
- else {
260
- const eventName = wait === 'domcontentloaded' ? 'Page.domContentEventFired' : 'Page.loadEventFired';
261
- await this.cdp.waitForEvent(eventName, undefined, timeout, this.sessionId);
273
+ catch (error) {
274
+ abortController.abort(error);
275
+ throw error;
262
276
  }
263
- // 更新状态
264
- await this.updateState();
265
- });
277
+ await navigationWait.promise;
278
+ await this.updateState(remainingNavigationTimeout(deadline));
279
+ }, deadline);
266
280
  }
267
281
  /**
268
282
  * 等待网络空闲(无进行中的请求且持续指定时间)
@@ -278,60 +292,71 @@ class SessionManager {
278
292
  */
279
293
  async waitForNavigation(timeout = DEFAULT_TIMEOUT) {
280
294
  this.ensureSession();
281
- await this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument'], timeout);
295
+ await this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument', 'Page.frameNavigated'], timeout);
282
296
  }
283
297
  /**
284
298
  * 后退
285
299
  */
286
300
  async goBack(timeout = DEFAULT_TIMEOUT) {
301
+ const deadline = Date.now() + timeout;
287
302
  return this.withLock(async () => {
288
303
  this.ensureSession();
289
- const { currentIndex, entries } = await this.send('Page.getNavigationHistory', undefined, timeout);
304
+ const { currentIndex, entries } = await this.send('Page.getNavigationHistory', undefined, remainingNavigationTimeout(deadline));
290
305
  if (currentIndex <= 0) {
291
306
  return { navigated: false };
292
307
  }
293
- // 跨文档导航触发 loadEventFired,同文档导航(hash/pushState)触发 navigatedWithinDocument
294
- 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));
295
310
  // 预注册 rejection handler:若 send() 抛错导致 waitPromise 永远不被 await,
296
311
  // 其 timer reject 不会成为 unhandled rejection(Node 20 默认会退出进程)
297
312
  waitPromise.catch(() => { });
298
- await this.send('Page.navigateToHistoryEntry', { entryId: entries[currentIndex - 1].id }, timeout);
313
+ await this.send('Page.navigateToHistoryEntry', { entryId: entries[currentIndex - 1].id }, remainingNavigationTimeout(deadline));
299
314
  await waitPromise;
300
- await this.updateState();
315
+ await this.updateState(remainingNavigationTimeout(deadline));
301
316
  return { navigated: true };
302
- });
317
+ }, deadline);
303
318
  }
304
319
  /**
305
320
  * 前进
306
321
  */
307
322
  async goForward(timeout = DEFAULT_TIMEOUT) {
323
+ const deadline = Date.now() + timeout;
308
324
  return this.withLock(async () => {
309
325
  this.ensureSession();
310
- const { currentIndex, entries } = await this.send('Page.getNavigationHistory', undefined, timeout);
326
+ const { currentIndex, entries } = await this.send('Page.getNavigationHistory', undefined, remainingNavigationTimeout(deadline));
311
327
  if (currentIndex >= entries.length - 1) {
312
328
  return { navigated: false };
313
329
  }
314
- // 跨文档导航触发 loadEventFired,同文档导航(hash/pushState)触发 navigatedWithinDocument
315
- 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));
316
332
  waitPromise.catch(() => { });
317
- await this.send('Page.navigateToHistoryEntry', { entryId: entries[currentIndex + 1].id }, timeout);
333
+ await this.send('Page.navigateToHistoryEntry', { entryId: entries[currentIndex + 1].id }, remainingNavigationTimeout(deadline));
318
334
  await waitPromise;
319
- await this.updateState();
335
+ await this.updateState(remainingNavigationTimeout(deadline));
320
336
  return { navigated: true };
321
- });
337
+ }, deadline);
322
338
  }
323
339
  /**
324
340
  * 刷新
325
341
  */
326
- async reload(ignoreCache = false, _waitUntil, timeout = DEFAULT_TIMEOUT) {
342
+ async reload(ignoreCache = false, waitUntil = 'load', timeout = DEFAULT_TIMEOUT) {
343
+ const deadline = Date.now() + timeout;
327
344
  return this.withLock(async () => {
328
345
  this.ensureSession();
329
- const waitPromise = this.cdp.waitForEvent('Page.loadEventFired', undefined, timeout, this.sessionId);
330
- waitPromise.catch(() => { });
331
- await this.send('Page.reload', { ignoreCache }, timeout);
332
- await waitPromise;
333
- await this.updateState();
334
- });
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);
335
360
  }
336
361
  /**
337
362
  * 创建定位器
@@ -360,7 +385,7 @@ class SessionManager {
360
385
  /**
361
386
  * 鼠标移动
362
387
  */
363
- async mouseMove(x, y) {
388
+ async mouseMove(x, y, timeout) {
364
389
  this.ensureSession();
365
390
  // 整数点位:避免 sub-pixel 渲染时坐标命中元素边界外的情况(与 Playwright 一致)
366
391
  const ix = Math.round(x);
@@ -370,7 +395,7 @@ class SessionManager {
370
395
  x: ix,
371
396
  y: iy,
372
397
  modifiers: this.modifiers,
373
- });
398
+ }, timeout);
374
399
  this.behaviorSimulator.setCurrentPosition({ x: ix, y: iy });
375
400
  }
376
401
  /**
@@ -424,13 +449,11 @@ class SessionManager {
424
449
  */
425
450
  async keyDown(key, commands, options) {
426
451
  this.ensureSession();
427
- if (MODIFIER_KEYS[key]) {
428
- this.modifiers |= MODIFIER_KEYS[key];
429
- }
452
+ const nextModifiers = MODIFIER_KEYS[key] ? this.modifiers | MODIFIER_KEYS[key] : this.modifiers;
430
453
  const keyDefinition = getKeyDefinition(key);
431
454
  const params = {
432
455
  type: options?.rawKeyDown ? 'rawKeyDown' : 'keyDown',
433
- modifiers: this.modifiers,
456
+ modifiers: nextModifiers,
434
457
  ...keyDefinition,
435
458
  };
436
459
  if (commands && commands.length > 0) {
@@ -441,6 +464,7 @@ class SessionManager {
441
464
  params.autoRepeat = true;
442
465
  }
443
466
  await this.send('Input.dispatchKeyEvent', params);
467
+ this.modifiers = nextModifiers;
444
468
  }
445
469
  /**
446
470
  * 键盘释放
@@ -459,8 +483,16 @@ class SessionManager {
459
483
  /**
460
484
  * 输入文本
461
485
  */
462
- async type(text, delay = 0) {
486
+ async type(text, delay = 0, timeout = DEFAULT_TIMEOUT) {
463
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
+ };
464
496
  // 归一化换行:\r\n 和 \r 都视作单个 \n
465
497
  const normalized = text.replace(/\r\n?/g, '\n');
466
498
  for (const char of normalized) {
@@ -473,36 +505,29 @@ class SessionManager {
473
505
  nativeVirtualKeyCode: 13,
474
506
  modifiers: this.modifiers,
475
507
  };
476
- await this.send('Input.dispatchKeyEvent', {
477
- type: 'keyDown',
478
- ...enterParams,
479
- });
480
- await this.send('Input.dispatchKeyEvent', {
481
- type: 'char',
482
- text: '\r',
483
- ...enterParams,
484
- });
485
- await this.send('Input.dispatchKeyEvent', {
486
- type: 'keyUp',
487
- ...enterParams,
488
- });
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
+ }
489
516
  }
490
517
  else {
491
- await this.send('Input.dispatchKeyEvent', {
492
- type: 'keyDown',
493
- modifiers: this.modifiers,
494
- text: char,
495
- });
496
- await this.send('Input.dispatchKeyEvent', {
497
- type: 'keyUp',
498
- modifiers: this.modifiers,
499
- text: char,
500
- });
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
+ }
501
525
  }
502
526
  if (delay > 0) {
503
- await new Promise((r) => setTimeout(r, delay));
527
+ await new Promise((r) => setTimeout(r, Math.min(delay, remainingTimeout())));
504
528
  }
505
529
  }
530
+ remainingTimeout();
506
531
  }
507
532
  /**
508
533
  * 触屏开始
@@ -556,6 +581,7 @@ class SessionManager {
556
581
  catch {
557
582
  throw new Error(`screenshot: 无法解析页面尺寸: ${result.value}`);
558
583
  }
584
+ assertScreenshotBudget(width, height, scale ?? 1);
559
585
  // 设置视口
560
586
  await this.send('Emulation.setDeviceMetricsOverride', {
561
587
  width,
@@ -565,6 +591,7 @@ class SessionManager {
565
591
  });
566
592
  try {
567
593
  const { data } = (await this.send('Page.captureScreenshot', captureParams));
594
+ assertScreenshotBase64Budget(data);
568
595
  return { data, format: effectiveFormat };
569
596
  }
570
597
  finally {
@@ -576,7 +603,19 @@ class SessionManager {
576
603
  }
577
604
  }
578
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
+ }
579
617
  const { data } = (await this.send('Page.captureScreenshot', captureParams));
618
+ assertScreenshotBase64Budget(data);
580
619
  return { data, format: effectiveFormat };
581
620
  }
582
621
  /**
@@ -644,7 +683,10 @@ class SessionManager {
644
683
  async getPageText(selector) {
645
684
  this.ensureSession();
646
685
  if (selector) {
647
- 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]);
648
690
  }
649
691
  return this.evaluate('document.body.innerText');
650
692
  }
@@ -728,7 +770,7 @@ class SessionManager {
728
770
  el.getAttribute('placeholder') ||
729
771
  el.textContent ||
730
772
  ''
731
- ).replace(new RegExp('\\s+', 'g'), ' ').trim().slice(0, 160);
773
+ ).replace(/\\s+/g, ' ').trim().slice(0, 160);
732
774
  }
733
775
  var selector = [
734
776
  'button,a[href],input,textarea,select,[role]',
@@ -767,12 +809,12 @@ class SessionManager {
767
809
  frames.push({
768
810
  index,
769
811
  frameId: node.frame.id,
770
- parentFrameId: node.frame.parentId ?? parentFrameId,
812
+ parentFrameId: node.frame.parentId ?? parentFrameId ?? null,
771
813
  url: node.frame.url,
772
- title: index === 0 ? this.state?.title : undefined,
773
- name: node.frame.name,
774
- selector: undefined,
775
- rect: undefined,
814
+ title: index === 0 ? (this.state?.title ?? null) : null,
815
+ name: node.frame.name ?? null,
816
+ selector: null,
817
+ rect: null,
776
818
  mimeType: node.frame.mimeType,
777
819
  });
778
820
  for (const child of node.childFrames ?? []) {
@@ -843,6 +885,7 @@ class SessionManager {
843
885
  feeds.push({href: l.href, type: l.getAttribute('type'), title: l.getAttribute('title') || undefined});
844
886
  });
845
887
  return {
888
+ url: location.href,
846
889
  title: document.title,
847
890
  description: meta('description'),
848
891
  canonical: (document.querySelector('link[rel="canonical"]') || {}).href || undefined,
@@ -976,8 +1019,12 @@ class SessionManager {
976
1019
  await this.send('Input.dispatchKeyEvent', params);
977
1020
  }
978
1021
  /** CDP 通用 inputMouse 接口实现:直接转发 Input.dispatchMouseEvent */
979
- async inputMouse(type, x, y, options = {}) {
1022
+ async inputMouse(type, x, y, options = {}, timeout) {
1023
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
980
1024
  this.ensureSession();
1025
+ if (deadline !== undefined) {
1026
+ remainingNavigationTimeout(deadline);
1027
+ }
981
1028
  const params = {
982
1029
  type,
983
1030
  x: Math.round(x),
@@ -998,7 +1045,39 @@ class SessionManager {
998
1045
  if (options.modifiers !== undefined) {
999
1046
  params.modifiers = options.modifiers;
1000
1047
  }
1001
- 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
+ }
1002
1081
  // mouseMoved 同步坐标到 BehaviorSimulator,与 mouseMove 方法保持一致
1003
1082
  if (type === 'mouseMoved') {
1004
1083
  this.behaviorSimulator.setCurrentPosition({ x: Math.round(x), y: Math.round(y) });
@@ -1010,8 +1089,8 @@ class SessionManager {
1010
1089
  await this.dispatchTouch({ type, touchPoints });
1011
1090
  }
1012
1091
  /** CDP inputType 接口实现:直接复用现有 type 方法 */
1013
- inputType(text, delay = 0) {
1014
- return this.type(text, delay);
1092
+ inputType(text, delay = 0, timeout) {
1093
+ return this.type(text, delay, timeout);
1015
1094
  }
1016
1095
  // ==================== IBrowserDriver: Stealth(CDP 不支持) ====================
1017
1096
  stealthKey(_key, _type, _modifiers) {
@@ -1045,13 +1124,53 @@ class SessionManager {
1045
1124
  await this.activateTarget(targetId);
1046
1125
  }
1047
1126
  /** IBrowserDriver 接口:选择操作目标(attach 即可) */
1048
- async selectPage(targetId) {
1049
- 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);
1050
1130
  }
1051
1131
  /** IBrowserDriver 接口:获取当前操作目标 ID */
1052
1132
  getCurrentTargetId() {
1053
1133
  return this.currentTargetId;
1054
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
+ }
1055
1174
  /** IBrowserDriver 接口:设置当前操作目标 ID(attach 到指定 target) */
1056
1175
  setCurrentTargetId(targetId) {
1057
1176
  // CDP 路径不支持同步 setCurrentTargetId(attach 是异步的);
@@ -1087,12 +1206,30 @@ class SessionManager {
1087
1206
  * tabId 在 CDP 模式下忽略(CDP 单 session 概念不区分 tab);
1088
1207
  * browser-level 域(Target/Browser/SystemInfo/DeviceAccess/IO)走 sendBrowserCommand
1089
1208
  */
1090
- debuggerSend(method, params, _tabId, timeout) {
1209
+ async debuggerSend(method, params, _tabId, timeout) {
1091
1210
  const domain = method.split('.')[0];
1092
1211
  const browserLevelDomains = ['Target', 'Browser', 'SystemInfo', 'DeviceAccess', 'IO'];
1093
1212
  if (browserLevelDomains.includes(domain)) {
1213
+ if (this.pendingPageCondition) {
1214
+ throw new DriverCapabilityError('浏览器级 CDP 命令不支持页面条件,未执行动作');
1215
+ }
1094
1216
  return this.sendBrowserCommand(method, params);
1095
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
+ }
1096
1233
  return this.send(method, params, timeout);
1097
1234
  }
1098
1235
  /**
@@ -1234,7 +1371,7 @@ class SessionManager {
1234
1371
  const CDP_MARGIN = 5000;
1235
1372
  const sendTimeout = timeout !== undefined ? timeout + CDP_MARGIN : undefined;
1236
1373
  // 有参数时使用 callFunctionOn:避免大 payload 字符串拼接,参数通过协议结构化传递
1237
- if (args && args.length > 0) {
1374
+ if (args !== undefined) {
1238
1375
  const { result: globalResult } = (await this.send('Runtime.evaluate', {
1239
1376
  expression: 'globalThis',
1240
1377
  returnByValue: false,
@@ -1317,10 +1454,26 @@ class SessionManager {
1317
1454
  *
1318
1455
  * IBrowserDriver 接口:可选 url 参数,url 提供时新建后立即导航
1319
1456
  */
1320
- 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
+ }
1321
1461
  const target = await this.withLock(async () => this.newPageInternal());
1322
1462
  if (url) {
1323
- 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
+ }
1324
1477
  return {
1325
1478
  targetId: target.targetId,
1326
1479
  url: this.state?.url ?? url,
@@ -1347,13 +1500,26 @@ class SessionManager {
1347
1500
  * 关闭页面
1348
1501
  */
1349
1502
  async closePage(targetId) {
1503
+ if (!targetId) {
1504
+ throw new TargetNotFoundError('targetId is required');
1505
+ }
1350
1506
  return this.withLock(async () => {
1351
1507
  this.ensureConnected();
1352
- const id = targetId ?? this.currentTargetId;
1353
- if (!id) {
1354
- throw new TargetNotFoundError('unknown');
1508
+ const targets = await this.listTargets();
1509
+ if (!targets.some((target) => target.targetId === targetId)) {
1510
+ throw new TargetNotFoundError(targetId);
1511
+ }
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;
1355
1517
  }
1356
- await this.cdp.send('Target.closeTarget', { targetId: id });
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);
1357
1523
  // 如果关闭的是当前页面,清除会话状态
1358
1524
  if (id === this.currentTargetId) {
1359
1525
  this.clearAttachedTargetState();
@@ -1384,12 +1550,12 @@ class SessionManager {
1384
1550
  getState() {
1385
1551
  return this.state;
1386
1552
  }
1387
- async getLiveState() {
1553
+ async getLiveState(timeout) {
1388
1554
  if (!this.currentTargetId) {
1389
1555
  return this.state;
1390
1556
  }
1391
1557
  this.ensureConnected();
1392
- const { targetInfo } = await this.sendBrowserCommand('Target.getTargetInfo', { targetId: this.currentTargetId });
1558
+ const { targetInfo } = await this.sendBrowserCommand('Target.getTargetInfo', { targetId: this.currentTargetId }, timeout);
1393
1559
  this.state = {
1394
1560
  url: targetInfo.url ?? '',
1395
1561
  title: targetInfo.title ?? '',
@@ -1410,17 +1576,40 @@ class SessionManager {
1410
1576
  * 多步操作(type 循环、fullPage 截图等)的 await 间隙可能被 close() 打断,
1411
1577
  * ensureSession() 确保在当前 tick 内 this.cdp 非空
1412
1578
  */
1413
- send(method, params, timeout) {
1579
+ async send(method, params, timeout) {
1580
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
1414
1581
  this.ensureSession();
1415
- 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);
1416
1605
  }
1417
1606
  /**
1418
1607
  * 发送 browser-level CDP 命令(不携带 sessionId)
1419
1608
  * 用于 Target.*、Browser.* 等浏览器级命令
1420
1609
  */
1421
- sendBrowserCommand(method, params) {
1610
+ sendBrowserCommand(method, params, timeout) {
1422
1611
  this.ensureConnected();
1423
- return this.cdp.send(method, params);
1612
+ return this.cdp.send(method, params, undefined, timeout);
1424
1613
  }
1425
1614
  /**
1426
1615
  * 派发 CDP Input.dispatchTouchEvent,临时启用 touch 模拟避免命令挂起
@@ -1439,13 +1628,189 @@ class SessionManager {
1439
1628
  }
1440
1629
  }
1441
1630
  }
1442
- /**
1443
- * 在调用 navigate 之前注册网络空闲监听器,返回等待 idle 的 Promise
1444
- * 预先注册避免 Page.navigate 返回和监听器注册之间遗漏早期请求
1445
- */
1446
- startNetworkIdleWatcher(timeout, idleTime = 500) {
1631
+ /** 在触发导航前注册相应等待器,并按主 frame loader 过滤生命周期事件 */
1632
+ startNavigationWait(wait, timeout, signal, bindFromFrameNavigation) {
1447
1633
  this.ensureSession();
1448
- 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
+ };
1449
1814
  }
1450
1815
  /**
1451
1816
  * 核心网络空闲等待逻辑
@@ -1453,7 +1818,7 @@ class SessionManager {
1453
1818
  * 捕获 cdp 引用防止 close() 并发置 null,用局部 Set 追踪请求避免污染成员变量
1454
1819
  * close() 时通过 'disconnected' 信号立即 reject
1455
1820
  */
1456
- buildNetworkIdlePromise(cdp, timeout, idleTime) {
1821
+ buildNetworkIdlePromise(cdp, timeout, idleTime, signal) {
1457
1822
  const localPendingRequests = new Set();
1458
1823
  const sessionId = this.sessionId;
1459
1824
  return new Promise((resolve, reject) => {
@@ -1498,11 +1863,16 @@ class SessionManager {
1498
1863
  if (timeoutTimer !== null) {
1499
1864
  clearTimeout(timeoutTimer);
1500
1865
  }
1866
+ signal?.removeEventListener('abort', onAbort);
1501
1867
  cdp.offEvent('Network.requestWillBeSent', onRequestStart);
1502
1868
  cdp.offEvent('Network.loadingFinished', onRequestEnd);
1503
1869
  cdp.offEvent('Network.loadingFailed', onRequestEnd);
1504
1870
  cdp.removeListener('disconnected', onDisconnected);
1505
1871
  };
1872
+ const onAbort = () => {
1873
+ cleanup();
1874
+ reject(signal?.reason instanceof Error ? signal.reason : new Error('网络空闲等待已取消'));
1875
+ };
1506
1876
  timeoutTimer = setTimeout(() => {
1507
1877
  cleanup();
1508
1878
  reject(new NavigationTimeoutError('networkidle', timeout));
@@ -1515,13 +1885,18 @@ class SessionManager {
1515
1885
  cdp.onEvent('Network.requestWillBeSent', onRequestStart);
1516
1886
  cdp.onEvent('Network.loadingFinished', onRequestEnd);
1517
1887
  cdp.onEvent('Network.loadingFailed', onRequestEnd);
1888
+ signal?.addEventListener('abort', onAbort, { once: true });
1889
+ if (signal?.aborted) {
1890
+ onAbort();
1891
+ return;
1892
+ }
1518
1893
  checkIdle();
1519
1894
  });
1520
1895
  }
1521
1896
  /**
1522
1897
  * 附加到指定页面(内部版本,不加锁,供 launch/connect 等已持锁方法调用)
1523
1898
  */
1524
- async attachToTargetInternal(targetId) {
1899
+ async attachToTargetInternal(targetId, deadline) {
1525
1900
  this.ensureConnected();
1526
1901
  // 如果已经附加到同一个 target,跳过
1527
1902
  if (this.currentTargetId === targetId && this.sessionId) {
@@ -1530,9 +1905,9 @@ class SessionManager {
1530
1905
  // 如果有之前的 session,先分离
1531
1906
  if (this.sessionId) {
1532
1907
  try {
1533
- await this.cdp.send('Target.detachFromTarget', {
1908
+ await this.sendBrowserCommand('Target.detachFromTarget', {
1534
1909
  sessionId: this.sessionId,
1535
- });
1910
+ }, deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
1536
1911
  }
1537
1912
  catch {
1538
1913
  // 忽略分离错误
@@ -1540,14 +1915,14 @@ class SessionManager {
1540
1915
  }
1541
1916
  this.clearAttachedTargetState();
1542
1917
  // 附加到目标
1543
- const { sessionId } = (await this.cdp.send('Target.attachToTarget', {
1918
+ const { sessionId } = (await this.sendBrowserCommand('Target.attachToTarget', {
1544
1919
  targetId,
1545
1920
  flatten: true,
1546
- }));
1921
+ }, deadline === undefined ? undefined : remainingNavigationTimeout(deadline)));
1547
1922
  this.sessionId = sessionId;
1548
1923
  this.currentTargetId = targetId;
1549
1924
  // 初始化会话
1550
- await this.initSession();
1925
+ await this.initSession(deadline);
1551
1926
  }
1552
1927
  /**
1553
1928
  * 新建页面(内部版本,不加锁,供 launch 等已持锁方法调用)
@@ -1556,8 +1931,30 @@ class SessionManager {
1556
1931
  this.ensureConnected();
1557
1932
  const { targetId } = (await this.cdp.send('Target.createTarget', {
1558
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
+ });
1559
1943
  }));
1560
- 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
+ }
1561
1958
  return {
1562
1959
  targetId,
1563
1960
  type: 'page',
@@ -1570,6 +1967,7 @@ class SessionManager {
1570
1967
  this.challengeRequired = false;
1571
1968
  this.runtimeEnabled = false;
1572
1969
  this.mainFrameId = null;
1970
+ this.mainFrameLoaderId = null;
1573
1971
  this.modifiers = 0;
1574
1972
  this.sessionId = null;
1575
1973
  this.currentTargetId = null;
@@ -1594,6 +1992,9 @@ class SessionManager {
1594
1992
  this.launcher = null;
1595
1993
  }
1596
1994
  this.clearAttachedTargetState();
1995
+ this.revisionEpoch = randomUUID();
1996
+ this.revisions.clear();
1997
+ this.pendingPageCondition = null;
1597
1998
  this.behaviorSimulator.setCurrentPosition({ x: 0, y: 0 });
1598
1999
  this.listenersInstalled = false;
1599
2000
  this.connectedPort = 0;
@@ -1601,25 +2002,44 @@ class SessionManager {
1601
2002
  /**
1602
2003
  * 串行执行操作(防止并发竞态)
1603
2004
  */
1604
- async withLock(fn) {
2005
+ async withLock(fn, deadline) {
1605
2006
  const previousLock = this.operationLock;
1606
2007
  let releaseLock;
1607
2008
  this.operationLock = new Promise((resolve) => {
1608
2009
  releaseLock = resolve;
1609
2010
  });
2011
+ let acquired = false;
1610
2012
  try {
1611
- await previousLock;
2013
+ await waitForNavigationQueue(previousLock, deadline);
2014
+ acquired = true;
1612
2015
  return await fn();
1613
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
+ }
1614
2029
  finally {
1615
- releaseLock();
2030
+ if (acquired) {
2031
+ releaseLock();
2032
+ }
2033
+ else {
2034
+ void previousLock.then(releaseLock, releaseLock);
2035
+ }
1616
2036
  }
1617
2037
  }
1618
2038
  /**
1619
2039
  * 等待多个事件中的任一个触发
1620
2040
  *
1621
- * 用于同时监听跨文档导航 (loadEventFired) 和同文档导航 (navigatedWithinDocument),
1622
- * 任意一个事件触发后清理所有监听器和超时定时器
2041
+ * 监听当前 session 的加载完成、主 frame BFCache 恢复和同文档导航,
2042
+ * 接受完成事件后清理所有监听器和超时定时器
1623
2043
  * close() 时通过 'disconnected' 信号立即 reject,不必等 timer 超时
1624
2044
  */
1625
2045
  waitForAnyEvent(events, timeout) {
@@ -1648,10 +2068,22 @@ class SessionManager {
1648
2068
  };
1649
2069
  cdp.once('disconnected', onDisconnected);
1650
2070
  for (const event of events) {
1651
- const listener = (_params, eventSessionId) => {
2071
+ const listener = (params, eventSessionId) => {
1652
2072
  if (eventSessionId !== sessionId) {
1653
2073
  return;
1654
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
+ }
1655
2087
  cleanup();
1656
2088
  resolve();
1657
2089
  };
@@ -1663,27 +2095,30 @@ class SessionManager {
1663
2095
  /**
1664
2096
  * 初始化会话
1665
2097
  */
1666
- async initSession() {
2098
+ async initSession(deadline) {
2099
+ const remaining = () => (deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
1667
2100
  // 启用必要的域
1668
2101
  await Promise.all([
1669
- this.send('Page.enable'),
1670
- this.send('DOM.enable'),
1671
- this.send('Network.enable'),
1672
- 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()),
1673
2106
  ]);
1674
- const { frameTree } = await this.send('Page.getFrameTree');
2107
+ await this.send('Page.setLifecycleEventsEnabled', { enabled: true }, remaining());
2108
+ const { frameTree } = await this.send('Page.getFrameTree', undefined, remaining());
1675
2109
  this.mainFrameId = frameTree.frame.id;
2110
+ this.mainFrameLoaderId = frameTree.frame.loaderId ?? null;
1676
2111
  // 根据 stealth 模式注入反检测脚本。不在当前文档 Runtime.evaluate,避免干扰 Cloudflare JS Challenge
1677
2112
  if (this.stealthMode !== 'off') {
1678
2113
  const script = getAntiDetectionScript(this.stealthMode);
1679
2114
  await this.send('Page.addScriptToEvaluateOnNewDocument', {
1680
2115
  source: script,
1681
- });
2116
+ }, remaining());
1682
2117
  }
1683
2118
  // 监听事件
1684
2119
  this.setupEventListeners();
1685
2120
  // 更新状态
1686
- await this.updateState();
2121
+ await this.updateState(remaining());
1687
2122
  }
1688
2123
  /**
1689
2124
  * 设置事件监听(幂等,只安装一次)
@@ -1700,6 +2135,15 @@ class SessionManager {
1700
2135
  const frame = params.frame;
1701
2136
  if (frame?.id && !frame.parentId) {
1702
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);
1703
2147
  }
1704
2148
  });
1705
2149
  // 控制台日志
@@ -1790,8 +2234,8 @@ class SessionManager {
1790
2234
  /**
1791
2235
  * 更新页面状态
1792
2236
  */
1793
- async updateState() {
1794
- await this.getLiveState();
2237
+ async updateState(timeout) {
2238
+ await this.getLiveState(timeout);
1795
2239
  }
1796
2240
  async ensureRuntimeEnabled() {
1797
2241
  if (this.runtimeEnabled) {