@pyrokine/mcp-chrome 3.1.0 → 3.1.1

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 (107) hide show
  1. package/README.md +597 -306
  2. package/README_zh.md +525 -341
  3. package/dist/cdp/client.d.ts +1 -0
  4. package/dist/cdp/client.d.ts.map +1 -1
  5. package/dist/cdp/client.js +16 -8
  6. package/dist/cdp/client.js.map +1 -1
  7. package/dist/core/browser-driver.d.ts +2 -1
  8. package/dist/core/browser-driver.d.ts.map +1 -1
  9. package/dist/core/browser-driver.js.map +1 -1
  10. package/dist/core/browser-events.d.ts +9 -3
  11. package/dist/core/browser-events.d.ts.map +1 -1
  12. package/dist/core/browser-events.js +365 -195
  13. package/dist/core/browser-events.js.map +1 -1
  14. package/dist/core/challenge-page.d.ts.map +1 -1
  15. package/dist/core/challenge-page.js +6 -1
  16. package/dist/core/challenge-page.js.map +1 -1
  17. package/dist/core/error-sanitizer.d.ts.map +1 -1
  18. package/dist/core/error-sanitizer.js +2 -1
  19. package/dist/core/error-sanitizer.js.map +1 -1
  20. package/dist/core/errors.d.ts.map +1 -1
  21. package/dist/core/errors.js +7 -3
  22. package/dist/core/errors.js.map +1 -1
  23. package/dist/core/file-upload.js +1 -1
  24. package/dist/core/file-upload.js.map +1 -1
  25. package/dist/core/locator.d.ts +1 -0
  26. package/dist/core/locator.d.ts.map +1 -1
  27. package/dist/core/locator.js +19 -11
  28. package/dist/core/locator.js.map +1 -1
  29. package/dist/core/os-mouse.d.ts.map +1 -1
  30. package/dist/core/os-mouse.js +4 -2
  31. package/dist/core/os-mouse.js.map +1 -1
  32. package/dist/core/session.d.ts +4 -3
  33. package/dist/core/session.d.ts.map +1 -1
  34. package/dist/core/session.js +164 -75
  35. package/dist/core/session.js.map +1 -1
  36. package/dist/core/unified-session.d.ts +10 -5
  37. package/dist/core/unified-session.d.ts.map +1 -1
  38. package/dist/core/unified-session.js +138 -59
  39. package/dist/core/unified-session.js.map +1 -1
  40. package/dist/core/utils.d.ts +4 -1
  41. package/dist/core/utils.d.ts.map +1 -1
  42. package/dist/core/utils.js +4 -1
  43. package/dist/core/utils.js.map +1 -1
  44. package/dist/extension/bridge.d.ts +3 -3
  45. package/dist/extension/bridge.d.ts.map +1 -1
  46. package/dist/extension/bridge.js +57 -17
  47. package/dist/extension/bridge.js.map +1 -1
  48. package/dist/extension/http-server.d.ts +1 -0
  49. package/dist/extension/http-server.d.ts.map +1 -1
  50. package/dist/extension/http-server.js +14 -14
  51. package/dist/extension/http-server.js.map +1 -1
  52. package/dist/index.js +2 -1
  53. package/dist/index.js.map +1 -1
  54. package/dist/tools/browser-event-output.js.map +1 -1
  55. package/dist/tools/challenge.d.ts +1 -0
  56. package/dist/tools/challenge.d.ts.map +1 -1
  57. package/dist/tools/challenge.js +113 -17
  58. package/dist/tools/challenge.js.map +1 -1
  59. package/dist/tools/cookies.d.ts.map +1 -1
  60. package/dist/tools/cookies.js +2 -1
  61. package/dist/tools/cookies.js.map +1 -1
  62. package/dist/tools/diagnostics.d.ts.map +1 -1
  63. package/dist/tools/diagnostics.js +2 -1
  64. package/dist/tools/diagnostics.js.map +1 -1
  65. package/dist/tools/evaluate.d.ts.map +1 -1
  66. package/dist/tools/evaluate.js +4 -2
  67. package/dist/tools/evaluate.js.map +1 -1
  68. package/dist/tools/extract.d.ts.map +1 -1
  69. package/dist/tools/extract.js +152 -58
  70. package/dist/tools/extract.js.map +1 -1
  71. package/dist/tools/input.d.ts.map +1 -1
  72. package/dist/tools/input.js +225 -86
  73. package/dist/tools/input.js.map +1 -1
  74. package/dist/tools/logs.js +1 -1
  75. package/dist/tools/logs.js.map +1 -1
  76. package/dist/tools/manage.d.ts.map +1 -1
  77. package/dist/tools/manage.js +18 -8
  78. package/dist/tools/manage.js.map +1 -1
  79. package/dist/tools/network-sanitizer.d.ts +1 -0
  80. package/dist/tools/network-sanitizer.d.ts.map +1 -1
  81. package/dist/tools/network-sanitizer.js +23 -9
  82. package/dist/tools/network-sanitizer.js.map +1 -1
  83. package/dist/tools/page-context.d.ts +1 -1
  84. package/dist/tools/page-context.d.ts.map +1 -1
  85. package/dist/tools/page-context.js +2 -1
  86. package/dist/tools/page-context.js.map +1 -1
  87. package/dist/tools/png.d.ts.map +1 -1
  88. package/dist/tools/png.js +12 -3
  89. package/dist/tools/png.js.map +1 -1
  90. package/dist/tools/post-condition.d.ts.map +1 -1
  91. package/dist/tools/post-condition.js +57 -33
  92. package/dist/tools/post-condition.js.map +1 -1
  93. package/dist/tools/schema.d.ts +1 -1
  94. package/dist/tools/schema.d.ts.map +1 -1
  95. package/dist/tools/target-diagnostics.d.ts.map +1 -1
  96. package/dist/tools/target-diagnostics.js +53 -33
  97. package/dist/tools/target-diagnostics.js.map +1 -1
  98. package/dist/tools/wait.d.ts.map +1 -1
  99. package/dist/tools/wait.js +4 -4
  100. package/dist/tools/wait.js.map +1 -1
  101. package/extension/dist/assets/{content.ts-BAMOcF3R.js → content.ts-C9QgtUYe.js} +1 -1
  102. package/extension/dist/assets/{content.ts-loader-4F9a1EWZ.js → content.ts-loader-yqB_P8vu.js} +1 -1
  103. package/extension/dist/assets/{index.ts-B79g2ikq.js → index.ts-DBFNh8mZ.js} +8650 -8195
  104. package/extension/dist/assets/{page-scripts-CSxn58h1.js → page-scripts-BjqQ0zXt.js} +1 -1
  105. package/extension/dist/manifest.json +4 -4
  106. package/extension/dist/service-worker-loader.js +1 -1
  107. package/package.json +5 -5
@@ -8,14 +8,14 @@
8
8
  * - 日志收集
9
9
  */
10
10
  import { randomUUID } from 'node:crypto';
11
- import { BROWSER_EVENT_METHODS, BrowserEventController, eventRefTarget, } from './browser-events.js';
12
- import { browserEventCommandSchema } from './browser-event-schema.js';
13
- import { installDomHelpers } from './dom-helpers.js';
14
11
  import { BehaviorSimulator, getAntiDetectionScript } from '../anti-detection/index.js';
15
12
  import { BrowserLauncher, CDPClient, getBrowserWSEndpoint, getTargets } from '../cdp/index.js';
16
13
  import { assertScreenshotBase64Budget, assertScreenshotBudget } from '../tools/png.js';
17
14
  import { AutoWait } from './auto-wait.js';
18
15
  import { DriverCapabilityError, } from './browser-driver.js';
16
+ import { browserEventCommandSchema } from './browser-event-schema.js';
17
+ import { BROWSER_EVENT_METHODS, BrowserEventController, eventRefTarget, } from './browser-events.js';
18
+ import { installDomHelpers } from './dom-helpers.js';
19
19
  import { CDPError, creationError, ElementNotFoundError, formatErrorResponse, NavigationError, NavigationTimeoutError, PagePreconditionError, SessionNotFoundError, setErrorSource, StructuredToolError, TargetNotFoundError, TimeoutError, } from './errors.js';
20
20
  import { Locator } from './locator.js';
21
21
  import { DEFAULT_TIMEOUT, extractCdpValue, formatCdpException, MODIFIER_KEYS, } from './types.js';
@@ -258,6 +258,7 @@ class SessionManager {
258
258
  remaining();
259
259
  const pageTarget = targets.find((t) => t.type === 'page');
260
260
  if (!pageTarget) {
261
+ // noinspection ExceptionCaughtLocallyJS -- 外层关闭本次创建的 client 与 launcher
261
262
  throw new Error('未找到页面');
262
263
  }
263
264
  // 附加到页面
@@ -287,33 +288,48 @@ class SessionManager {
287
288
  * 连接到已运行的浏览器
288
289
  */
289
290
  async connect(options) {
291
+ const { host = '127.0.0.1', port, timeout = DEFAULT_TIMEOUT, stealth = 'safe' } = options;
292
+ const scope = this.requestContext?.();
293
+ const signal = scope?.signal;
294
+ const deadline = Math.min(Date.now() + timeout, scope?.deadline ?? Infinity);
295
+ const remaining = () => {
296
+ signal?.throwIfAborted();
297
+ return remainingNavigationTimeout(deadline);
298
+ };
299
+ remaining();
290
300
  return this.withLock(async () => {
291
- const { host = '127.0.0.1', port, timeout = DEFAULT_TIMEOUT, stealth = 'safe' } = options;
292
- // 关闭现有会话
293
- this.resetState();
294
- // 保存 stealth 模式
295
- this.stealthMode = stealth;
296
- // 获取 WebSocket 端点
297
- const endpoint = await getBrowserWSEndpoint(host, port);
298
- // 连接 CDP
299
- this.cdp = new CDPClient(() => this.requestContext?.());
300
- await this.cdp.connect(endpoint, timeout);
301
- this.connectedPort = port;
302
- // 获取第一个页面
303
- const targets = await getTargets(host, port);
304
- const pageTarget = targets.find((t) => t.type === 'page');
301
+ const endpoint = await getBrowserWSEndpoint(host, port, remaining(), signal);
302
+ const targets = await getTargets(host, port, remaining(), signal);
303
+ remaining();
304
+ const reused = this.cdp?.isConnected === true && this.cdp.endpoint === endpoint;
305
+ const pageTarget = (reused
306
+ ? targets.find((target) => target.id === this.currentTargetId && target.type === 'page')
307
+ : undefined) ?? targets.find((target) => target.type === 'page');
305
308
  if (!pageTarget) {
306
309
  throw new Error('未找到页面');
307
310
  }
308
- // 附加到页面
309
- await this.attachToTargetInternal(pageTarget.id);
311
+ const stealthChanged = this.stealthMode !== stealth;
312
+ if (!reused) {
313
+ this.resetState();
314
+ this.cdp = new CDPClient(() => this.requestContext?.());
315
+ await this.cdp.connect(endpoint, remaining());
316
+ this.connectedPort = port;
317
+ }
318
+ this.stealthMode = stealth;
319
+ if (reused && this.currentTargetId === pageTarget.id && this.sessionId && stealthChanged) {
320
+ await this.initSession(deadline);
321
+ }
322
+ else {
323
+ await this.attachToTargetInternal(pageTarget.id, deadline);
324
+ }
325
+ remaining();
310
326
  return {
311
327
  targetId: pageTarget.id,
312
328
  type: pageTarget.type,
313
329
  url: pageTarget.url,
314
330
  title: pageTarget.title,
315
331
  };
316
- });
332
+ }, deadline);
317
333
  }
318
334
  /**
319
335
  * 列出所有可用页面
@@ -485,6 +501,7 @@ class SessionManager {
485
501
  const frame = this.frameScopes.get(this.selectedFrame);
486
502
  return new Locator(this.cdp, target, frame?.sessionId ?? this.sessionId, {
487
503
  contextId: frame?.contextId,
504
+ frameId: frame?.frameId,
488
505
  localPoint: frame
489
506
  ? async (timeout) => {
490
507
  const deadline = Date.now() + timeout;
@@ -648,33 +665,46 @@ class SessionManager {
648
665
  // 归一化换行:\r\n 和 \r 都视作单个 \n
649
666
  const normalized = text.replace(/\r\n?/g, '\n');
650
667
  for (const char of normalized) {
651
- if (char === '\n') {
652
- // Enter 键:char 通道不接受 \n,必须分发 keyDown + char('\r') + keyUp
653
- const enterParams = {
668
+ const keyParams = char === '\n'
669
+ ? {
654
670
  key: 'Enter',
655
671
  code: 'Enter',
656
672
  windowsVirtualKeyCode: 13,
657
673
  nativeVirtualKeyCode: 13,
658
674
  modifiers: this.modifiers,
659
- };
660
- const keyDownTimeout = remainingTimeout();
661
- try {
662
- await this.send('Input.dispatchKeyEvent', { type: 'keyDown', ...enterParams }, keyDownTimeout);
663
- await this.send('Input.dispatchKeyEvent', { type: 'char', text: '\r', ...enterParams }, remainingTimeout());
664
675
  }
665
- finally {
666
- await this.send('Input.dispatchKeyEvent', { type: 'keyUp', ...enterParams }, Math.max(1, deadline - Date.now()));
676
+ : { modifiers: this.modifiers, text: char };
677
+ const keyDownTimeout = remainingTimeout();
678
+ let failed = false;
679
+ let failure;
680
+ try {
681
+ await this.send('Input.dispatchKeyEvent', { type: 'keyDown', ...keyParams }, keyDownTimeout);
682
+ if (char === '\n') {
683
+ // Enter 键:char 通道不接受 \n,必须分发 keyDown + char('\r') + keyUp
684
+ await this.send('Input.dispatchKeyEvent', { type: 'char', text: '\r', ...keyParams }, remainingTimeout());
667
685
  }
668
686
  }
669
- else {
670
- const keyDownTimeout = remainingTimeout();
687
+ catch (error) {
688
+ failed = true;
689
+ failure = error;
690
+ }
691
+ finally {
671
692
  try {
672
- await this.send('Input.dispatchKeyEvent', { type: 'keyDown', modifiers: this.modifiers, text: char }, keyDownTimeout);
693
+ await this.send('Input.dispatchKeyEvent', { type: 'keyUp', ...keyParams }, Math.max(1, deadline - Date.now()), undefined, true);
673
694
  }
674
- finally {
675
- await this.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: this.modifiers, text: char }, Math.max(1, deadline - Date.now()));
695
+ catch (error) {
696
+ if (failed) {
697
+ console.warn('[MCP] Typing key release failed after input error:', error);
698
+ }
699
+ else {
700
+ failed = true;
701
+ failure = error;
702
+ }
676
703
  }
677
704
  }
705
+ if (failed) {
706
+ throw failure;
707
+ }
678
708
  if (delay > 0) {
679
709
  await new Promise((r) => setTimeout(r, Math.min(delay, remainingTimeout())));
680
710
  }
@@ -922,7 +952,8 @@ class SessionManager {
922
952
  ...(value !== undefined ? {value: value} : {}),
923
953
  selector: selectorFor(el),
924
954
  visible: visible,
925
- disabled: Boolean(el.disabled) || el.getAttribute('aria-disabled') === 'true',
955
+ disabled: el.matches(':disabled') || Boolean(el.disabled) ||
956
+ el.getAttribute('aria-disabled') === 'true',
926
957
  bounds: {x: rect.x, y: rect.y, width: rect.width, height: rect.height},
927
958
  covered: Boolean(visible && top && top !== el && !el.contains(top)),
928
959
  frameId: 0
@@ -930,10 +961,15 @@ class SessionManager {
930
961
  });
931
962
  }`;
932
963
  if (target && 'x' in target && 'y' in target) {
933
- const elements = await this.evaluate(`(() => {
934
- const root = globalThis.__mcpDomHelpers.deepElementFromPoint(${JSON.stringify(target.x)}, ${JSON.stringify(target.y)});
935
- return root ? (${script}).call(root) : null;
936
- })()`, undefined, timeout);
964
+ const elements = await this.evaluate('(() => {\n const root = ' +
965
+ 'globalThis.__mcpDomHelpers.deepElementFromPoin' +
966
+ 't(' +
967
+ `${JSON.stringify(target.x)}` +
968
+ ', ' +
969
+ `${JSON.stringify(target.y)}` +
970
+ ');\n return root ? (' +
971
+ `${script}` +
972
+ ').call(root) : null;\n })()', undefined, timeout);
937
973
  if (!elements) {
938
974
  throw new ElementNotFoundError(target, timeout ?? DEFAULT_TIMEOUT);
939
975
  }
@@ -1449,35 +1485,50 @@ class SessionManager {
1449
1485
  const anchor = await this.cdp.send('Runtime.evaluate', {
1450
1486
  contextId: owner.contextId,
1451
1487
  returnByValue: false,
1452
- expression: `(() => {
1453
- const walk=document.createTreeWalker(document,NodeFilter.SHOW_ELEMENT);
1454
- for(let el=walk.nextNode();el;el=walk.nextNode()) {
1455
- const r=el.getBoundingClientRect();
1456
- if (!(r.width>0 && r.height>0) || el.getClientRects().length!==1) continue;
1457
- let aligned=true;
1458
- for(let p=el;p;p=p.parentElement) {
1459
- const s=getComputedStyle(p),m=new DOMMatrix(s.transform==='none'?undefined:s.transform);
1460
- if(!m.is2D || Math.abs(m.b)>1e-12 || Math.abs(m.c)>1e-12 || m.a<=0 || m.d<=0 ||
1461
- (s.rotate&&s.rotate!=='none'&&!/^(?:[xyz] )?0deg$/.test(s.rotate)) ||
1462
- (s.scale&&s.scale!=='none'&&s.scale.split(/\\s+/).some(value=>Number(value)<=0))) {aligned=false;break}
1463
- }
1464
- if(aligned)return el;
1465
- }
1466
- return null;
1467
- })()`,
1488
+ expression: '(() => {\n const ' +
1489
+ 'walk=document.createTreeWalker(document,' +
1490
+ 'NodeFilter.SHOW_ELEMENT);\n ' +
1491
+ ' for(let el=walk.nextNode();el;' +
1492
+ 'el=walk.nextNode()) {\n ' +
1493
+ ' const r=el.getBoundingClientRect();\n ' +
1494
+ ' if (!(r.width>0 ' +
1495
+ '&& r.height>0) || el.getClientRects().length!=' +
1496
+ '=1) continue;\n ' +
1497
+ 'let aligned=true;\n ' +
1498
+ ' for(let p=el;p;p=p.parentElement) {\n ' +
1499
+ ' const ' +
1500
+ 's=getComputedStyle(p),m=new ' +
1501
+ "DOMMatrix(s.transform==='none'?undefined:s.tra" +
1502
+ 'nsform);\n ' +
1503
+ 'if(!m.is2D || Math.abs(m.b)>1e-12 || ' +
1504
+ 'Math.abs(m.c)>1e-12 || m.a<=0 || m.d<=0 ||\n ' +
1505
+ ' ' +
1506
+ "(s.rotate&&s.rotate!=='none'&&!/^(?:[xyz] " +
1507
+ ')?0deg$/.test(s.rotate)) ||\n ' +
1508
+ " (s.scale&&s.scale!=='non" +
1509
+ "e'&&s.scale.split(/\\s+/).some(value=>" +
1510
+ 'Number(value)<=0))) {aligned=false;break}\n ' +
1511
+ ' }\n ' +
1512
+ ' if(aligned)return el;\n ' +
1513
+ ' }\n ' +
1514
+ ' return null;\n })()',
1468
1515
  }, owner.sessionId, remaining());
1469
1516
  const objectId = anchor.result.objectId;
1470
1517
  if (!objectId) {
1518
+ // noinspection ExceptionCaughtLocallyJS -- 外层统一返回 frame 几何错误
1471
1519
  throw new Error('Frame zoom viewport anchor is unavailable');
1472
1520
  }
1473
1521
  try {
1474
1522
  const { result: { value: r }, } = await this.cdp.send('Runtime.callFunctionOn', {
1475
1523
  objectId,
1476
- functionDeclaration: 'function(){const r=this.getBoundingClientRect();return {x:r.x,y:r.y,width:r.width,height:r.height}}',
1524
+ functionDeclaration: 'function(){const r=this.getBoundingClientRect();' +
1525
+ 'return {x:r.x,y:r.y,width:r.width,' +
1526
+ 'height:r.height}}',
1477
1527
  returnByValue: true,
1478
1528
  }, owner.sessionId, remaining());
1479
1529
  const { model: { border: q }, } = await this.cdp.send('DOM.getBoxModel', { objectId }, owner.sessionId, remaining());
1480
1530
  if (!(r.width > 0 && r.height > 0) || q.length !== 8 || !q.every(Number.isFinite)) {
1531
+ // noinspection ExceptionCaughtLocallyJS -- 统一返回几何错误并释放临时对象
1481
1532
  throw new Error('Frame zoom viewport anchor is invalid');
1482
1533
  }
1483
1534
  const [a, b, c, d] = [
@@ -1490,6 +1541,7 @@ class SessionManager {
1490
1541
  if (Math.abs(determinant) < 1e-12 ||
1491
1542
  Math.abs(q[4] - q[2] - q[6] + q[0]) > 0.001 ||
1492
1543
  Math.abs(q[5] - q[3] - q[7] + q[1]) > 0.001) {
1544
+ // noinspection ExceptionCaughtLocallyJS -- 统一返回几何错误并释放临时对象
1493
1545
  throw new Error('Frame zoom viewport anchor is singular or non-affine');
1494
1546
  }
1495
1547
  const dx = mapped.x - q[0], dy = mapped.y - q[1];
@@ -1500,10 +1552,12 @@ class SessionManager {
1500
1552
  }
1501
1553
  }
1502
1554
  if (!(this.contexts.get(owner.sessionId) ?? []).some((c) => c.id === owner.contextId && c.frameId === owner.frameId)) {
1555
+ // noinspection ExceptionCaughtLocallyJS -- 外层统一返回 frame 身份变化的几何错误
1503
1556
  throw new Error('Frame document identity changed before input');
1504
1557
  }
1505
1558
  const { node } = await this.cdp.send('DOM.describeNode', { backendNodeId: owner.backendNodeId }, owner.parentSessionId, remaining());
1506
1559
  if (node.frameId !== owner.frameId) {
1560
+ // noinspection ExceptionCaughtLocallyJS -- 外层统一返回 frame 身份变化的几何错误
1507
1561
  throw new Error('Frame owner identity changed before input');
1508
1562
  }
1509
1563
  const { model } = await this.cdp.send('DOM.getBoxModel', { backendNodeId: owner.backendNodeId }, owner.parentSessionId, remaining());
@@ -1518,6 +1572,7 @@ class SessionManager {
1518
1572
  !(width > 0 && height > 0) ||
1519
1573
  q.length !== 8 ||
1520
1574
  !q.every(Number.isFinite)) {
1575
+ // noinspection ExceptionCaughtLocallyJS -- 外层统一返回 frame 几何错误
1521
1576
  throw new Error('Frame content quad or viewport is unavailable');
1522
1577
  }
1523
1578
  const [a, b, c, d, e, f] = [
@@ -1531,6 +1586,7 @@ class SessionManager {
1531
1586
  if (Math.abs(a * d - b * c) < 1e-12 ||
1532
1587
  Math.abs(q[4] - q[2] - q[6] + q[0]) > 0.001 ||
1533
1588
  Math.abs(q[5] - q[3] - q[7] + q[1]) > 0.001) {
1589
+ // noinspection ExceptionCaughtLocallyJS -- 外层统一返回 frame 几何错误
1534
1590
  throw new Error('Frame content quad is singular or non-affine');
1535
1591
  }
1536
1592
  mapped = { x: a * mapped.x + c * mapped.y + e, y: b * mapped.x + d * mapped.y + f };
@@ -1738,10 +1794,15 @@ class SessionManager {
1738
1794
  async deleteCookie(url, name, scope, exact) {
1739
1795
  this.ensureSession();
1740
1796
  const contextId = await this.cookieContext(scope);
1741
- const target = scope?.targetId ?? this.currentTargetId;
1797
+ let target = scope?.targetId ?? this.currentTargetId;
1742
1798
  const { targetInfo } = await this.sendBrowserCommand('Target.getTargetInfo', { targetId: target });
1743
1799
  if (scope?.browserContextId !== undefined && contextId !== targetInfo.browserContextId) {
1744
- throw new DriverCapabilityError('Cookie deletion requires a target in the selected browser context');
1800
+ const { targetInfos } = await this.sendBrowserCommand('Target.getTargets');
1801
+ const selected = targetInfos.find((candidate) => candidate.type === 'page' && candidate.browserContextId === contextId);
1802
+ if (!selected) {
1803
+ throw new DriverCapabilityError('Cookie deletion requires a target in the selected browser context');
1804
+ }
1805
+ target = selected.targetId;
1745
1806
  }
1746
1807
  const cdp = this.cdp;
1747
1808
  let sid = this.targetSessions.get(target);
@@ -1789,7 +1850,12 @@ class SessionManager {
1789
1850
  throw new Error('clearCookies requires url or domain');
1790
1851
  }
1791
1852
  this.ensureSession();
1792
- const scope = { ...filter, targetId: filter.targetId ?? this.currentTargetId };
1853
+ const scope = {
1854
+ ...filter,
1855
+ ...(filter.targetId === undefined && filter.browserContextId === undefined
1856
+ ? { targetId: this.currentTargetId }
1857
+ : {}),
1858
+ };
1793
1859
  const cookies = await this.getCookies(scope);
1794
1860
  if (cookies.some((cookie) => 'partitionKeyOpaque' in cookie && !cookie.partitionKey)) {
1795
1861
  throw new DriverCapabilityError('Cookie 分区身份不可序列化,未执行清除');
@@ -1852,17 +1918,20 @@ class SessionManager {
1852
1918
  }
1853
1919
  catch (error) {
1854
1920
  if (!acknowledged) {
1921
+ // noinspection ExceptionCaughtLocallyJS -- 外层按 delete 阶段保留实际清除进度
1855
1922
  throw error;
1856
1923
  }
1857
1924
  cleanupFailure = { error };
1858
1925
  }
1859
1926
  phase = 'verification';
1860
1927
  if ((await this.getCookies(identityFilter)).some(matches)) {
1928
+ // noinspection ExceptionCaughtLocallyJS -- 外层按 verification 阶段记录仍存在的 Cookie
1861
1929
  throw new StructuredToolError('COOKIE_STILL_PRESENT', '浏览器确认请求后仍存在相同身份的 Cookie', '读取该 Cookie 核对实际状态,勿自动重放清除', {});
1862
1930
  }
1863
1931
  ++progress.count;
1864
1932
  if (cleanupFailure) {
1865
1933
  phase = 'cleanup';
1934
+ // noinspection ExceptionCaughtLocallyJS -- 外层同时保留已完成清除与清理失败
1866
1935
  throw cleanupFailure.error;
1867
1936
  }
1868
1937
  }
@@ -2184,7 +2253,7 @@ class SessionManager {
2184
2253
  * 多步操作(type 循环、fullPage 截图等)的 await 间隙可能被 close() 打断,
2185
2254
  * ensureSession() 确保在当前 tick 内 this.cdp 非空
2186
2255
  */
2187
- async send(method, params, timeout, dispatchedAction) {
2256
+ async send(method, params, timeout, dispatchedAction, cleanup = false) {
2188
2257
  const deadline = timeout === undefined ? undefined : Date.now() + timeout;
2189
2258
  this.ensureSession();
2190
2259
  const mutation = method === 'Page.navigate' ||
@@ -2219,7 +2288,7 @@ class SessionManager {
2219
2288
  const scoped = frame && (/^(?:Runtime|DOM|Accessibility)\./.test(method) || method === 'Input.dispatchKeyEvent');
2220
2289
  const sessionId = scoped ? frame.sessionId : this.sessionId;
2221
2290
  const nativeParams = scoped && method === 'Runtime.evaluate' ? { ...params, contextId: frame.contextId } : params;
2222
- const operation = this.cdp.send(method, nativeParams, sessionId, remaining, false, dispatchedAction);
2291
+ const operation = this.cdp.send(method, nativeParams, sessionId, remaining, cleanup, dispatchedAction);
2223
2292
  return blocking
2224
2293
  ? this.ensureEventController(this.currentTargetId, this.sessionId)
2225
2294
  .race(operation)
@@ -2249,6 +2318,7 @@ class SessionManager {
2249
2318
  const { object } = await this.cdp.send('DOM.resolveNode', { backendNodeId: owner.backendNodeId }, owner.parentSessionId, remainingNavigationTimeout(deadline));
2250
2319
  objectId = object.objectId;
2251
2320
  if (!objectId) {
2321
+ // noinspection ExceptionCaughtLocallyJS -- 外层统一返回 frame 几何错误
2252
2322
  throw new Error('Frame owner object is unavailable');
2253
2323
  }
2254
2324
  const { result, exceptionDetails } = await this.cdp.send('Runtime.callFunctionOn', { objectId, functionDeclaration: 'function(){return this.currentCSSZoom ?? 1}', returnByValue: true }, owner.parentSessionId, remainingNavigationTimeout(deadline));
@@ -2256,6 +2326,7 @@ class SessionManager {
2256
2326
  typeof result.value !== 'number' ||
2257
2327
  !Number.isFinite(result.value) ||
2258
2328
  result.value <= 0) {
2329
+ // noinspection ExceptionCaughtLocallyJS -- 统一返回几何错误,finally 释放临时对象
2259
2330
  throw new Error('Frame owner CSS zoom is unavailable');
2260
2331
  }
2261
2332
  return result.value;
@@ -2620,6 +2691,7 @@ class SessionManager {
2620
2691
  const logs = this.targetLogs.get(targetId);
2621
2692
  this.consoleLogs = logs?.console ?? [];
2622
2693
  this.networkRequests = logs?.network ?? [];
2694
+ this.requestMap = logs?.requests ?? new Map();
2623
2695
  // 初始化会话
2624
2696
  await this.initSession(deadline);
2625
2697
  }
@@ -2663,11 +2735,15 @@ class SessionManager {
2663
2735
  }
2664
2736
  clearAttachedTargetState() {
2665
2737
  if (this.currentTargetId) {
2666
- this.targetLogs.set(this.currentTargetId, { console: this.consoleLogs, network: this.networkRequests });
2738
+ this.targetLogs.set(this.currentTargetId, {
2739
+ console: this.consoleLogs,
2740
+ network: this.networkRequests,
2741
+ requests: this.requestMap,
2742
+ });
2667
2743
  }
2668
2744
  this.consoleLogs = [];
2669
2745
  this.networkRequests = [];
2670
- this.requestMap.clear();
2746
+ this.requestMap = new Map();
2671
2747
  this.challengeRequired = false;
2672
2748
  this.runtimeEnabled = false;
2673
2749
  this.mainFrameId = null;
@@ -2678,6 +2754,13 @@ class SessionManager {
2678
2754
  this.currentTargetId = null;
2679
2755
  this.state = null;
2680
2756
  }
2757
+ networkState(eventSessionId) {
2758
+ if (this.isCurrentSessionEvent(eventSessionId)) {
2759
+ return { network: this.networkRequests, requests: this.requestMap };
2760
+ }
2761
+ const targetId = [...this.targetSessions].find(([, sid]) => sid === eventSessionId)?.[0];
2762
+ return targetId ? this.targetLogs.get(targetId) : undefined;
2763
+ }
2681
2764
  isCurrentSessionEvent(eventSessionId) {
2682
2765
  return this.sessionId !== null && eventSessionId === this.sessionId;
2683
2766
  }
@@ -2917,6 +3000,7 @@ class SessionManager {
2917
3000
  if (this.currentTargetId === targetId) {
2918
3001
  this.clearAttachedTargetState();
2919
3002
  }
3003
+ this.targetLogs.delete(targetId);
2920
3004
  if (controller) {
2921
3005
  void controller
2922
3006
  .dispose('native target detached')
@@ -2990,11 +3074,12 @@ class SessionManager {
2990
3074
  });
2991
3075
  // 网络请求
2992
3076
  this.cdp.onEvent('Network.requestWillBeSent', (params, eventSessionId) => {
2993
- if (!this.isCurrentSessionEvent(eventSessionId)) {
3077
+ const state = this.networkState(eventSessionId);
3078
+ if (!state) {
2994
3079
  return;
2995
3080
  }
2996
3081
  const p = params;
2997
- this.requestMap.set(p.requestId, {
3082
+ state.requests.set(p.requestId, {
2998
3083
  url: p.request.url,
2999
3084
  method: p.request.method,
3000
3085
  type: p.type,
@@ -3005,14 +3090,17 @@ class SessionManager {
3005
3090
  });
3006
3091
  });
3007
3092
  this.cdp.onEvent('Network.responseReceived', (params, eventSessionId) => {
3008
- if (!this.isCurrentSessionEvent(eventSessionId)) {
3093
+ const state = this.networkState(eventSessionId);
3094
+ if (!state) {
3009
3095
  return;
3010
3096
  }
3011
3097
  const p = params;
3012
- const request = this.requestMap.get(p.requestId);
3098
+ const request = state.requests.get(p.requestId);
3013
3099
  if (request) {
3014
3100
  const challenge = isCloudflareChallenge(p.response.headers);
3015
- if (request.type.toLowerCase() === 'document' && request.frameId === this.mainFrameId) {
3101
+ if (this.isCurrentSessionEvent(eventSessionId) &&
3102
+ request.type.toLowerCase() === 'document' &&
3103
+ request.frameId === this.mainFrameId) {
3016
3104
  // 仅新的主文档响应可以解除已知 Challenge,清空日志不能解除该状态
3017
3105
  this.challengeRequired = challenge;
3018
3106
  }
@@ -3022,27 +3110,28 @@ class SessionManager {
3022
3110
  });
3023
3111
  // 网络请求失败时写入日志再清理 requestMap,防止 diagnostics 丢失失败请求
3024
3112
  const finalizeRequest = (params, eventSessionId) => {
3025
- if (!this.isCurrentSessionEvent(eventSessionId)) {
3113
+ const state = this.networkState(eventSessionId);
3114
+ if (!state) {
3026
3115
  return;
3027
3116
  }
3028
3117
  const p = params;
3029
- const request = this.requestMap.get(p.requestId);
3118
+ const request = state.requests.get(p.requestId);
3030
3119
  if (request) {
3031
3120
  const { _monotonic, ...requestData } = request;
3032
3121
  delete requestData.frameId;
3033
3122
  delete requestData.loaderId;
3034
- this.networkRequests.push({
3123
+ state.network.push({
3035
3124
  sequence: ++this.nextNetworkRequestSequence,
3036
3125
  ...requestData,
3037
3126
  type: p.type ?? requestData.type,
3038
3127
  errorText: p.errorText,
3039
3128
  duration: Math.round((p.timestamp - _monotonic) * 1000),
3040
3129
  });
3041
- if (this.networkRequests.length > SessionManager.MAX_LOG_ENTRIES) {
3042
- this.networkRequests.splice(0, this.networkRequests.length - 800);
3130
+ if (state.network.length > SessionManager.MAX_LOG_ENTRIES) {
3131
+ state.network.splice(0, state.network.length - 800);
3043
3132
  }
3044
3133
  }
3045
- this.requestMap.delete(p.requestId);
3134
+ state.requests.delete(p.requestId);
3046
3135
  };
3047
3136
  this.cdp.onEvent('Network.loadingFinished', finalizeRequest);
3048
3137
  this.cdp.onEvent('Network.loadingFailed', finalizeRequest);