@pyrokine/mcp-chrome 2.4.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/README.md +546 -192
  2. package/README_zh.md +490 -192
  3. package/dist/anti-detection/behavior.js +1 -1
  4. package/dist/anti-detection/behavior.js.map +1 -1
  5. package/dist/anti-detection/injection.d.ts.map +1 -1
  6. package/dist/anti-detection/injection.js +5 -4
  7. package/dist/anti-detection/injection.js.map +1 -1
  8. package/dist/cdp/client.d.ts +2 -2
  9. package/dist/cdp/client.d.ts.map +1 -1
  10. package/dist/cdp/client.js +24 -10
  11. package/dist/cdp/client.js.map +1 -1
  12. package/dist/cdp/launcher.d.ts +2 -3
  13. package/dist/cdp/launcher.d.ts.map +1 -1
  14. package/dist/cdp/launcher.js +84 -24
  15. package/dist/cdp/launcher.js.map +1 -1
  16. package/dist/core/auto-wait.d.ts +3 -3
  17. package/dist/core/auto-wait.d.ts.map +1 -1
  18. package/dist/core/auto-wait.js +45 -20
  19. package/dist/core/auto-wait.js.map +1 -1
  20. package/dist/core/browser-driver.d.ts +104 -14
  21. package/dist/core/browser-driver.d.ts.map +1 -1
  22. package/dist/core/browser-driver.js +1 -0
  23. package/dist/core/browser-driver.js.map +1 -1
  24. package/dist/core/errors.d.ts +25 -0
  25. package/dist/core/errors.d.ts.map +1 -1
  26. package/dist/core/errors.js +93 -1
  27. package/dist/core/errors.js.map +1 -1
  28. package/dist/core/locator.d.ts.map +1 -1
  29. package/dist/core/locator.js +6 -4
  30. package/dist/core/locator.js.map +1 -1
  31. package/dist/core/os-mouse.d.ts +78 -0
  32. package/dist/core/os-mouse.d.ts.map +1 -0
  33. package/dist/core/os-mouse.js +378 -0
  34. package/dist/core/os-mouse.js.map +1 -0
  35. package/dist/core/session.d.ts +46 -21
  36. package/dist/core/session.d.ts.map +1 -1
  37. package/dist/core/session.js +724 -175
  38. package/dist/core/session.js.map +1 -1
  39. package/dist/core/types.d.ts +12 -0
  40. package/dist/core/types.d.ts.map +1 -1
  41. package/dist/core/types.js +2 -0
  42. package/dist/core/types.js.map +1 -1
  43. package/dist/core/unified-session.d.ts +117 -21
  44. package/dist/core/unified-session.d.ts.map +1 -1
  45. package/dist/core/unified-session.js +619 -129
  46. package/dist/core/unified-session.js.map +1 -1
  47. package/dist/core/utils.d.ts +5 -0
  48. package/dist/core/utils.d.ts.map +1 -1
  49. package/dist/core/utils.js +475 -54
  50. package/dist/core/utils.js.map +1 -1
  51. package/dist/extension/bridge.d.ts +61 -35
  52. package/dist/extension/bridge.d.ts.map +1 -1
  53. package/dist/extension/bridge.js +290 -106
  54. package/dist/extension/bridge.js.map +1 -1
  55. package/dist/extension/http-server.d.ts +3 -0
  56. package/dist/extension/http-server.d.ts.map +1 -1
  57. package/dist/extension/http-server.js +25 -3
  58. package/dist/extension/http-server.js.map +1 -1
  59. package/dist/index.js +7 -0
  60. package/dist/index.js.map +1 -1
  61. package/dist/tools/browse.d.ts +1 -1
  62. package/dist/tools/browse.d.ts.map +1 -1
  63. package/dist/tools/browse.js +291 -175
  64. package/dist/tools/browse.js.map +1 -1
  65. package/dist/tools/challenge.d.ts +153 -0
  66. package/dist/tools/challenge.d.ts.map +1 -0
  67. package/dist/tools/challenge.js +611 -0
  68. package/dist/tools/challenge.js.map +1 -0
  69. package/dist/tools/cookies.d.ts.map +1 -1
  70. package/dist/tools/cookies.js +13 -7
  71. package/dist/tools/cookies.js.map +1 -1
  72. package/dist/tools/diagnostics.d.ts +5 -5
  73. package/dist/tools/diagnostics.d.ts.map +1 -1
  74. package/dist/tools/diagnostics.js +39 -20
  75. package/dist/tools/diagnostics.js.map +1 -1
  76. package/dist/tools/evaluate.d.ts.map +1 -1
  77. package/dist/tools/evaluate.js +106 -23
  78. package/dist/tools/evaluate.js.map +1 -1
  79. package/dist/tools/extract.d.ts.map +1 -1
  80. package/dist/tools/extract.js +199 -208
  81. package/dist/tools/extract.js.map +1 -1
  82. package/dist/tools/input.d.ts +1 -1
  83. package/dist/tools/input.d.ts.map +1 -1
  84. package/dist/tools/input.js +523 -175
  85. package/dist/tools/input.js.map +1 -1
  86. package/dist/tools/logs.d.ts.map +1 -1
  87. package/dist/tools/logs.js +7 -7
  88. package/dist/tools/logs.js.map +1 -1
  89. package/dist/tools/manage.d.ts.map +1 -1
  90. package/dist/tools/manage.js +400 -64
  91. package/dist/tools/manage.js.map +1 -1
  92. package/dist/tools/network-sanitizer.d.ts.map +1 -1
  93. package/dist/tools/network-sanitizer.js +1 -0
  94. package/dist/tools/network-sanitizer.js.map +1 -1
  95. package/dist/tools/page-context.d.ts +17 -0
  96. package/dist/tools/page-context.d.ts.map +1 -0
  97. package/dist/tools/page-context.js +103 -0
  98. package/dist/tools/page-context.js.map +1 -0
  99. package/dist/tools/png.d.ts +5 -0
  100. package/dist/tools/png.d.ts.map +1 -1
  101. package/dist/tools/png.js +89 -22
  102. package/dist/tools/png.js.map +1 -1
  103. package/dist/tools/post-condition.d.ts.map +1 -1
  104. package/dist/tools/post-condition.js +17 -5
  105. package/dist/tools/post-condition.js.map +1 -1
  106. package/dist/tools/schema.d.ts +9 -0
  107. package/dist/tools/schema.d.ts.map +1 -1
  108. package/dist/tools/schema.js +15 -0
  109. package/dist/tools/schema.js.map +1 -1
  110. package/dist/tools/target-diagnostics.d.ts +7 -0
  111. package/dist/tools/target-diagnostics.d.ts.map +1 -1
  112. package/dist/tools/target-diagnostics.js +47 -17
  113. package/dist/tools/target-diagnostics.js.map +1 -1
  114. package/dist/tools/wait.d.ts.map +1 -1
  115. package/dist/tools/wait.js +52 -56
  116. package/dist/tools/wait.js.map +1 -1
  117. package/extension/dist/assets/content.ts-C4imZ6A9.js +13 -0
  118. package/extension/dist/assets/content.ts-loader-CnJuCGhl.js +13 -0
  119. package/extension/dist/assets/{index.ts-GG6dPUPX.js → index.ts-GeHNZBml.js} +2156 -1950
  120. package/extension/dist/assets/page-scripts-CMIY1zhd.js +1379 -0
  121. package/extension/dist/assets/{popup.html-B81xccfq.js → popup.html-CgtWL6Py.js} +48 -1
  122. package/extension/dist/manifest.json +4 -3
  123. package/extension/dist/service-worker-loader.js +1 -1
  124. package/extension/dist/src/popup/popup.html +54 -44
  125. package/package.json +11 -8
  126. package/scripts/start-chrome.ps1 +58 -0
  127. package/dist/extension/native-host-installer.d.ts +0 -21
  128. package/dist/extension/native-host-installer.d.ts.map +0 -1
  129. package/dist/extension/native-host-installer.js +0 -147
  130. package/dist/extension/native-host-installer.js.map +0 -1
  131. package/dist/extension/socket-server.d.ts +0 -32
  132. package/dist/extension/socket-server.d.ts.map +0 -1
  133. package/dist/extension/socket-server.js +0 -177
  134. package/dist/extension/socket-server.js.map +0 -1
  135. package/dist/extension/ws-server.d.ts +0 -40
  136. package/dist/extension/ws-server.d.ts.map +0 -1
  137. package/dist/extension/ws-server.js +0 -246
  138. package/dist/extension/ws-server.js.map +0 -1
  139. package/dist/native-host/index.js +0 -280
  140. package/dist/native-host/mcp-chrome-host +0 -2
  141. package/extension/dist/assets/content.ts-Cj_iiU2s.js +0 -25
@@ -5,33 +5,75 @@
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';
10
+ import { DEFAULT_TIMEOUT } from '../core/types.js';
8
11
  import { ExtensionHttpServer } from './http-server.js';
9
12
  /** RPC 传输余量(毫秒):给网络往返和 Extension 处理留出的额外时间 */
10
13
  const RPC_MARGIN = 5000;
11
- /** goBack/goForward 信号窗口(毫秒):Extension 等待导航开始的上限 */
12
- const NAV_SIGNAL_WINDOW = 5000;
14
+ const CONDITIONAL_ACTIONS = new Set([
15
+ 'tabs_close',
16
+ 'tabs_activate',
17
+ 'tabs_activate_managed',
18
+ 'tabs_adopt',
19
+ 'tabs_release',
20
+ 'tabs_read_access',
21
+ 'tabs_move',
22
+ 'tabs_reorder',
23
+ 'tabs_pin',
24
+ 'tabs_update',
25
+ 'navigate',
26
+ 'go_back',
27
+ 'go_forward',
28
+ 'reload',
29
+ 'click',
30
+ 'actionable_click',
31
+ 'dispatch_input',
32
+ 'drag_and_drop',
33
+ 'type',
34
+ 'scroll',
35
+ 'evaluate',
36
+ 'evaluate_in_frame',
37
+ 'debugger_send',
38
+ 'input_key',
39
+ 'input_mouse',
40
+ 'input_touch',
41
+ 'input_type',
42
+ 'stealth_click',
43
+ 'stealth_type',
44
+ 'stealth_key',
45
+ 'stealth_mouse',
46
+ 'stealth_inject',
47
+ ]);
13
48
  export class ExtensionBridge {
14
49
  httpServer;
15
50
  currentTabId = null;
16
51
  currentFrameId = 0;
17
52
  state = null;
53
+ pendingPageCondition = null;
18
54
  constructor(options = {}) {
19
55
  this.httpServer = new ExtensionHttpServer({
20
56
  port: options.port,
21
57
  autoPort: true,
22
58
  });
59
+ this.httpServer.setActionConditionProvider((action, params) => {
60
+ const condition = this.pendingPageCondition;
61
+ if (!condition || !CONDITIONAL_ACTIONS.has(action)) {
62
+ return undefined;
63
+ }
64
+ const tabId = params?.tabId;
65
+ if (tabId === undefined || String(tabId) !== condition.targetId) {
66
+ throw new DriverCapabilityError('条件动作的目标与请求目标不一致,未执行动作');
67
+ }
68
+ this.pendingPageCondition = null;
69
+ return {
70
+ ...(condition.expectedUrl !== undefined ? { expectedUrl: condition.expectedUrl } : {}),
71
+ ...(condition.expectedRevision !== undefined ? { expectedRevision: condition.expectedRevision } : {}),
72
+ };
73
+ });
23
74
  }
24
75
  async start() {
25
76
  await this.httpServer.start();
26
- // Extension 重连后自动恢复 attach 状态
27
- this.httpServer.on('connected', () => {
28
- if (this.currentTabId !== null) {
29
- const tabId = this.currentTabId;
30
- this.httpServer.sendCommand('debugger_attach', { tabId }).catch((err) => {
31
- console.error('[Bridge] 重连后 debugger re-attach 失败:', err.message);
32
- });
33
- }
34
- });
35
77
  }
36
78
  async stop() {
37
79
  await this.httpServer.stop();
@@ -53,12 +95,12 @@ export class ExtensionBridge {
53
95
  return this.httpServer.getConnectionInfo();
54
96
  }
55
97
  // ==================== Tab 操作 ====================
56
- async listTabs() {
57
- const result = await this.httpServer.sendCommand('tabs_list', {});
98
+ async listTabs(timeout) {
99
+ const result = await this.httpServer.sendCommand('tabs_list', {}, timeout);
58
100
  return result;
59
101
  }
60
- async listWindows() {
61
- const result = await this.httpServer.sendCommand('tabs_topology', {});
102
+ async listWindows(timeout) {
103
+ const result = await this.httpServer.sendCommand('tabs_topology', {}, timeout);
62
104
  const topology = result;
63
105
  return {
64
106
  ...topology,
@@ -73,18 +115,30 @@ export class ExtensionBridge {
73
115
  };
74
116
  }
75
117
  /** IBrowserDriver 接口:列出所有 tab,统一为 ListedTarget 形式(id 字符串化以保持跨 driver 兼容) */
76
- async listTargets() {
77
- const tabs = await this.listTabs();
118
+ async listTargets(timeout) {
119
+ const tabs = await this.listTabs(timeout);
78
120
  return tabs.map((tab) => this.tabToTarget(tab));
79
121
  }
80
- async createTab(url, timeout) {
81
- const rpcTimeout = timeout !== undefined ? timeout + RPC_MARGIN : undefined;
82
- const result = await this.httpServer.sendCommand('tabs_create', {
122
+ async createTab(url, timeout, options = {}) {
123
+ const rpcTimeout = (timeout ?? 30000) + RPC_MARGIN;
124
+ const result = await this.httpServer
125
+ .sendCommand('tabs_create', {
83
126
  url,
84
127
  active: false,
128
+ ...options,
85
129
  waitUntil: 'load',
86
130
  timeout,
87
- }, rpcTimeout);
131
+ }, rpcTimeout)
132
+ .catch((error) => {
133
+ throw creationError(error, {
134
+ action: 'tabs_create',
135
+ createdTargetId: null,
136
+ managed: null,
137
+ actionExecuted: 'unknown',
138
+ actionStatus: 'unknown',
139
+ failureStage: 'rpc',
140
+ });
141
+ });
88
142
  const tab = result;
89
143
  // 自动切换到新创建的 tab,后续操作立即生效
90
144
  this.currentTabId = tab.id;
@@ -92,9 +146,10 @@ export class ExtensionBridge {
92
146
  return tab;
93
147
  }
94
148
  /** IBrowserDriver 接口:新建页面(targetId 为字符串化的 chrome tab id) */
95
- async newPage(url, timeout) {
96
- const tab = await this.createTab(url, timeout);
149
+ async newPage(url, timeout, options) {
150
+ const tab = await this.createTab(url, timeout, options);
97
151
  return {
152
+ ...this.tabToTarget(tab),
98
153
  targetId: String(tab.id),
99
154
  url: tab.url,
100
155
  title: tab.title,
@@ -110,13 +165,18 @@ export class ExtensionBridge {
110
165
  }
111
166
  return this.normalizePageChange(result);
112
167
  }
113
- /** IBrowserDriver 接口:关闭页面(targetId 是 chrome tab id 的字符串形式,省略时关闭当前 tab) */
168
+ /** IBrowserDriver 接口:只能关闭明确指定的 tab */
114
169
  async closePage(targetId) {
115
- const tabId = targetId !== undefined ? this.parseTargetId(targetId) : this.currentTabId;
116
- if (tabId === null) {
117
- throw new DriverCapabilityError('没有可关闭的页面,请指定 targetId');
170
+ if (!targetId) {
171
+ throw new DriverCapabilityError('closePage 需要显式 targetId,未关闭页面');
118
172
  }
119
- return this.closeTab(tabId);
173
+ return this.closeTab(this.parseTargetId(targetId));
174
+ }
175
+ async setReadAccess(targetId, allow) {
176
+ return (await this.httpServer.sendCommand('tabs_read_access', {
177
+ tabId: this.parseTargetId(targetId),
178
+ allow,
179
+ }));
120
180
  }
121
181
  async adoptPage(targetId) {
122
182
  const tabId = this.parseTargetId(targetId);
@@ -140,6 +200,7 @@ export class ExtensionBridge {
140
200
  target: this.tabToTarget(result.tab),
141
201
  managedBefore: result.managedBefore,
142
202
  managedAfter: result.managedAfter,
203
+ ...(result.warnings?.length ? { warnings: result.warnings } : {}),
143
204
  };
144
205
  }
145
206
  async movePage(targetId, options) {
@@ -152,6 +213,43 @@ export class ExtensionBridge {
152
213
  }));
153
214
  return this.normalizePageChange(result);
154
215
  }
216
+ async updatePage(targetId, options) {
217
+ const tabId = this.parseTargetId(targetId);
218
+ const result = (await this.httpServer.sendCommand('tabs_update', {
219
+ tabId,
220
+ ...options,
221
+ }));
222
+ const after = result.after;
223
+ if (this.currentTabId === tabId && after) {
224
+ this.updateState(after);
225
+ }
226
+ return this.normalizePageChange(result);
227
+ }
228
+ async groupPages(targetIds, options) {
229
+ const tabIds = targetIds.map((id) => this.parseTargetId(id));
230
+ if (options.groupId !== undefined &&
231
+ [options.windowId, options.title, options.color, options.collapsed].some((value) => value !== undefined)) {
232
+ throw new DriverCapabilityError('加入已有分组仅接受页面列表与 groupId;修改分组请用 updateGroup/moveGroup,未执行');
233
+ }
234
+ const result = options.groupId !== undefined
235
+ ? await this.httpServer.sendCommand('tabgroup_add', { tabIds, groupId: options.groupId })
236
+ : await this.httpServer.sendCommand('tabgroup_create', { tabIds, ...options });
237
+ return this.normalizeGroupChange(result);
238
+ }
239
+ async ungroupPages(targetIds) {
240
+ const result = await this.httpServer.sendCommand('tabgroup_remove', {
241
+ tabIds: targetIds.map((id) => this.parseTargetId(id)),
242
+ });
243
+ return this.normalizeGroupChange(result);
244
+ }
245
+ async updateGroup(groupId, options) {
246
+ const result = await this.httpServer.sendCommand('tabgroup_update', { groupId, ...options });
247
+ return this.normalizeGroupChange(result);
248
+ }
249
+ async moveGroup(groupId, options) {
250
+ const result = await this.httpServer.sendCommand('tabgroup_move', { groupId, ...options });
251
+ return this.normalizeGroupChange(result);
252
+ }
155
253
  async reorderPage(targetId, index) {
156
254
  const tabId = this.parseTargetId(targetId);
157
255
  const result = (await this.httpServer.sendCommand('tabs_reorder', {
@@ -176,8 +274,31 @@ export class ExtensionBridge {
176
274
  }));
177
275
  return this.normalizePageChange(result);
178
276
  }
277
+ async updateWindow(windowId, options) {
278
+ const result = (await this.httpServer.sendCommand('window_update', {
279
+ windowId,
280
+ ...options,
281
+ }));
282
+ return this.normalizePageChange(result);
283
+ }
179
284
  async newWindow(options) {
180
- const result = (await this.httpServer.sendCommand('window_create', options));
285
+ const { targetId, ...properties } = options;
286
+ const tabId = targetId !== undefined ? this.parseTargetId(targetId) : undefined;
287
+ const result = (await this.httpServer
288
+ .sendCommand('window_create', {
289
+ ...properties,
290
+ ...(tabId !== undefined ? { tabId } : {}),
291
+ })
292
+ .catch((error) => {
293
+ throw creationError(error, {
294
+ action: 'window_create',
295
+ createdTargetId: null,
296
+ managed: null,
297
+ actionExecuted: 'unknown',
298
+ actionStatus: 'unknown',
299
+ failureStage: 'rpc',
300
+ });
301
+ }));
181
302
  if (result.targetId) {
182
303
  this.currentTabId = this.parseTargetId(result.targetId);
183
304
  const after = result.after;
@@ -197,6 +318,7 @@ export class ExtensionBridge {
197
318
  }
198
319
  return this.normalizePageChange(result);
199
320
  }
321
+ // noinspection JSUnusedGlobalSymbols — UnifiedSessionManager 通过 bridge 结构类型调用
200
322
  async activatePageWithAffected(targetId) {
201
323
  const tabId = this.parseTargetId(targetId);
202
324
  const result = (await this.httpServer.sendCommand('tabs_activate_managed', {
@@ -221,9 +343,13 @@ export class ExtensionBridge {
221
343
  await this.activateTab(tabId);
222
344
  }
223
345
  /** IBrowserDriver 接口:选择操作目标 tab(不切换前台,只设置当前 currentTabId) */
224
- async selectPage(targetId) {
346
+ async selectPage(targetId, timeout) {
225
347
  const tabId = this.parseTargetId(targetId);
226
- const tabs = await this.listTabs();
348
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
349
+ const tabs = await this.listTabs(timeout);
350
+ if (deadline !== undefined) {
351
+ remainingNavigationTimeout(deadline);
352
+ }
227
353
  const tab = tabs.find((item) => item.id === tabId);
228
354
  if (!tab) {
229
355
  throw new DriverCapabilityError(`Tab ${targetId} 不存在,请先 browse(action="list") 查看可用页面`);
@@ -235,6 +361,41 @@ export class ExtensionBridge {
235
361
  getCurrentTargetId() {
236
362
  return this.currentTabId !== null ? String(this.currentTabId) : null;
237
363
  }
364
+ async getPageSnapshot(targetId, timeout) {
365
+ const tabId = this.parseTargetId(targetId);
366
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
367
+ try {
368
+ return (await this.httpServer.sendCommand('page_snapshot', { tabId }, timeout));
369
+ }
370
+ catch (error) {
371
+ if (error instanceof Error && error.message === 'Unknown action: page_snapshot') {
372
+ const tabs = await this.listTabs(deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
373
+ if (deadline !== undefined) {
374
+ remainingNavigationTimeout(deadline);
375
+ }
376
+ const tab = tabs.find((item) => item.id === tabId);
377
+ if (!tab) {
378
+ throw new TargetNotFoundError(targetId);
379
+ }
380
+ return {
381
+ targetId,
382
+ url: tab.url,
383
+ revision: null,
384
+ warning: '当前 Extension 不支持页面 revision 或原子页面条件,仅返回当前 URL',
385
+ };
386
+ }
387
+ if (error instanceof Error &&
388
+ (error.message === `No tab with id: ${tabId}` || error.message === `No tab with id: ${tabId}.`)) {
389
+ const missing = new TargetNotFoundError(targetId);
390
+ missing.context.nativeMessage = error.message;
391
+ throw missing;
392
+ }
393
+ throw error;
394
+ }
395
+ }
396
+ setPageCondition(condition) {
397
+ this.pendingPageCondition = condition;
398
+ }
238
399
  /** IBrowserDriver 接口:设置当前操作目标 ID */
239
400
  setCurrentTargetId(targetId) {
240
401
  this.currentTabId = targetId !== null ? this.parseTargetId(targetId) : null;
@@ -243,68 +404,39 @@ export class ExtensionBridge {
243
404
  }
244
405
  }
245
406
  async navigate(url, options) {
246
- if (this.currentTabId === null) {
247
- throw new DriverCapabilityError('没有当前页面,请先 browse attach 或先 browse open 创建受控页面');
248
- }
249
- const rpcTimeout = options?.timeout !== undefined ? options.timeout + RPC_MARGIN : undefined;
250
- const params = {
407
+ const result = await this.sendBudgetedCommand('navigate', {
251
408
  tabId: this.requireCurrentTabId(),
252
409
  url,
253
410
  waitUntil: options?.wait ?? 'load',
254
- timeout: options?.timeout,
255
- };
256
- const result = await this.httpServer.sendCommand('navigate', params, rpcTimeout);
411
+ }, options?.timeout);
257
412
  const tab = result;
258
413
  this.currentTabId = tab.id;
259
414
  this.updateState(tab);
260
415
  }
261
416
  // ==================== 导航操作 ====================
262
417
  async goBack(timeout) {
263
- if (this.currentTabId === null) {
264
- throw new DriverCapabilityError('没有当前页面,请先 browse attach 或先 browse open 创建受控页面');
265
- }
266
- // 默认:NAV_SIGNAL_WINDOW + 导航等待(默认 30s)+ RPC_MARGIN = 40s
267
- // 调用方传 timeout 时:timeout 即导航超时 + 信号窗口 + 传输余量
268
- const rpcTimeout = timeout !== undefined ? timeout + NAV_SIGNAL_WINDOW + RPC_MARGIN : 30000 + NAV_SIGNAL_WINDOW + RPC_MARGIN;
269
- const params = {
418
+ const result = (await this.sendBudgetedCommand('go_back', {
270
419
  tabId: this.requireCurrentTabId(),
271
420
  waitUntil: 'load',
272
- timeout,
273
- };
274
- const result = (await this.httpServer.sendCommand('go_back', params, rpcTimeout));
421
+ }, timeout));
275
422
  this.updateState(result);
276
423
  return result;
277
424
  }
278
425
  async goForward(timeout) {
279
- if (this.currentTabId === null) {
280
- throw new DriverCapabilityError('没有当前页面,请先 browse attach 或先 browse open 创建受控页面');
281
- }
282
- // 默认:NAV_SIGNAL_WINDOW + 导航等待(默认 30s)+ RPC_MARGIN = 40s
283
- // 调用方传 timeout 时:timeout 即导航超时 + 信号窗口 + 传输余量
284
- const rpcTimeout = timeout !== undefined ? timeout + NAV_SIGNAL_WINDOW + RPC_MARGIN : 30000 + NAV_SIGNAL_WINDOW + RPC_MARGIN;
285
- const params = {
426
+ const result = (await this.sendBudgetedCommand('go_forward', {
286
427
  tabId: this.requireCurrentTabId(),
287
428
  waitUntil: 'load',
288
- timeout,
289
- };
290
- const result = (await this.httpServer.sendCommand('go_forward', params, rpcTimeout));
429
+ }, timeout));
291
430
  this.updateState(result);
292
431
  return result;
293
432
  }
294
433
  async reload(ignoreCache = false, waitUntil, timeout) {
295
- if (this.currentTabId === null) {
296
- throw new DriverCapabilityError('没有当前页面,请先 browse attach 或先 browse open 创建受控页面');
297
- }
298
- const rpcTimeout = timeout !== undefined ? timeout + RPC_MARGIN : undefined;
299
- const params = {
434
+ const result = await this.sendBudgetedCommand('reload', {
300
435
  tabId: this.requireCurrentTabId(),
301
436
  ignoreCache,
302
437
  waitUntil: waitUntil ?? 'load',
303
- timeout,
304
- };
305
- const result = await this.httpServer.sendCommand('reload', params, rpcTimeout);
306
- const tab = result;
307
- this.updateState(tab);
438
+ }, timeout);
439
+ this.updateState(result);
308
440
  }
309
441
  async readPage(options) {
310
442
  return (await this.httpServer.sendCommand('read_page', {
@@ -416,29 +548,33 @@ export class ExtensionBridge {
416
548
  throw new Error(`evaluate 结果 JSON 解析失败: ${err}`, { cause: err });
417
549
  }
418
550
  }
419
- async find(selector, text, xpath, timeout) {
551
+ async find(selector, text, xpath, timeout, point, matchIndex) {
420
552
  return (await this.httpServer.sendCommand('find', {
421
553
  tabId: this.requireCurrentTabId(),
422
554
  frameId: this.currentFrameId || undefined,
423
555
  selector,
424
556
  text,
425
557
  xpath,
558
+ point,
559
+ matchIndex,
426
560
  }, timeout));
427
561
  }
428
- async getText(selector) {
562
+ async getText(selector, refId) {
429
563
  const result = (await this.httpServer.sendCommand('get_text', {
430
564
  tabId: this.requireCurrentTabId(),
431
565
  frameId: this.currentFrameId || undefined,
432
566
  selector,
567
+ refId,
433
568
  }));
434
569
  return result.text;
435
570
  }
436
- async getHtml(selector, outer = true) {
571
+ async getHtml(selector, outer = true, refId) {
437
572
  const result = (await this.httpServer.sendCommand('get_html', {
438
573
  tabId: this.requireCurrentTabId(),
439
574
  frameId: this.currentFrameId || undefined,
440
575
  selector,
441
576
  outer,
577
+ refId,
442
578
  }));
443
579
  return result.html;
444
580
  }
@@ -456,18 +592,25 @@ export class ExtensionBridge {
456
592
  const requests = await this.networkGet(options);
457
593
  return requests;
458
594
  }
595
+ async getChallengeState() {
596
+ const result = (await this.httpServer.sendCommand('network_challenge_state', {
597
+ tabId: this.requireCurrentTabId(),
598
+ }));
599
+ return result.challengeRequired;
600
+ }
459
601
  async screenshot(options) {
460
602
  return (await this.httpServer.sendCommand('screenshot', {
461
603
  tabId: this.requireCurrentTabId(),
462
604
  ...options,
463
605
  }));
464
606
  }
465
- async getHtmlWithImages(selector, outer = true) {
607
+ async getHtmlWithImages(selector, outer = true, refId) {
466
608
  return (await this.httpServer.sendCommand('get_html_with_images', {
467
609
  tabId: this.requireCurrentTabId(),
468
610
  frameId: this.currentFrameId || undefined,
469
611
  selector,
470
612
  outer,
613
+ refId,
471
614
  }));
472
615
  }
473
616
  async getAttribute(selector, refId, attribute) {
@@ -518,6 +661,25 @@ export class ExtensionBridge {
518
661
  params,
519
662
  }, timeout);
520
663
  }
664
+ async debuggerDetach(tabId, timeout = DEFAULT_TIMEOUT) {
665
+ await this.sendBudgetedCommand('debugger_detach', {
666
+ tabId: tabId ?? this.requireCurrentTabId(),
667
+ }, timeout);
668
+ }
669
+ async getViewportMetrics(frameId) {
670
+ const selectedFrameId = frameId ?? this.currentFrameId;
671
+ return this.httpServer.sendCommand('viewport_metrics', {
672
+ tabId: this.requireCurrentTabId(),
673
+ frameId: selectedFrameId || undefined,
674
+ });
675
+ }
676
+ async inspectChallenge(params, timeout) {
677
+ return this.sendBudgetedCommand('challenge_inspect', {
678
+ tabId: this.requireCurrentTabId(),
679
+ frameId: this.currentFrameId || undefined,
680
+ ...params,
681
+ }, timeout);
682
+ }
521
683
  // ==================== Debugger (CDP via Extension) ====================
522
684
  async inputKey(type, options = {}) {
523
685
  await this.httpServer.sendCommand('input_key', {
@@ -527,14 +689,14 @@ export class ExtensionBridge {
527
689
  });
528
690
  }
529
691
  // ==================== 输入事件(通过 CDP)====================
530
- async inputMouse(type, x, y, options = {}) {
531
- await this.httpServer.sendCommand('input_mouse', {
532
- tabId: this.requireCurrentTabId(),
533
- type,
534
- x,
535
- y,
536
- ...options,
537
- });
692
+ async inputMouse(type, x, y, options = {}, timeout) {
693
+ const params = { tabId: this.requireCurrentTabId(), type, x, y, ...options };
694
+ if (timeout === undefined) {
695
+ await this.httpServer.sendCommand('input_mouse', params);
696
+ }
697
+ else {
698
+ await this.sendBudgetedCommand('input_mouse', params, timeout);
699
+ }
538
700
  }
539
701
  async inputTouch(type, touchPoints) {
540
702
  await this.httpServer.sendCommand('input_touch', {
@@ -543,12 +705,8 @@ export class ExtensionBridge {
543
705
  touchPoints,
544
706
  });
545
707
  }
546
- async inputType(text, delay = 0) {
547
- await this.httpServer.sendCommand('input_type', {
548
- tabId: this.requireCurrentTabId(),
549
- text,
550
- delay,
551
- });
708
+ async inputType(text, delay = 0, timeout = DEFAULT_TIMEOUT) {
709
+ await this.httpServer.sendCommand('input_type', { tabId: this.requireCurrentTabId(), text, delay, deadline: Date.now() + timeout }, timeout);
552
710
  }
553
711
  async consoleEnable() {
554
712
  await this.httpServer.sendCommand('console_enable', {
@@ -576,7 +734,7 @@ export class ExtensionBridge {
576
734
  }));
577
735
  return result.requests;
578
736
  }
579
- async stealthType(text, delay = 0) {
737
+ async stealthType(text, delay = 0, timeout = DEFAULT_TIMEOUT) {
580
738
  if (this.currentTabId === null) {
581
739
  throw new DriverCapabilityError('没有当前页面,请先 browse attach 或先 browse open 创建受控页面');
582
740
  }
@@ -585,8 +743,9 @@ export class ExtensionBridge {
585
743
  frameId: this.currentFrameId !== null ? this.currentFrameId : undefined,
586
744
  text,
587
745
  delay,
746
+ deadline: Date.now() + timeout,
588
747
  };
589
- await this.httpServer.sendCommand('stealth_type', params);
748
+ await this.httpServer.sendCommand('stealth_type', params, timeout);
590
749
  }
591
750
  // ==================== Stealth 模式(JS 事件模拟,无 debugger)====================
592
751
  async stealthKey(key, type = 'press', modifiers = []) {
@@ -602,7 +761,7 @@ export class ExtensionBridge {
602
761
  };
603
762
  await this.httpServer.sendCommand('stealth_key', params);
604
763
  }
605
- async stealthClick(x, y, button = 'left', clickCount = 1, refId) {
764
+ async stealthClick(x, y, button = 'left', clickCount = 1, refId, timeout = DEFAULT_TIMEOUT) {
606
765
  if (this.currentTabId === null) {
607
766
  throw new DriverCapabilityError('没有当前页面,请先 browse attach 或先 browse open 创建受控页面');
608
767
  }
@@ -617,9 +776,9 @@ export class ExtensionBridge {
617
776
  if (typeof refId === 'string') {
618
777
  params.refId = refId;
619
778
  }
620
- await this.httpServer.sendCommand('stealth_click', params);
779
+ await this.sendBudgetedCommand('stealth_click', params, timeout);
621
780
  }
622
- async stealthMouse(type, x, y, button = 'left') {
781
+ async stealthMouse(type, x, y, button = 'left', timeout) {
623
782
  if (this.currentTabId === null) {
624
783
  throw new DriverCapabilityError('没有当前页面,请先 browse attach 或先 browse open 创建受控页面');
625
784
  }
@@ -631,7 +790,12 @@ export class ExtensionBridge {
631
790
  y,
632
791
  button,
633
792
  };
634
- await this.httpServer.sendCommand('stealth_mouse', params);
793
+ if (timeout === undefined) {
794
+ await this.httpServer.sendCommand('stealth_mouse', params);
795
+ }
796
+ else {
797
+ await this.sendBudgetedCommand('stealth_mouse', params, timeout);
798
+ }
635
799
  }
636
800
  async stealthInject() {
637
801
  if (this.currentTabId === null) {
@@ -676,6 +840,24 @@ export class ExtensionBridge {
676
840
  frame,
677
841
  }));
678
842
  }
843
+ async sendBudgetedCommand(action, params, timeout = DEFAULT_TIMEOUT) {
844
+ const deadline = Date.now() + timeout;
845
+ const remaining = remainingNavigationTimeout(deadline);
846
+ try {
847
+ return await this.httpServer.sendCommand(action, { ...params, timeout: remaining, deadline }, remaining);
848
+ }
849
+ catch (error) {
850
+ if (error instanceof Error && error.message.startsWith(`Request timeout for action: ${action} (`)) {
851
+ throw new StructuredToolError('TIMEOUT', error.message, '请回读实际页面,勿自动重放操作', {
852
+ actionExecuted: 'unknown',
853
+ actionStatus: 'unknown',
854
+ failureStage: 'rpc',
855
+ retryable: false,
856
+ });
857
+ }
858
+ throw error;
859
+ }
860
+ }
679
861
  requireCurrentTabId() {
680
862
  if (this.currentTabId === null) {
681
863
  throw new DriverCapabilityError('没有当前页面,请先 browse attach 或先 browse open 创建受控页面');
@@ -690,6 +872,15 @@ export class ExtensionBridge {
690
872
  after: this.normalizeAffected(result.after),
691
873
  };
692
874
  }
875
+ normalizeGroupChange(result) {
876
+ return {
877
+ groupId: result.groupId,
878
+ before: result.before,
879
+ after: result.after,
880
+ tabsBefore: result.tabsBefore.map((tab) => this.tabToTarget(tab)),
881
+ tabsAfter: result.tabsAfter.map((tab) => this.tabToTarget(tab)),
882
+ };
883
+ }
693
884
  normalizeAffected(value) {
694
885
  if (!value) {
695
886
  return value;
@@ -703,27 +894,20 @@ export class ExtensionBridge {
703
894
  };
704
895
  }
705
896
  parseTargetId(targetId) {
706
- const parsed = parseInt(targetId, 10);
707
- if (isNaN(parsed)) {
897
+ if (!/^(0|[1-9]\d*)$/.test(targetId)) {
898
+ throw new DriverCapabilityError(`无效的 Tab ID: ${targetId}`);
899
+ }
900
+ const parsed = Number(targetId);
901
+ if (!Number.isSafeInteger(parsed)) {
708
902
  throw new DriverCapabilityError(`无效的 Tab ID: ${targetId}`);
709
903
  }
710
904
  return parsed;
711
905
  }
712
906
  tabToTarget(tab) {
713
907
  return {
714
- id: tab.id,
908
+ ...tab,
715
909
  targetId: String(tab.id),
716
- url: tab.url,
717
- title: tab.title,
718
910
  type: 'page',
719
- active: tab.active,
720
- windowId: tab.windowId,
721
- index: tab.index,
722
- groupId: tab.groupId,
723
- pinned: tab.pinned,
724
- incognito: tab.incognito,
725
- managed: tab.managed,
726
- status: tab.status,
727
911
  };
728
912
  }
729
913
  updateState(page) {