@pyrokine/mcp-chrome 3.0.1 → 3.1.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 (144) hide show
  1. package/README.md +678 -341
  2. package/README_zh.md +694 -291
  3. package/dist/cdp/client.d.ts +7 -3
  4. package/dist/cdp/client.d.ts.map +1 -1
  5. package/dist/cdp/client.js +252 -63
  6. package/dist/cdp/client.js.map +1 -1
  7. package/dist/cdp/launcher.d.ts +1 -1
  8. package/dist/cdp/launcher.d.ts.map +1 -1
  9. package/dist/cdp/launcher.js +33 -12
  10. package/dist/cdp/launcher.js.map +1 -1
  11. package/dist/core/auto-wait.d.ts.map +1 -1
  12. package/dist/core/auto-wait.js +88 -52
  13. package/dist/core/auto-wait.js.map +1 -1
  14. package/dist/core/browser-driver.d.ts +72 -15
  15. package/dist/core/browser-driver.d.ts.map +1 -1
  16. package/dist/core/browser-driver.js.map +1 -1
  17. package/dist/core/browser-event-schema.d.ts +287 -0
  18. package/dist/core/browser-event-schema.d.ts.map +1 -0
  19. package/dist/core/browser-event-schema.js +104 -0
  20. package/dist/core/browser-event-schema.js.map +1 -0
  21. package/dist/core/browser-events.d.ts +99 -0
  22. package/dist/core/browser-events.d.ts.map +1 -0
  23. package/dist/core/browser-events.js +1312 -0
  24. package/dist/core/browser-events.js.map +1 -0
  25. package/dist/core/challenge-page.d.ts +39 -0
  26. package/dist/core/challenge-page.d.ts.map +1 -0
  27. package/dist/core/challenge-page.js +226 -0
  28. package/dist/core/challenge-page.js.map +1 -0
  29. package/dist/core/dom-helpers.d.ts +28 -0
  30. package/dist/core/dom-helpers.d.ts.map +1 -0
  31. package/dist/core/dom-helpers.js +311 -0
  32. package/dist/core/dom-helpers.js.map +1 -0
  33. package/dist/core/errors.d.ts +4 -0
  34. package/dist/core/errors.d.ts.map +1 -1
  35. package/dist/core/errors.js +51 -7
  36. package/dist/core/errors.js.map +1 -1
  37. package/dist/core/file-upload.d.ts +22 -0
  38. package/dist/core/file-upload.d.ts.map +1 -0
  39. package/dist/core/file-upload.js +194 -0
  40. package/dist/core/file-upload.js.map +1 -0
  41. package/dist/core/locator.d.ts +10 -2
  42. package/dist/core/locator.d.ts.map +1 -1
  43. package/dist/core/locator.js +121 -200
  44. package/dist/core/locator.js.map +1 -1
  45. package/dist/core/os-mouse.d.ts +11 -0
  46. package/dist/core/os-mouse.d.ts.map +1 -1
  47. package/dist/core/os-mouse.js +102 -29
  48. package/dist/core/os-mouse.js.map +1 -1
  49. package/dist/core/retry.d.ts.map +1 -1
  50. package/dist/core/retry.js +4 -1
  51. package/dist/core/retry.js.map +1 -1
  52. package/dist/core/session.d.ts +61 -12
  53. package/dist/core/session.d.ts.map +1 -1
  54. package/dist/core/session.js +1040 -259
  55. package/dist/core/session.js.map +1 -1
  56. package/dist/core/types.d.ts +5 -1
  57. package/dist/core/types.d.ts.map +1 -1
  58. package/dist/core/types.js +16 -1
  59. package/dist/core/types.js.map +1 -1
  60. package/dist/core/unified-session.d.ts +41 -35
  61. package/dist/core/unified-session.d.ts.map +1 -1
  62. package/dist/core/unified-session.js +872 -263
  63. package/dist/core/unified-session.js.map +1 -1
  64. package/dist/core/utils.d.ts +5 -4
  65. package/dist/core/utils.d.ts.map +1 -1
  66. package/dist/core/utils.js +73 -18
  67. package/dist/core/utils.js.map +1 -1
  68. package/dist/extension/bridge.d.ts +48 -17
  69. package/dist/extension/bridge.d.ts.map +1 -1
  70. package/dist/extension/bridge.js +239 -37
  71. package/dist/extension/bridge.js.map +1 -1
  72. package/dist/extension/http-server.d.ts +7 -2
  73. package/dist/extension/http-server.d.ts.map +1 -1
  74. package/dist/extension/http-server.js +211 -49
  75. package/dist/extension/http-server.js.map +1 -1
  76. package/dist/index.js +14 -1
  77. package/dist/index.js.map +1 -1
  78. package/dist/tools/browse.d.ts.map +1 -1
  79. package/dist/tools/browse.js +56 -28
  80. package/dist/tools/browse.js.map +1 -1
  81. package/dist/tools/browser-event-output.d.ts +7 -0
  82. package/dist/tools/browser-event-output.d.ts.map +1 -0
  83. package/dist/tools/browser-event-output.js +19 -0
  84. package/dist/tools/browser-event-output.js.map +1 -0
  85. package/dist/tools/challenge.d.ts +17 -5
  86. package/dist/tools/challenge.d.ts.map +1 -1
  87. package/dist/tools/challenge.js +110 -189
  88. package/dist/tools/challenge.js.map +1 -1
  89. package/dist/tools/cookies.d.ts.map +1 -1
  90. package/dist/tools/cookies.js +33 -8
  91. package/dist/tools/cookies.js.map +1 -1
  92. package/dist/tools/diagnostics.d.ts.map +1 -1
  93. package/dist/tools/diagnostics.js +14 -0
  94. package/dist/tools/diagnostics.js.map +1 -1
  95. package/dist/tools/evaluate.d.ts +6 -5
  96. package/dist/tools/evaluate.d.ts.map +1 -1
  97. package/dist/tools/evaluate.js +92 -52
  98. package/dist/tools/evaluate.js.map +1 -1
  99. package/dist/tools/extract.d.ts.map +1 -1
  100. package/dist/tools/extract.js +149 -103
  101. package/dist/tools/extract.js.map +1 -1
  102. package/dist/tools/input.d.ts.map +1 -1
  103. package/dist/tools/input.js +555 -229
  104. package/dist/tools/input.js.map +1 -1
  105. package/dist/tools/logs.d.ts.map +1 -1
  106. package/dist/tools/logs.js +50 -11
  107. package/dist/tools/logs.js.map +1 -1
  108. package/dist/tools/manage.d.ts.map +1 -1
  109. package/dist/tools/manage.js +111 -16
  110. package/dist/tools/manage.js.map +1 -1
  111. package/dist/tools/network-sanitizer.d.ts +1 -0
  112. package/dist/tools/network-sanitizer.d.ts.map +1 -1
  113. package/dist/tools/network-sanitizer.js +30 -1
  114. package/dist/tools/network-sanitizer.js.map +1 -1
  115. package/dist/tools/page-context.d.ts +4 -3
  116. package/dist/tools/page-context.d.ts.map +1 -1
  117. package/dist/tools/page-context.js +56 -14
  118. package/dist/tools/page-context.js.map +1 -1
  119. package/dist/tools/post-condition.d.ts +1 -1
  120. package/dist/tools/post-condition.d.ts.map +1 -1
  121. package/dist/tools/post-condition.js +136 -44
  122. package/dist/tools/post-condition.js.map +1 -1
  123. package/dist/tools/schema.d.ts +7 -4
  124. package/dist/tools/schema.d.ts.map +1 -1
  125. package/dist/tools/schema.js +32 -122
  126. package/dist/tools/schema.js.map +1 -1
  127. package/dist/tools/target-diagnostics.d.ts +3 -3
  128. package/dist/tools/target-diagnostics.d.ts.map +1 -1
  129. package/dist/tools/target-diagnostics.js +17 -7
  130. package/dist/tools/target-diagnostics.js.map +1 -1
  131. package/dist/tools/wait.d.ts.map +1 -1
  132. package/dist/tools/wait.js +94 -40
  133. package/dist/tools/wait.js.map +1 -1
  134. package/extension/dist/assets/{content.ts-qe6IB5DK.js → content.ts-BAMOcF3R.js} +1 -1
  135. package/extension/dist/assets/{content.ts-loader-DUWbDHRS.js → content.ts-loader-4F9a1EWZ.js} +1 -1
  136. package/extension/dist/assets/index.ts-B79g2ikq.js +19820 -0
  137. package/extension/dist/assets/{page-scripts-D508WLkW.js → page-scripts-CSxn58h1.js} +257 -366
  138. package/extension/dist/assets/{popup.html-B-eVq48O.js → popup.html-DwwHo00N.js} +2 -2
  139. package/extension/dist/manifest.json +4 -4
  140. package/extension/dist/service-worker-loader.js +1 -1
  141. package/extension/dist/src/popup/popup.html +3 -3
  142. package/package.json +8 -6
  143. package/scripts/start-chrome.ps1 +9 -1
  144. package/extension/dist/assets/index.ts-D7_LCUoV.js +0 -9319
@@ -5,13 +5,15 @@
5
5
  * 使用 HTTP + WebSocket 实现
6
6
  */
7
7
  import { DriverCapabilityError, } from '../core/browser-driver.js';
8
- import { creationError, StructuredToolError, TargetNotFoundError } from '../core/errors.js';
9
- import { remainingNavigationTimeout } from '../core/utils.js';
8
+ import { creationError, setErrorPageContext, setErrorSource, StructuredToolError, TargetNotFoundError, } from '../core/errors.js';
10
9
  import { DEFAULT_TIMEOUT } from '../core/types.js';
10
+ import { remainingNavigationTimeout } from '../core/utils.js';
11
+ import { eventRefTarget } from '../core/browser-events.js';
11
12
  import { ExtensionHttpServer } from './http-server.js';
12
13
  /** RPC 传输余量(毫秒):给网络往返和 Extension 处理留出的额外时间 */
13
14
  const RPC_MARGIN = 5000;
14
15
  const CONDITIONAL_ACTIONS = new Set([
16
+ 'tabs_metadata',
15
17
  'tabs_close',
16
18
  'tabs_activate',
17
19
  'tabs_activate_managed',
@@ -35,6 +37,7 @@ const CONDITIONAL_ACTIONS = new Set([
35
37
  'evaluate',
36
38
  'evaluate_in_frame',
37
39
  'debugger_send',
40
+ 'keyboard_focus',
38
41
  'input_key',
39
42
  'input_mouse',
40
43
  'input_touch',
@@ -46,18 +49,24 @@ const CONDITIONAL_ACTIONS = new Set([
46
49
  'stealth_inject',
47
50
  ]);
48
51
  export class ExtensionBridge {
52
+ options;
49
53
  httpServer;
50
54
  currentTabId = null;
55
+ browserEventTargets = new Set();
51
56
  currentFrameId = 0;
57
+ currentFrameDocumentId;
52
58
  state = null;
53
59
  pendingPageCondition = null;
54
60
  constructor(options = {}) {
61
+ this.options = options;
55
62
  this.httpServer = new ExtensionHttpServer({
56
63
  port: options.port,
57
64
  autoPort: true,
65
+ requestContext: options.requestContext,
58
66
  });
59
67
  this.httpServer.setActionConditionProvider((action, params) => {
60
- const condition = this.pendingPageCondition;
68
+ const context = this.options.requestContext?.();
69
+ const condition = context ? context.pendingPageCondition : this.pendingPageCondition;
61
70
  if (!condition || !CONDITIONAL_ACTIONS.has(action)) {
62
71
  return undefined;
63
72
  }
@@ -65,7 +74,12 @@ export class ExtensionBridge {
65
74
  if (tabId === undefined || String(tabId) !== condition.targetId) {
66
75
  throw new DriverCapabilityError('条件动作的目标与请求目标不一致,未执行动作');
67
76
  }
68
- this.pendingPageCondition = null;
77
+ if (context) {
78
+ context.pendingPageCondition = null;
79
+ }
80
+ else {
81
+ this.pendingPageCondition = null;
82
+ }
69
83
  return {
70
84
  ...(condition.expectedUrl !== undefined ? { expectedUrl: condition.expectedUrl } : {}),
71
85
  ...(condition.expectedRevision !== undefined ? { expectedRevision: condition.expectedRevision } : {}),
@@ -86,7 +100,7 @@ export class ExtensionBridge {
86
100
  * @param timeout 超时时间(毫秒),0 表示无限等待(默认)
87
101
  */
88
102
  async waitForConnection(timeout = 0) {
89
- return this.httpServer.waitForConnection(timeout);
103
+ return this.httpServer.waitForConnection(timeout, this.options.requestContext?.()?.signal);
90
104
  }
91
105
  getPort() {
92
106
  return this.httpServer.getPort();
@@ -95,11 +109,20 @@ export class ExtensionBridge {
95
109
  return this.httpServer.getConnectionInfo();
96
110
  }
97
111
  // ==================== Tab 操作 ====================
98
- async listTabs(timeout) {
112
+ async listTabs(timeout, options) {
113
+ const currentTabId = this.currentTabId;
99
114
  const result = await this.httpServer.sendCommand('tabs_list', {}, timeout);
100
- return result;
115
+ const tabs = result;
116
+ if (options?.preserveDefaultTarget !== true &&
117
+ currentTabId !== null &&
118
+ this.currentTabId === currentTabId &&
119
+ !tabs.some((tab) => tab.id === currentTabId)) {
120
+ this.setCurrentTargetId(null);
121
+ }
122
+ return tabs;
101
123
  }
102
- async listWindows(timeout) {
124
+ async listWindows(timeout, options) {
125
+ const currentTabId = this.currentTabId;
103
126
  const result = await this.httpServer.sendCommand('tabs_topology', {}, timeout);
104
127
  const topology = result;
105
128
  const windows = topology.windows.map((window) => ({
@@ -141,11 +164,17 @@ export class ExtensionBridge {
141
164
  }
142
165
  return group;
143
166
  });
167
+ if (options?.preserveDefaultTarget !== true &&
168
+ currentTabId !== null &&
169
+ this.currentTabId === currentTabId &&
170
+ !windows.some((window) => window.tabs.some((tab) => tab.id === currentTabId))) {
171
+ this.setCurrentTargetId(null);
172
+ }
144
173
  return { ...topology, windows, ...(groups === undefined ? {} : { groups }) };
145
174
  }
146
175
  /** IBrowserDriver 接口:列出所有 tab,统一为 ListedTarget 形式(id 字符串化以保持跨 driver 兼容) */
147
- async listTargets(timeout) {
148
- const tabs = await this.listTabs(timeout);
176
+ async listTargets(timeout, options) {
177
+ const tabs = await this.listTabs(timeout, options);
149
178
  return tabs.map((tab) => this.tabToTarget(tab));
150
179
  }
151
180
  async createTab(url, timeout, options = {}) {
@@ -201,6 +230,12 @@ export class ExtensionBridge {
201
230
  }
202
231
  return this.closeTab(this.parseTargetId(targetId));
203
232
  }
233
+ async setPageMetadata(targetId, updates) {
234
+ return (await this.httpServer.sendCommand('tabs_metadata', {
235
+ tabId: this.parseTargetId(targetId),
236
+ ...updates,
237
+ }));
238
+ }
204
239
  async setReadAccess(targetId, allow) {
205
240
  return (await this.httpServer.sendCommand('tabs_read_access', {
206
241
  tabId: this.parseTargetId(targetId),
@@ -397,7 +432,7 @@ export class ExtensionBridge {
397
432
  }
398
433
  catch (error) {
399
434
  if (error instanceof Error && error.message === 'Unknown action: page_snapshot') {
400
- const tabs = await this.listTabs(deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
435
+ const tabs = await this.listTabs(deadline === undefined ? undefined : remainingNavigationTimeout(deadline), { preserveDefaultTarget: true });
401
436
  if (deadline !== undefined) {
402
437
  remainingNavigationTimeout(deadline);
403
438
  }
@@ -422,7 +457,13 @@ export class ExtensionBridge {
422
457
  }
423
458
  }
424
459
  setPageCondition(condition) {
425
- this.pendingPageCondition = condition;
460
+ const context = this.options.requestContext?.();
461
+ if (context) {
462
+ context.pendingPageCondition = condition;
463
+ }
464
+ else {
465
+ this.pendingPageCondition = condition;
466
+ }
426
467
  }
427
468
  /** IBrowserDriver 接口:设置当前操作目标 ID */
428
469
  setCurrentTargetId(targetId) {
@@ -474,24 +515,26 @@ export class ExtensionBridge {
474
515
  }));
475
516
  }
476
517
  // ==================== 页面内容 ====================
477
- async click(refId) {
518
+ async click(refId, timeout, modifiers = 0) {
478
519
  const result = (await this.httpServer.sendCommand('click', {
479
520
  tabId: this.requireCurrentTabId(),
480
521
  frameId: this.currentFrameId || undefined,
481
522
  refId,
482
- }));
523
+ modifiers,
524
+ }, timeout));
483
525
  if (!result.success) {
484
526
  throw new Error(result.error || 'Click failed');
485
527
  }
486
528
  }
487
529
  // ==================== DOM 操作 ====================
488
- async actionableClick(refId, force) {
530
+ async actionableClick(refId, force, timeout, modifiers = 0) {
489
531
  return (await this.httpServer.sendCommand('actionable_click', {
490
532
  tabId: this.requireCurrentTabId(),
491
533
  frameId: this.currentFrameId || undefined,
492
534
  refId,
493
535
  force: force ?? false,
494
- }));
536
+ modifiers,
537
+ }, timeout));
495
538
  }
496
539
  async checkActionability(refId) {
497
540
  const result = (await this.httpServer.sendCommand('check_actionability', {
@@ -502,12 +545,16 @@ export class ExtensionBridge {
502
545
  return { ...result, success: result.success ?? result.actionable === true };
503
546
  }
504
547
  async dispatchInput(refId, text) {
505
- return (await this.httpServer.sendCommand('dispatch_input', {
548
+ const result = await this.httpServer.sendCommand('dispatch_input', {
506
549
  tabId: this.requireCurrentTabId(),
507
550
  frameId: this.currentFrameId || undefined,
508
551
  refId,
509
552
  text,
510
- }));
553
+ });
554
+ if (!result || typeof result !== 'object' || !('success' in result) || typeof result.success !== 'boolean') {
555
+ throw new StructuredToolError('ACTION_RESULT_INVALID', 'controlled 输入已派发,但未返回有效的动作结果', '独立读取目标实际文本后再决定下一步,工具不会重放输入', { actionExecuted: 'unknown', actionStatus: 'unknown', retryable: false, failureStage: 'script_result' });
556
+ }
557
+ return result;
511
558
  }
512
559
  async dragAndDrop(srcRefId, dstRefId) {
513
560
  return (await this.httpServer.sendCommand('drag_and_drop', {
@@ -554,7 +601,7 @@ export class ExtensionBridge {
554
601
  scrollAt(x, y, refId) {
555
602
  return this.scroll(x, y, refId);
556
603
  }
557
- async evaluate(code, _args, timeout) {
604
+ async evaluate(code, _args, timeout, userAction) {
558
605
  // _args 参数仅满足 IBrowserDriver 接口签名;ExtensionBridge 不消费 args(stealth 路径上层已字符串拼接)
559
606
  const rpcTimeout = timeout !== undefined ? timeout + RPC_MARGIN : undefined;
560
607
  const result = (await this.httpServer.sendCommand('evaluate', {
@@ -562,21 +609,92 @@ export class ExtensionBridge {
562
609
  frameId: this.currentFrameId || undefined,
563
610
  code,
564
611
  timeout,
565
- }, rpcTimeout));
612
+ deadline: Date.now() + (timeout ?? DEFAULT_TIMEOUT),
613
+ }, rpcTimeout, userAction));
614
+ const outputError = (message, suggestion, context, cause) => {
615
+ const error = new StructuredToolError('NON_SERIALIZABLE_EVALUATE_RESULT', message, suggestion, {
616
+ ...context,
617
+ ...(result.errorMessage !== undefined ? { originalOutputError: result.errorMessage } : {}),
618
+ actionExecuted: true,
619
+ actionStatus: 'completed',
620
+ failureStage: 'output',
621
+ retryable: false,
622
+ });
623
+ if (cause !== undefined) {
624
+ Object.defineProperty(error, 'cause', { value: cause, configurable: true, writable: true });
625
+ }
626
+ if (userAction === undefined) {
627
+ setErrorPageContext(error, { contextPhase: 'preparation' });
628
+ }
629
+ return error;
630
+ };
566
631
  if (!result.success) {
567
- throw new Error(result.error || 'Evaluate failed');
632
+ if (result.errorSource === 'context' && result.actionExecuted === false) {
633
+ throw setErrorSource(new StructuredToolError(result.errorCode ?? 'UNKNOWN_ERROR', result.error ?? 'Script compilation failed', result.errorCode === 'CSP_BLOCKED'
634
+ ? '可使用 evaluate 的 mode="precise" 执行脚本;当前脚本未执行'
635
+ : '请检查脚本语法,当前脚本未执行', {
636
+ actionExecuted: false,
637
+ actionStatus: 'not_started',
638
+ failureStage: 'context',
639
+ retryable: false,
640
+ phase: 'compile',
641
+ }), 'context');
642
+ }
643
+ if (result.errorSource === 'output') {
644
+ if (result.errorCode === 'NON_SERIALIZABLE_EVALUATE_RESULT') {
645
+ throw outputError(result.error ?? 'evaluate 输出处理失败', '请检查返回值及页面的 JSON 序列化行为', {
646
+ error: result.error,
647
+ detailSerializationFailed: true,
648
+ });
649
+ }
650
+ let detail;
651
+ try {
652
+ const value = JSON.parse(result.error)?.error;
653
+ if (typeof value?.message !== 'string' ||
654
+ typeof value.suggestion !== 'string' ||
655
+ !value.context ||
656
+ typeof value.context !== 'object' ||
657
+ Array.isArray(value.context)) {
658
+ throw new TypeError('浏览器返回的 evaluate 输出错误详情格式无效');
659
+ }
660
+ detail = {
661
+ message: value.message,
662
+ suggestion: value.suggestion,
663
+ context: value.context,
664
+ };
665
+ }
666
+ catch (error) {
667
+ throw outputError(`evaluate 输出错误详情解析失败: ${error}`, '请检查页面的 JSON 序列化行为', {
668
+ error: result.error,
669
+ detailParsingError: String(error),
670
+ }, error);
671
+ }
672
+ throw outputError(detail.message, detail.suggestion, detail.context);
673
+ }
674
+ const error = new Error(result.error ?? 'Evaluate failed');
675
+ throw result.errorSource === 'page' ? setErrorSource(error, 'page') : error;
568
676
  }
569
- if (!result.result) {
677
+ if (result.result === undefined) {
570
678
  return undefined;
571
679
  }
572
680
  try {
681
+ if (typeof result.result !== 'string') {
682
+ throw new TypeError('浏览器返回的 evaluate 结果不是 JSON 字符串');
683
+ }
573
684
  return JSON.parse(result.result);
574
685
  }
575
686
  catch (err) {
576
- throw new Error(`evaluate 结果 JSON 解析失败: ${err}`, { cause: err });
687
+ throw outputError(`evaluate 结果 JSON 解析失败: ${err}`, '请返回可 JSON 序列化的简单数据,并检查页面的 JSON 序列化行为', { error: String(err) }, err);
577
688
  }
578
689
  }
579
- async find(selector, text, xpath, timeout, point, matchIndex) {
690
+ async find(selector, text, xpath, timeout, semanticOrPointOrMatchIndex, matchIndex) {
691
+ const point = typeof semanticOrPointOrMatchIndex === 'object' && 'x' in semanticOrPointOrMatchIndex
692
+ ? semanticOrPointOrMatchIndex
693
+ : undefined;
694
+ const semantic = typeof semanticOrPointOrMatchIndex === 'object' && !('x' in semanticOrPointOrMatchIndex)
695
+ ? semanticOrPointOrMatchIndex
696
+ : undefined;
697
+ matchIndex = typeof semanticOrPointOrMatchIndex === 'number' ? semanticOrPointOrMatchIndex : matchIndex;
580
698
  return (await this.httpServer.sendCommand('find', {
581
699
  tabId: this.requireCurrentTabId(),
582
700
  frameId: this.currentFrameId || undefined,
@@ -584,6 +702,7 @@ export class ExtensionBridge {
584
702
  text,
585
703
  xpath,
586
704
  point,
705
+ semantic,
587
706
  matchIndex,
588
707
  }, timeout));
589
708
  }
@@ -676,25 +795,67 @@ export class ExtensionBridge {
676
795
  ...(chromeSameSite !== undefined && { sameSite: chromeSameSite }),
677
796
  });
678
797
  }
679
- async deleteCookie(url, name) {
680
- await this.httpServer.sendCommand('cookies_delete', { url, name });
798
+ async deleteCookie(url, name, scope) {
799
+ await this.httpServer.sendCommand('cookies_delete', { url, name, ...scope });
681
800
  }
682
801
  async clearCookies(filter) {
683
802
  return (await this.httpServer.sendCommand('cookies_clear', filter ?? {}));
684
803
  }
685
- async debuggerSend(method, params, tabId, timeout) {
804
+ async browserEvents(action, command, targetId, timeout) {
805
+ const refTarget = command.ref ? eventRefTarget(command.ref) : undefined;
806
+ if (refTarget && (refTarget.backend !== 'extension' || (targetId && refTarget.targetId !== targetId))) {
807
+ throw new DriverCapabilityError('Browser event ref target mismatch');
808
+ }
809
+ const id = refTarget?.targetId ?? targetId ?? this.getCurrentTargetId();
810
+ if (!id || !/^\d+$/.test(id)) {
811
+ throw new DriverCapabilityError('Browser events require an explicit target or observed ref');
812
+ }
813
+ const result = (await this.httpServer.sendCommand('browser_events', { tabId: Number(id), action, command }, timeout));
814
+ this.browserEventTargets.add(id);
815
+ return result;
816
+ }
817
+ hasBrowserEventObservation(targetId) {
818
+ const id = targetId ?? this.getCurrentTargetId();
819
+ return id !== null && id !== undefined && this.browserEventTargets.has(id);
820
+ }
821
+ async browserFetchCommand(method, params, targetId) {
822
+ const id = targetId ?? this.getCurrentTargetId();
823
+ if (!id || !/^\d+$/.test(id)) {
824
+ throw new DriverCapabilityError('Explicit targetId required for Fetch control');
825
+ }
826
+ return this.httpServer.sendCommand('browser_events_raw', { tabId: Number(id), method, params });
827
+ }
828
+ async suspendBrowserEventsForChallenge() {
829
+ const id = String(this.requireCurrentTabId());
830
+ if (!this.browserEventTargets.has(id)) {
831
+ return { targetId: id, suspended: true, observations: [], cleanupFailures: [], fetchEnabled: false };
832
+ }
833
+ const result = (await this.httpServer.sendCommand('browser_events_suspend', { tabId: Number(id) }));
834
+ if (result.suspended === true) {
835
+ this.browserEventTargets.delete(id);
836
+ }
837
+ return result;
838
+ }
839
+ async debuggerSend(method, params, tabId, timeout, userAction) {
840
+ if (method === 'Fetch.enable') {
841
+ await this.browserEvents('read', { type: 'network', view: 'summary' }, String(tabId ?? this.requireCurrentTabId()), timeout);
842
+ }
686
843
  return await this.httpServer.sendCommand('debugger_send', {
687
844
  tabId: tabId ?? this.requireCurrentTabId(),
688
845
  method,
689
846
  params,
690
- }, timeout);
847
+ }, timeout, userAction);
691
848
  }
692
849
  async debuggerDetach(tabId, timeout = DEFAULT_TIMEOUT) {
693
850
  await this.sendBudgetedCommand('debugger_detach', {
694
851
  tabId: tabId ?? this.requireCurrentTabId(),
695
852
  }, timeout);
853
+ this.browserEventTargets.delete(String(tabId ?? this.requireCurrentTabId()));
696
854
  }
697
- async getViewportMetrics(frameId) {
855
+ async getViewportMetrics(frameId, pointerProbe, timeout) {
856
+ if (pointerProbe) {
857
+ return this.sendBudgetedCommand('viewport_metrics', { tabId: this.requireCurrentTabId(), pointerProbe }, timeout);
858
+ }
698
859
  const selectedFrameId = frameId ?? this.currentFrameId;
699
860
  return this.httpServer.sendCommand('viewport_metrics', {
700
861
  tabId: this.requireCurrentTabId(),
@@ -709,16 +870,43 @@ export class ExtensionBridge {
709
870
  }, timeout);
710
871
  }
711
872
  // ==================== Debugger (CDP via Extension) ====================
873
+ async acquireKeyboardFocus(id, timeout) {
874
+ return (await this.sendBudgetedCommand('keyboard_focus', {
875
+ operation: 'acquire',
876
+ id,
877
+ tabId: this.requireCurrentTabId(),
878
+ frameId: this.currentFrameId,
879
+ documentId: this.currentFrameDocumentId,
880
+ }, timeout));
881
+ }
882
+ async releaseKeyboardFocus(focus, releaseKeys) {
883
+ return (await this.sendBudgetedCommand('keyboard_focus', {
884
+ operation: 'release',
885
+ id: focus.id,
886
+ tabId: this.parseTargetId(focus.targetId),
887
+ releaseKeys,
888
+ }, 4000));
889
+ }
712
890
  async inputKey(type, options = {}, timeout) {
713
891
  await this.sendBudgetedCommand('input_key', {
714
892
  tabId: this.requireCurrentTabId(),
893
+ keyboardFocusId: this.options.requestContext?.()?.keyboardFocus?.id,
715
894
  type,
716
895
  ...options,
717
896
  }, timeout);
718
897
  }
719
898
  // ==================== 输入事件(通过 CDP)====================
720
899
  async inputMouse(type, x, y, options = {}, timeout) {
721
- const params = { tabId: this.requireCurrentTabId(), type, x, y, ...options };
900
+ const params = {
901
+ tabId: this.requireCurrentTabId(),
902
+ frameId: this.currentFrameId,
903
+ documentId: this.currentFrameDocumentId,
904
+ ...(type !== 'mouseWheel' && this.currentFrameId ? { coordinateSpace: 'frame' } : {}),
905
+ type,
906
+ x,
907
+ y,
908
+ ...options,
909
+ };
722
910
  if (timeout === undefined) {
723
911
  await this.httpServer.sendCommand('input_mouse', params);
724
912
  }
@@ -729,12 +917,20 @@ export class ExtensionBridge {
729
917
  async inputTouch(type, touchPoints) {
730
918
  await this.httpServer.sendCommand('input_touch', {
731
919
  tabId: this.requireCurrentTabId(),
920
+ frameId: this.currentFrameId,
921
+ documentId: this.currentFrameDocumentId,
732
922
  type,
733
923
  touchPoints,
734
924
  });
735
925
  }
736
926
  async inputType(text, delay = 0, timeout = DEFAULT_TIMEOUT) {
737
- await this.httpServer.sendCommand('input_type', { tabId: this.requireCurrentTabId(), text, delay, deadline: Date.now() + timeout }, timeout);
927
+ await this.httpServer.sendCommand('input_type', {
928
+ tabId: this.requireCurrentTabId(),
929
+ keyboardFocusId: this.options.requestContext?.()?.keyboardFocus?.id,
930
+ text,
931
+ delay,
932
+ deadline: Date.now() + timeout,
933
+ }, timeout);
738
934
  }
739
935
  async consoleEnable() {
740
936
  await this.httpServer.sendCommand('console_enable', {
@@ -789,7 +985,7 @@ export class ExtensionBridge {
789
985
  };
790
986
  await this.sendBudgetedCommand('stealth_key', params, timeout);
791
987
  }
792
- async stealthClick(x, y, button = 'left', clickCount = 1, refId, timeout = DEFAULT_TIMEOUT) {
988
+ async stealthClick(x, y, button = 'left', clickCount = 1, refId, timeout = DEFAULT_TIMEOUT, modifiers = 0) {
793
989
  if (this.currentTabId === null) {
794
990
  throw new DriverCapabilityError('没有当前页面,请先 browse attach 或先 browse open 创建受控页面');
795
991
  }
@@ -800,13 +996,14 @@ export class ExtensionBridge {
800
996
  y,
801
997
  button,
802
998
  clickCount,
999
+ modifiers,
803
1000
  };
804
1001
  if (typeof refId === 'string') {
805
1002
  params.refId = refId;
806
1003
  }
807
1004
  await this.sendBudgetedCommand('stealth_click', params, timeout);
808
1005
  }
809
- async stealthMouse(type, x, y, button = 'left', timeout) {
1006
+ async stealthMouse(type, x, y, button = 'left', timeout, modifiers = 0) {
810
1007
  if (this.currentTabId === null) {
811
1008
  throw new DriverCapabilityError('没有当前页面,请先 browse attach 或先 browse open 创建受控页面');
812
1009
  }
@@ -817,6 +1014,7 @@ export class ExtensionBridge {
817
1014
  x,
818
1015
  y,
819
1016
  button,
1017
+ modifiers,
820
1018
  };
821
1019
  if (timeout === undefined) {
822
1020
  await this.httpServer.sendCommand('stealth_mouse', params);
@@ -842,13 +1040,17 @@ export class ExtensionBridge {
842
1040
  getCurrentFrameId() {
843
1041
  return this.currentFrameId;
844
1042
  }
845
- setCurrentFrameId(frameId) {
1043
+ getCurrentFrameDocumentId() {
1044
+ return this.currentFrameDocumentId;
1045
+ }
1046
+ setCurrentFrameId(frameId, documentId) {
846
1047
  this.currentFrameId = frameId;
1048
+ this.currentFrameDocumentId = documentId;
847
1049
  }
848
1050
  /**
849
1051
  * 在指定 iframe 中以 precise 模式执行 JS(通过 contextId 绕过 CSP)
850
1052
  */
851
- async evaluateInFrame(frameId, expression, timeout, staleContextRetry = 'never') {
1053
+ async evaluateInFrame(frameId, expression, timeout, staleContextRetry = 'never', userAction) {
852
1054
  return (await this.httpServer.sendCommand('evaluate_in_frame', {
853
1055
  tabId: this.requireCurrentTabId(),
854
1056
  frameId,
@@ -857,7 +1059,7 @@ export class ExtensionBridge {
857
1059
  awaitPromise: true,
858
1060
  timeout,
859
1061
  staleContextRetry,
860
- }, timeout));
1062
+ }, timeout, userAction));
861
1063
  }
862
1064
  /**
863
1065
  * 解析 iframe 选择器/索引 → frameId
@@ -924,7 +1126,7 @@ export class ExtensionBridge {
924
1126
  };
925
1127
  }
926
1128
  parseTargetId(targetId) {
927
- if (!/^(0|[1-9]\d*)$/.test(targetId)) {
1129
+ if (!/^(?:0|[1-9]\d*)$/.test(targetId)) {
928
1130
  throw new DriverCapabilityError(`无效的 Tab ID: ${targetId}`);
929
1131
  }
930
1132
  const parsed = Number(targetId);