@pyrokine/mcp-chrome 2.4.4 → 3.0.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 (118) hide show
  1. package/README.md +495 -115
  2. package/README_zh.md +423 -128
  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 +105 -15
  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 +22 -4
  20. package/dist/core/errors.d.ts.map +1 -1
  21. package/dist/core/errors.js +90 -7
  22. package/dist/core/errors.js.map +1 -1
  23. package/dist/core/locator.d.ts +7 -0
  24. package/dist/core/locator.d.ts.map +1 -1
  25. package/dist/core/locator.js +54 -29
  26. package/dist/core/locator.js.map +1 -1
  27. package/dist/core/os-mouse.d.ts +15 -2
  28. package/dist/core/os-mouse.d.ts.map +1 -1
  29. package/dist/core/os-mouse.js +52 -8
  30. package/dist/core/os-mouse.js.map +1 -1
  31. package/dist/core/session.d.ts +39 -22
  32. package/dist/core/session.d.ts.map +1 -1
  33. package/dist/core/session.js +632 -153
  34. package/dist/core/session.js.map +1 -1
  35. package/dist/core/types.d.ts +2 -0
  36. package/dist/core/types.d.ts.map +1 -1
  37. package/dist/core/types.js.map +1 -1
  38. package/dist/core/unified-session.d.ts +105 -27
  39. package/dist/core/unified-session.d.ts.map +1 -1
  40. package/dist/core/unified-session.js +554 -138
  41. package/dist/core/unified-session.js.map +1 -1
  42. package/dist/core/utils.d.ts +5 -0
  43. package/dist/core/utils.d.ts.map +1 -1
  44. package/dist/core/utils.js +475 -54
  45. package/dist/core/utils.js.map +1 -1
  46. package/dist/extension/bridge.d.ts +49 -39
  47. package/dist/extension/bridge.d.ts.map +1 -1
  48. package/dist/extension/bridge.js +318 -131
  49. package/dist/extension/bridge.js.map +1 -1
  50. package/dist/extension/http-server.d.ts +3 -0
  51. package/dist/extension/http-server.d.ts.map +1 -1
  52. package/dist/extension/http-server.js +28 -2
  53. package/dist/extension/http-server.js.map +1 -1
  54. package/dist/index.js +7 -0
  55. package/dist/index.js.map +1 -1
  56. package/dist/tools/browse.d.ts.map +1 -1
  57. package/dist/tools/browse.js +248 -172
  58. package/dist/tools/browse.js.map +1 -1
  59. package/dist/tools/challenge.d.ts +1 -1
  60. package/dist/tools/challenge.d.ts.map +1 -1
  61. package/dist/tools/challenge.js +86 -51
  62. package/dist/tools/challenge.js.map +1 -1
  63. package/dist/tools/cookies.d.ts.map +1 -1
  64. package/dist/tools/cookies.js +5 -3
  65. package/dist/tools/cookies.js.map +1 -1
  66. package/dist/tools/diagnostics.d.ts +3 -3
  67. package/dist/tools/diagnostics.d.ts.map +1 -1
  68. package/dist/tools/diagnostics.js +13 -12
  69. package/dist/tools/diagnostics.js.map +1 -1
  70. package/dist/tools/evaluate.d.ts.map +1 -1
  71. package/dist/tools/evaluate.js +67 -26
  72. package/dist/tools/evaluate.js.map +1 -1
  73. package/dist/tools/extract.d.ts.map +1 -1
  74. package/dist/tools/extract.js +137 -197
  75. package/dist/tools/extract.js.map +1 -1
  76. package/dist/tools/input.d.ts +1 -1
  77. package/dist/tools/input.d.ts.map +1 -1
  78. package/dist/tools/input.js +445 -197
  79. package/dist/tools/input.js.map +1 -1
  80. package/dist/tools/logs.d.ts.map +1 -1
  81. package/dist/tools/logs.js +5 -5
  82. package/dist/tools/logs.js.map +1 -1
  83. package/dist/tools/manage.d.ts.map +1 -1
  84. package/dist/tools/manage.js +395 -86
  85. package/dist/tools/manage.js.map +1 -1
  86. package/dist/tools/page-context.d.ts +17 -0
  87. package/dist/tools/page-context.d.ts.map +1 -0
  88. package/dist/tools/page-context.js +103 -0
  89. package/dist/tools/page-context.js.map +1 -0
  90. package/dist/tools/png.d.ts +5 -0
  91. package/dist/tools/png.d.ts.map +1 -1
  92. package/dist/tools/png.js +84 -19
  93. package/dist/tools/png.js.map +1 -1
  94. package/dist/tools/post-condition.d.ts.map +1 -1
  95. package/dist/tools/post-condition.js +24 -7
  96. package/dist/tools/post-condition.js.map +1 -1
  97. package/dist/tools/schema.d.ts +9 -0
  98. package/dist/tools/schema.d.ts.map +1 -1
  99. package/dist/tools/schema.js +15 -0
  100. package/dist/tools/schema.js.map +1 -1
  101. package/dist/tools/target-diagnostics.d.ts +9 -1
  102. package/dist/tools/target-diagnostics.d.ts.map +1 -1
  103. package/dist/tools/target-diagnostics.js +89 -33
  104. package/dist/tools/target-diagnostics.js.map +1 -1
  105. package/dist/tools/wait.d.ts.map +1 -1
  106. package/dist/tools/wait.js +38 -32
  107. package/dist/tools/wait.js.map +1 -1
  108. package/extension/dist/assets/content.ts-loader-DUWbDHRS.js +13 -0
  109. package/extension/dist/assets/content.ts-qe6IB5DK.js +13 -0
  110. package/extension/dist/assets/{index.ts-Bqcu2qiN.js → index.ts-D7_LCUoV.js} +2477 -2201
  111. package/extension/dist/assets/page-scripts-D508WLkW.js +1378 -0
  112. package/extension/dist/assets/{popup.html-B81xccfq.js → popup.html-B-eVq48O.js} +54 -5
  113. package/extension/dist/manifest.json +4 -3
  114. package/extension/dist/service-worker-loader.js +1 -1
  115. package/extension/dist/src/popup/popup.html +11 -1
  116. package/package.json +16 -8
  117. package/scripts/start-chrome.ps1 +58 -0
  118. package/extension/dist/assets/content.ts-Cj_iiU2s.js +0 -25
@@ -5,12 +5,15 @@
5
5
  * 1. Extension 模式:通过 Chrome Extension 操作用户浏览器(推荐)
6
6
  * 2. CDP 模式:通过 Chrome DevTools Protocol 操作(Fallback)
7
7
  */
8
+ import { AsyncLocalStorage } from 'node:async_hooks';
8
9
  import { ExtensionBridge } from '../extension/index.js';
9
10
  import { DriverCapabilityError, } from './browser-driver.js';
10
- import { OsMouseError } from './errors.js';
11
+ import { OsMouseError, PagePreconditionError, setErrorPageContext, StructuredToolError, TargetNotFoundError, TimeoutError, } from './errors.js';
11
12
  import { isExtensionDisconnected } from './extension-errors.js';
12
13
  import { asViewportMetrics, osLeftClick, resolveTurnstileOsClickPoint, } from './os-mouse.js';
13
14
  import { getKeyDefinition, getSession as getCdpSession } from './session.js';
15
+ import { DEFAULT_TIMEOUT } from './types.js';
16
+ import { remainingNavigationTimeout, waitForNavigationQueue, withNavigationBudget } from './utils.js';
14
17
  import { EvaluateResultTooLargeError, extractCdpValue, formatCdpException, isKnownNonSerializableRemoteObject, MODIFIER_KEYS, NonSerializableEvaluateResultError, } from './types.js';
15
18
  class UnifiedSessionManager {
16
19
  static instance;
@@ -18,6 +21,7 @@ class UnifiedSessionManager {
18
21
  static CDP_MATERIALIZE_MAX_DEPTH = 8;
19
22
  static CDP_MATERIALIZE_MAX_NODES = 2000;
20
23
  static CDP_MATERIALIZE_MAX_CHARS = 1_000_000;
24
+ static CDP_MATERIALIZE_MAX_FILE_CHARS = 16 * 1024 * 1024;
21
25
  extensionBridge = null;
22
26
  inputMode = 'precise'; // 默认使用 precise 模式,可绕过 CSP 限制
23
27
  currentMousePosition = { x: 0, y: 0 }; // 跟踪鼠标位置
@@ -31,9 +35,11 @@ class UnifiedSessionManager {
31
35
  extensionChallengeStateUnsupported = false;
32
36
  unsupportedChallengeStateBundleHash = null;
33
37
  tabSwitchLock = Promise.resolve(); // 串行化 tab 切换,防止并发竞态
38
+ tabLockContext = new AsyncLocalStorage();
34
39
  requireExtension = false; // 指定 tabId 或 frame 时为 true,禁止 CDP 回退
35
40
  currentFrameOffset = null; // iframe 在主页面的偏移量(withFrame 期间有效)
36
41
  lastEvaluationMetadata;
42
+ pageMetadata = new Map();
37
43
  constructor() { }
38
44
  static getInstance() {
39
45
  if (!UnifiedSessionManager.instance) {
@@ -62,6 +68,10 @@ class UnifiedSessionManager {
62
68
  * 获取当前连接模式
63
69
  */
64
70
  getMode() {
71
+ const scopedMode = this.tabLockContext.getStore()?.mode;
72
+ if (scopedMode) {
73
+ return scopedMode;
74
+ }
65
75
  if (this.activeMode === 'extension' && this.extensionBridge?.isConnected()) {
66
76
  return 'extension';
67
77
  }
@@ -80,9 +90,11 @@ class UnifiedSessionManager {
80
90
  this.activeMode = null;
81
91
  return 'none';
82
92
  }
83
- setActiveMode(mode, cdpExplicitlySelected = false) {
84
- this.activeMode = mode;
85
- this.cdpExplicitlySelected = mode === 'cdp' && cdpExplicitlySelected;
93
+ async setActiveMode(mode, cdpExplicitlySelected = false) {
94
+ await this.withTabLock(async () => {
95
+ this.activeMode = mode;
96
+ this.cdpExplicitlySelected = mode === 'cdp' && cdpExplicitlySelected;
97
+ });
86
98
  }
87
99
  /**
88
100
  * 获取当前输入模式
@@ -100,6 +112,35 @@ class UnifiedSessionManager {
100
112
  }
101
113
  return null;
102
114
  }
115
+ getPageMetadata(targetId) {
116
+ return (this.pageMetadata.get(this.metadataKey(targetId)) ?? {
117
+ createdBy: 'unknown',
118
+ createdAt: null,
119
+ lastUsedAt: null,
120
+ });
121
+ }
122
+ async setPageMetadata(targetId, updates) {
123
+ await this.getPageSnapshot(targetId);
124
+ const metadata = { ...this.getPageMetadata(targetId) };
125
+ if (updates.taskHint !== undefined) {
126
+ if (updates.taskHint === null) {
127
+ delete metadata.taskHint;
128
+ }
129
+ else {
130
+ metadata.taskHint = updates.taskHint;
131
+ }
132
+ }
133
+ if (updates.note !== undefined) {
134
+ if (updates.note === null) {
135
+ delete metadata.note;
136
+ }
137
+ else {
138
+ metadata.note = updates.note;
139
+ }
140
+ }
141
+ this.pageMetadata.set(this.metadataKey(targetId), metadata);
142
+ return metadata;
143
+ }
103
144
  /**
104
145
  * 获取当前 iframe 在主页面的偏移量(仅 withFrame 期间有效)
105
146
  */
@@ -158,6 +199,7 @@ class UnifiedSessionManager {
158
199
  });
159
200
  this.activeMode = 'extension';
160
201
  this.cdpExplicitlySelected = false;
202
+ this.recordPageUse(result.targetId, true);
161
203
  return {
162
204
  targetId: result.targetId,
163
205
  type: result.type ?? 'page',
@@ -171,6 +213,7 @@ class UnifiedSessionManager {
171
213
  const target = await getCdpSession().launch(options);
172
214
  this.activeMode = 'cdp';
173
215
  this.cdpExplicitlySelected = false;
216
+ this.recordPageUse(target.targetId, target.targetCreated ?? target.reused !== true);
174
217
  return {
175
218
  ...target,
176
219
  mode: 'cdp',
@@ -179,52 +222,61 @@ class UnifiedSessionManager {
179
222
  /**
180
223
  * 列出所有页面
181
224
  */
182
- async listTargets() {
225
+ async listTargets(timeout) {
183
226
  const mode = this.getMode();
184
227
  if (mode === 'none') {
185
228
  return [];
186
229
  }
187
- const driver = await this.getDriver();
188
- const targets = await driver.listTargets();
189
- return targets.map((t) => ({
190
- targetId: t.targetId ?? String(t.id),
191
- type: t.type ?? 'page',
192
- url: t.url,
193
- title: t.title,
230
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
231
+ const driver = await this.getDriver(timeout);
232
+ const targets = await driver.listTargets(deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
233
+ const liveKeys = new Set(targets.map((t) => `${mode}:${t.targetId ?? String(t.id)}`));
234
+ for (const key of this.pageMetadata.keys()) {
235
+ if (key.startsWith(`${mode}:`) && !liveKeys.has(key)) {
236
+ this.pageMetadata.delete(key);
237
+ }
238
+ }
239
+ return targets.map(({ id, ...target }) => ({
240
+ ...target,
241
+ targetId: target.targetId ?? String(id),
242
+ type: target.type ?? 'page',
194
243
  mode,
195
- isActive: t.active ?? false,
196
- managed: t.managed,
197
- windowId: t.windowId,
198
- index: t.index,
199
- pinned: t.pinned,
200
- incognito: t.incognito,
201
- status: t.status,
244
+ ...(mode === 'extension' ? { isActive: target.active ?? false } : {}),
245
+ metadata: this.getPageMetadata(target.targetId ?? String(id)),
202
246
  }));
203
247
  }
204
- async listTopology() {
248
+ async listTopology(timeout) {
205
249
  const mode = this.getMode();
206
250
  if (mode === 'none') {
207
251
  return null;
208
252
  }
209
- const driver = await this.getDriver();
253
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
254
+ const driver = await this.getDriver(timeout);
210
255
  if (!driver.listWindows) {
211
256
  return null;
212
257
  }
213
- return driver.listWindows();
258
+ return driver.listWindows(deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
259
+ }
260
+ async setReadAccess(targetId, allow) {
261
+ const driver = await this.getDriver();
262
+ if (!driver.setReadAccess) {
263
+ throw new DriverCapabilityError('普通只读授权仅支持 Extension 模式,未执行');
264
+ }
265
+ return this.withTabLock(() => driver.setReadAccess(targetId, allow));
214
266
  }
215
267
  async adoptPage(targetId) {
216
268
  const driver = await this.getDriver();
217
269
  if (!driver.adoptPage) {
218
270
  throw new DriverCapabilityError('adoptPage 仅支持 Extension 模式');
219
271
  }
220
- return driver.adoptPage(targetId);
272
+ return this.withTabLock(() => driver.adoptPage(targetId));
221
273
  }
222
274
  async releasePage(targetId) {
223
275
  const driver = await this.getDriver();
224
276
  if (!driver.releasePage) {
225
277
  throw new DriverCapabilityError('releasePage 仅支持 Extension 模式');
226
278
  }
227
- return driver.releasePage(targetId);
279
+ return this.withTabLock(() => driver.releasePage(targetId));
228
280
  }
229
281
  async movePage(targetId, options) {
230
282
  const driver = await this.getDriver();
@@ -233,6 +285,41 @@ class UnifiedSessionManager {
233
285
  }
234
286
  return driver.movePage(targetId, options);
235
287
  }
288
+ async updatePage(targetId, options) {
289
+ const driver = await this.getDriver();
290
+ if (!driver.updatePage) {
291
+ throw new DriverCapabilityError('updatePage 原生 tab 配置仅支持 Extension 模式');
292
+ }
293
+ return this.withTabLock(() => driver.updatePage(targetId, options));
294
+ }
295
+ async groupPages(targetIds, options) {
296
+ const driver = await this.getDriver();
297
+ if (!driver.groupPages) {
298
+ throw new DriverCapabilityError('groupPages 仅支持 Extension 模式');
299
+ }
300
+ return this.withTabLock(() => driver.groupPages(targetIds, options));
301
+ }
302
+ async ungroupPages(targetIds) {
303
+ const driver = await this.getDriver();
304
+ if (!driver.ungroupPages) {
305
+ throw new DriverCapabilityError('ungroupPages 仅支持 Extension 模式');
306
+ }
307
+ return this.withTabLock(() => driver.ungroupPages(targetIds));
308
+ }
309
+ async updateGroup(groupId, options) {
310
+ const driver = await this.getDriver();
311
+ if (!driver.updateGroup) {
312
+ throw new DriverCapabilityError('updateGroup 仅支持 Extension 模式');
313
+ }
314
+ return this.withTabLock(() => driver.updateGroup(groupId, options));
315
+ }
316
+ async moveGroup(groupId, options) {
317
+ const driver = await this.getDriver();
318
+ if (!driver.moveGroup) {
319
+ throw new DriverCapabilityError('moveGroup 仅支持 Extension 模式');
320
+ }
321
+ return this.withTabLock(() => driver.moveGroup(groupId, options));
322
+ }
236
323
  async reorderPage(targetId, index) {
237
324
  const driver = await this.getDriver();
238
325
  if (!driver.reorderPage) {
@@ -249,11 +336,10 @@ class UnifiedSessionManager {
249
336
  }
250
337
  async activatePageWithAffected(targetId) {
251
338
  const driver = await this.getDriver();
252
- const bridge = driver;
253
- if (!bridge.activatePageWithAffected) {
254
- throw new DriverCapabilityError('activatePage 受控 affected 返回仅支持 Extension 模式');
339
+ if (!driver.activatePageWithAffected) {
340
+ throw new DriverCapabilityError('当前浏览器驱动不支持激活页面状态返回');
255
341
  }
256
- return this.withTabLock(() => bridge.activatePageWithAffected(targetId));
342
+ return this.withTabLock(() => driver.activatePageWithAffected(targetId));
257
343
  }
258
344
  async focusWindow(windowId) {
259
345
  const driver = await this.getDriver();
@@ -269,40 +355,72 @@ class UnifiedSessionManager {
269
355
  }
270
356
  return driver.resizeWindow(windowId, options);
271
357
  }
358
+ async updateWindow(windowId, options) {
359
+ const driver = await this.getDriver();
360
+ if (!driver.updateWindow) {
361
+ throw new DriverCapabilityError('updateWindow 仅支持 Extension 模式');
362
+ }
363
+ return this.withTabLock(() => driver.updateWindow(windowId, options));
364
+ }
272
365
  async newWindow(options) {
273
366
  const driver = await this.getDriver();
274
367
  if (!driver.newWindow) {
275
368
  throw new DriverCapabilityError('newWindow 仅支持 Extension 模式');
276
369
  }
277
- return this.withTabLock(() => driver.newWindow(options));
370
+ return this.withTabLock(async () => {
371
+ const result = await driver.newWindow(options);
372
+ if (result.after && 'tabs' in result.after) {
373
+ for (const tab of result.after.tabs) {
374
+ const targetId = tab.targetId ?? String(tab.id);
375
+ this.recordPageUse(targetId, targetId !== options.targetId);
376
+ }
377
+ }
378
+ else if (result.targetId) {
379
+ this.recordPageUse(result.targetId, options.targetId === undefined);
380
+ }
381
+ return result;
382
+ });
278
383
  }
279
384
  async closeWindow(windowId) {
280
385
  const driver = await this.getDriver();
281
386
  if (!driver.closeWindow) {
282
387
  throw new DriverCapabilityError('closeWindow 仅支持 Extension 模式');
283
388
  }
284
- return this.withTabLock(() => driver.closeWindow(windowId));
389
+ return this.withTabLock(async () => {
390
+ const result = await driver.closeWindow(windowId);
391
+ if (result.before && 'tabs' in result.before) {
392
+ for (const tab of result.before.tabs) {
393
+ this.pageMetadata.delete(this.metadataKey(tab.targetId ?? String(tab.id)));
394
+ }
395
+ }
396
+ return result;
397
+ });
285
398
  }
286
399
  /**
287
400
  * 导航到 URL
288
401
  */
289
402
  async navigate(url, options = {}) {
290
- const driver = await this.getDriver(options.timeout);
291
- await this.withTabLock(() => driver.navigate(url, { wait: options.wait, timeout: options.timeout }));
292
- }
293
- async goBack(timeout) {
294
- const driver = await this.getDriver(timeout);
295
- const result = await this.withTabLock(() => driver.goBack(timeout));
403
+ const deadline = Date.now() + (options.timeout ?? DEFAULT_TIMEOUT);
404
+ const driver = await this.getDriver(remainingNavigationTimeout(deadline));
405
+ const navigate = () => driver.navigate(url, { wait: options.wait, timeout: remainingNavigationTimeout(deadline) });
406
+ await (this.getMode() === 'extension' ? this.withTabLock(navigate, deadline) : navigate());
407
+ }
408
+ async goBack(timeout = DEFAULT_TIMEOUT) {
409
+ const deadline = Date.now() + timeout;
410
+ const driver = await this.getDriver(remainingNavigationTimeout(deadline));
411
+ const result = await this.withTabLock(() => driver.goBack(remainingNavigationTimeout(deadline)), deadline);
296
412
  return { navigated: result.navigated };
297
413
  }
298
- async goForward(timeout) {
299
- const driver = await this.getDriver(timeout);
300
- const result = await this.withTabLock(() => driver.goForward(timeout));
414
+ async goForward(timeout = DEFAULT_TIMEOUT) {
415
+ const deadline = Date.now() + timeout;
416
+ const driver = await this.getDriver(remainingNavigationTimeout(deadline));
417
+ const result = await this.withTabLock(() => driver.goForward(remainingNavigationTimeout(deadline)), deadline);
301
418
  return { navigated: result.navigated };
302
419
  }
303
420
  async reload(options = {}) {
304
- const driver = await this.getDriver(options.timeout);
305
- await this.withTabLock(() => driver.reload(options.ignoreCache, options.waitUntil, options.timeout));
421
+ const deadline = Date.now() + (options.timeout ?? DEFAULT_TIMEOUT);
422
+ const driver = await this.getDriver(remainingNavigationTimeout(deadline));
423
+ await this.withTabLock(() => driver.reload(options.ignoreCache, options.waitUntil, remainingNavigationTimeout(deadline)), deadline);
306
424
  }
307
425
  /**
308
426
  * 读取页面(Accessibility Tree)
@@ -329,26 +447,44 @@ class UnifiedSessionManager {
329
447
  *
330
448
  * 返回结构化结果,让调用方知道操作是否真正生效
331
449
  */
332
- async actionableClick(refId, force) {
450
+ async actionableClick(refId, force = false, button = 'left', clickCount = 1, point) {
333
451
  const driver = await this.getDriver();
334
- return driver.actionableClick(refId, force);
452
+ if (point) {
453
+ this.currentMousePosition = { x: point.x, y: point.y };
454
+ }
455
+ if (button === 'left' && clickCount === 1) {
456
+ return driver.actionableClick(refId, force);
457
+ }
458
+ if (!force) {
459
+ const result = await driver.checkActionability(refId);
460
+ if (!result.success)
461
+ return result;
462
+ }
463
+ if (force) {
464
+ const { x, y } = this.currentMousePosition;
465
+ await driver.stealthClick(x, y, button, clickCount, refId);
466
+ }
467
+ else {
468
+ await this.mouseClick(button, clickCount, refId);
469
+ }
470
+ return { success: true };
335
471
  }
336
472
  /**
337
- * dispatch 模式输入(ISOLATED 世界,兼容 React/Vue 受控组件)
473
+ * dispatch 模式输入(Extension MAIN 世界,兼容 React/Vue 受控组件)
338
474
  */
339
475
  async dispatchInput(refId, text) {
340
476
  const driver = await this.getDriver();
341
477
  return driver.dispatchInput(refId, text);
342
478
  }
343
479
  /**
344
- * HTML5 drag/drop(ISOLATED 世界,通过 refId 访问 __mcpElementMap 中的元素引用)
480
+ * HTML5 drag/drop(Extension MAIN 世界,与 refId 创建侧共享 __mcpElementMap)
345
481
  */
346
482
  async dragAndDrop(srcRefId, dstRefId) {
347
483
  const driver = await this.getDriver();
348
484
  return driver.dragAndDrop(srcRefId, dstRefId);
349
485
  }
350
486
  /**
351
- * 获取元素 computed style(ISOLATED 世界)
487
+ * 获取元素 computed style(Extension 受控页为 MAIN,只读 documentId 授权为 ISOLATED)
352
488
  */
353
489
  async getComputedStyle(refId, prop) {
354
490
  const driver = await this.getDriver();
@@ -391,7 +527,7 @@ class UnifiedSessionManager {
391
527
  const entryStart = Date.now();
392
528
  this.lastEvaluationMetadata = undefined;
393
529
  const effectiveMode = mode ?? this.inputMode;
394
- const hasArgs = args && args.length > 0;
530
+ const hasArgs = args !== undefined;
395
531
  // stealth 模式:args 只能通过字符串拼接(chrome.scripting 不支持协议级参数传递)
396
532
  let expression = code;
397
533
  if (hasArgs && effectiveMode === 'stealth') {
@@ -415,7 +551,7 @@ class UnifiedSessionManager {
415
551
  }
416
552
  // Extension 路径
417
553
  if (effectiveMode === 'precise') {
418
- return this.evaluateViaExtensionPrecise(code, expression, args, timeout, options.staleContextRetry ?? 'never');
554
+ return this.evaluateViaExtensionPrecise(code, expression, args, timeout, options);
419
555
  }
420
556
  return this.evaluateViaExtensionStealth(expression, timeout);
421
557
  }
@@ -456,6 +592,24 @@ class UnifiedSessionManager {
456
592
  async getHtml(selector, outer = true) {
457
593
  return (await this.getDriver()).getPageHtml(selector, outer);
458
594
  }
595
+ async getTextByRef(refId) {
596
+ return this.extensionReadBridge().getText(undefined, refId);
597
+ }
598
+ async getHtmlByRef(refId, outer = true) {
599
+ return this.extensionReadBridge().getHtml(undefined, outer, refId);
600
+ }
601
+ async getAttributeByRef(refId, attribute) {
602
+ return this.extensionReadBridge().getAttribute(undefined, refId, attribute);
603
+ }
604
+ async getComputedStyleByRef(refId, prop) {
605
+ return this.extensionReadBridge().getComputedStyle(refId, prop);
606
+ }
607
+ async findAtPoint(x, y, matchIndex, timeout) {
608
+ return this.extensionReadBridge().find(undefined, undefined, undefined, timeout, { x, y }, matchIndex);
609
+ }
610
+ async getHtmlWithImagesByRef(refId) {
611
+ return this.extensionReadBridge().getHtmlWithImages(undefined, true, refId);
612
+ }
459
613
  /**
460
614
  * 获取页面 HTML + 图片元信息
461
615
  */
@@ -468,7 +622,13 @@ class UnifiedSessionManager {
468
622
  */
469
623
  async getMetadata() {
470
624
  const driver = await this.getDriver();
471
- return driver.getMetadata();
625
+ const targetId = this.getCurrentTargetId();
626
+ const metadata = await driver.getMetadata();
627
+ const target = (await this.listTargets()).find((page) => page.targetId === targetId);
628
+ if (!target) {
629
+ throw new TargetNotFoundError(targetId ?? 'current');
630
+ }
631
+ return { ...metadata, managed: target.managed ?? false, metadata: target.metadata };
472
632
  }
473
633
  /**
474
634
  * 批量从浏览器缓存获取资源内容
@@ -518,7 +678,10 @@ class UnifiedSessionManager {
518
678
  * @param xpath XPath 表达式
519
679
  * @param timeout 端到端预算(毫秒),包含连接等待和请求超时,传给 bridge.find → sendCommand
520
680
  */
521
- async find(selector, text, xpath, timeout) {
681
+ async find(selector, text, xpath, timeout, matchIndex) {
682
+ if (matchIndex !== undefined) {
683
+ return this.extensionReadBridge().find(selector, text, xpath, timeout, undefined, matchIndex);
684
+ }
522
685
  if (timeout !== undefined) {
523
686
  // 轮询上下文:快速失败,端到端预算受控
524
687
  if (this.isExtensionConnected()) {
@@ -567,12 +730,14 @@ class UnifiedSessionManager {
567
730
  /**
568
731
  * 创建新页面
569
732
  */
570
- async newPage(url) {
733
+ async newPage(url, options, timeout) {
571
734
  const driver = await this.getDriver();
572
735
  const isExt = this.isExtensionConnected();
573
736
  const op = async () => {
574
- const result = await driver.newPage(url);
737
+ const result = await driver.newPage(url, timeout, options);
738
+ this.recordPageUse(result.targetId, true);
575
739
  return {
740
+ ...result,
576
741
  targetId: result.targetId,
577
742
  type: result.type ?? 'page',
578
743
  url: result.url,
@@ -587,9 +752,16 @@ class UnifiedSessionManager {
587
752
  * 关闭页面
588
753
  */
589
754
  async closePage(targetId) {
755
+ if (!targetId) {
756
+ throw new DriverCapabilityError('closePage 需要显式 targetId,未关闭页面');
757
+ }
590
758
  const driver = await this.getDriver();
591
759
  const isExt = this.isExtensionConnected();
592
- const op = () => driver.closePage(targetId);
760
+ const op = async () => {
761
+ const result = await driver.closePage(targetId);
762
+ this.pageMetadata.delete(this.metadataKey(targetId));
763
+ return result;
764
+ };
593
765
  if (isExt) {
594
766
  return this.withTabLock(op);
595
767
  }
@@ -622,6 +794,40 @@ class UnifiedSessionManager {
622
794
  else {
623
795
  await op();
624
796
  }
797
+ this.recordPageUse(targetId);
798
+ }
799
+ /**
800
+ * 串行化所有 tab 切换操作,防止并发请求互相覆盖 currentTabId,
801
+ * 调用者:selectPage/activatePage/adoptPage/releasePage/newPage/closePage/navigate/reload/launch/withTabId
802
+ *
803
+ * 同一请求内的嵌套调用可重入,恢复状态只保存在当前请求的 AsyncLocalStorage 中
804
+ */
805
+ async withTabLock(fn, deadline) {
806
+ if (this.tabLockContext.getStore()?.session === this) {
807
+ if (deadline !== undefined) {
808
+ remainingNavigationTimeout(deadline);
809
+ }
810
+ return fn();
811
+ }
812
+ const previousLock = this.tabSwitchLock;
813
+ let releaseLock;
814
+ this.tabSwitchLock = new Promise((resolve) => {
815
+ releaseLock = resolve;
816
+ });
817
+ let acquired = false;
818
+ try {
819
+ await waitForNavigationQueue(previousLock, deadline);
820
+ acquired = true;
821
+ return await this.tabLockContext.run({ session: this }, fn);
822
+ }
823
+ finally {
824
+ if (acquired) {
825
+ releaseLock();
826
+ }
827
+ else {
828
+ void previousLock.then(releaseLock, releaseLock);
829
+ }
830
+ }
625
831
  }
626
832
  /**
627
833
  * 临时切换操作目标 tab,执行完后恢复
@@ -632,44 +838,182 @@ class UnifiedSessionManager {
632
838
  * 即使不传 tabId,也需要加锁:fn() 内调用 bridge 方法会读取 currentTabId,
633
839
  * 不加锁则并发的 withTabId(someId, ...) 可能在 fn() 执行中途修改 currentTabId
634
840
  */
635
- async withTabId(tabId, fn) {
636
- // Extension 未连接时不需要锁和 tab 切换(CDP 模式无 currentTabId 竞态)
637
- if (!this.extensionBridge?.isConnected()) {
638
- if (tabId) {
841
+ async withTabId(targetId, fn, deadline) {
842
+ return this.withTabLock(async () => {
843
+ const remaining = () => (deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
844
+ const mode = this.getMode();
845
+ const scope = this.tabLockContext.getStore();
846
+ if (mode !== 'none') {
847
+ scope.mode = mode;
848
+ }
849
+ if (!targetId) {
850
+ const current = this.getCurrentTargetId();
851
+ if (current) {
852
+ this.recordPageUse(current);
853
+ }
639
854
  const previousRequireExtension = this.requireExtension;
640
- this.requireExtension = true;
855
+ const previousCdpSelection = this.cdpExplicitlySelected;
856
+ if (mode === 'extension') {
857
+ this.requireExtension = true;
858
+ }
859
+ else if (mode === 'cdp') {
860
+ this.cdpExplicitlySelected = true;
861
+ }
641
862
  try {
642
- this.assertCdpFallbackAllowed();
863
+ return await fn();
643
864
  }
644
865
  finally {
645
866
  this.requireExtension = previousRequireExtension;
867
+ this.cdpExplicitlySelected = previousCdpSelection;
646
868
  }
647
869
  }
648
- return fn();
870
+ if (mode === 'none') {
871
+ throw new DriverCapabilityError('浏览器未连接,无法选择目标页面');
872
+ }
873
+ const driver = mode === 'extension' ? this.extensionBridge : getCdpSession();
874
+ const targets = await driver.listTargets(remaining());
875
+ if (!targets.some((target) => (target.targetId ?? String(target.id)) === targetId)) {
876
+ throw new DriverCapabilityError(`目标页面 ${targetId} 不存在于当前 ${mode} 连接`);
877
+ }
878
+ const previousId = driver.getCurrentTargetId();
879
+ const previousRequireExtension = this.requireExtension;
880
+ const previousCdpSelection = this.cdpExplicitlySelected;
881
+ const previousMode = this.activeMode;
882
+ if (mode === 'extension') {
883
+ this.requireExtension = true;
884
+ }
885
+ else {
886
+ this.cdpExplicitlySelected = true;
887
+ }
888
+ try {
889
+ if (targetId !== previousId) {
890
+ await driver.selectPage(targetId, remaining());
891
+ }
892
+ this.activeMode = mode;
893
+ this.recordPageUse(targetId);
894
+ return await fn();
895
+ }
896
+ finally {
897
+ this.requireExtension = previousRequireExtension;
898
+ this.cdpExplicitlySelected = previousCdpSelection;
899
+ this.activeMode = previousMode;
900
+ if (targetId !== previousId) {
901
+ const restoration = {
902
+ status: previousId ? 'restored' : 'cleared',
903
+ previousTargetId: previousId,
904
+ temporaryTargetId: targetId,
905
+ currentTargetId: null,
906
+ };
907
+ let clearTarget = true;
908
+ try {
909
+ if (previousId) {
910
+ const targets = await driver.listTargets(remaining());
911
+ if (targets.some((target) => (target.targetId ?? String(target.id)) === previousId)) {
912
+ await driver.selectPage(previousId, remaining());
913
+ clearTarget = false;
914
+ }
915
+ else {
916
+ restoration.status = 'previous_target_closed';
917
+ }
918
+ }
919
+ }
920
+ catch (error) {
921
+ restoration.status = 'failed';
922
+ restoration.error = error instanceof Error ? error.message : String(error);
923
+ }
924
+ if (clearTarget) {
925
+ try {
926
+ if (mode === 'extension') {
927
+ driver.setCurrentTargetId(null);
928
+ }
929
+ else {
930
+ await getCdpSession().deselectPage(deadline === undefined ? undefined : Math.max(0, deadline - Date.now()));
931
+ }
932
+ }
933
+ catch (error) {
934
+ const message = error instanceof Error ? error.message : String(error);
935
+ if (restoration.error) {
936
+ restoration.cleanupError = message;
937
+ }
938
+ else {
939
+ restoration.status = 'failed';
940
+ restoration.error = message;
941
+ }
942
+ }
943
+ }
944
+ restoration.currentTargetId = driver.getCurrentTargetId();
945
+ this.tabLockContext.getStore().targetRestoration = restoration;
946
+ }
947
+ }
948
+ }, deadline);
949
+ }
950
+ getTargetRestoration() {
951
+ return this.tabLockContext.getStore()?.targetRestoration;
952
+ }
953
+ async getPageSnapshot(targetId, timeout) {
954
+ const mode = this.getMode();
955
+ if (mode === 'none') {
956
+ throw new DriverCapabilityError('浏览器未连接,无法读取页面状态');
649
957
  }
650
- if (!tabId) {
651
- // 不切换 tab,但需要加锁保护 currentTabId 不被并发修改
652
- return this.withTabLock(fn);
958
+ const id = targetId ?? this.getCurrentTargetId();
959
+ if (!id) {
960
+ throw new DriverCapabilityError('没有操作目标,请先选择页面');
961
+ }
962
+ const snapshot = mode === 'extension'
963
+ ? await this.extensionBridge.getPageSnapshot(id, timeout)
964
+ : await getCdpSession().getPageSnapshot(id, timeout);
965
+ this.recordPageUse(id);
966
+ return snapshot;
967
+ }
968
+ async withPageCondition(condition, fn, deadline) {
969
+ if (condition.expectedUrl === undefined && condition.expectedRevision === undefined) {
970
+ return fn();
653
971
  }
654
- const driver = this.extensionBridge;
655
972
  return this.withTabLock(async () => {
656
- const previousTargetId = driver.getCurrentTargetId();
657
- // 临时切换用 setCurrentTargetId,跳过 managed 校验(tabId 仅用于读取/执行,不改变持久 attach 目标)
658
- driver.setCurrentTargetId(tabId);
659
- // tabId 明确指定时,禁止 CDP 回退(CDP 不感知 Extension tab)
973
+ const mode = this.getMode();
974
+ const targetId = condition.targetId ?? this.getCurrentTargetId();
975
+ if (mode === 'none' || !targetId) {
976
+ throw new DriverCapabilityError('没有操作目标,请先选择页面');
977
+ }
978
+ const driver = mode === 'extension' ? this.extensionBridge : getCdpSession();
660
979
  const previousRequireExtension = this.requireExtension;
661
- const previousActiveMode = this.activeMode;
662
- this.requireExtension = true;
663
- this.activeMode = 'extension';
980
+ const previousCdpSelection = this.cdpExplicitlySelected;
981
+ const previousMode = this.activeMode;
982
+ if (mode === 'extension') {
983
+ this.requireExtension = true;
984
+ }
985
+ else {
986
+ this.cdpExplicitlySelected = true;
987
+ }
664
988
  try {
989
+ const snapshot = await driver.getPageSnapshot(targetId, deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
990
+ if (snapshot.revision === null) {
991
+ throw new StructuredToolError('DRIVER_CAPABILITY_ERROR', '当前 Extension 不支持原子页面条件,未执行操作', '更新 Extension 后再使用 expectedUrl 或 expectedRevision', { targetId, actionExecuted: false, actionStatus: 'not_started', failureStage: 'precondition' });
992
+ }
993
+ if ((condition.expectedUrl !== undefined && snapshot.url !== condition.expectedUrl) ||
994
+ (condition.expectedRevision !== undefined && snapshot.revision !== condition.expectedRevision)) {
995
+ throw new PagePreconditionError({
996
+ targetId,
997
+ expectedUrl: condition.expectedUrl ?? null,
998
+ expectedRevision: condition.expectedRevision ?? null,
999
+ actualUrl: snapshot.url,
1000
+ actualRevision: snapshot.revision,
1001
+ });
1002
+ }
1003
+ driver.setPageCondition({
1004
+ targetId,
1005
+ expectedUrl: condition.expectedUrl,
1006
+ expectedRevision: condition.expectedRevision,
1007
+ });
665
1008
  return await fn();
666
1009
  }
667
1010
  finally {
1011
+ driver.setPageCondition(null);
668
1012
  this.requireExtension = previousRequireExtension;
669
- this.activeMode = previousActiveMode;
670
- driver.setCurrentTargetId(previousTargetId);
1013
+ this.cdpExplicitlySelected = previousCdpSelection;
1014
+ this.activeMode = previousMode;
671
1015
  }
672
- });
1016
+ }, deadline);
673
1017
  }
674
1018
  /**
675
1019
  * 临时切换操作目标 iframe,执行完后恢复
@@ -680,15 +1024,15 @@ class UnifiedSessionManager {
680
1024
  * 与 withTabId 配合使用时,应嵌套在 withTabId 内部:
681
1025
  * withTabId(tabId, () => withFrame(frame, () => { ... }))
682
1026
  */
683
- async withFrame(frame, fn) {
1027
+ async withFrame(frame, fn, deadline) {
684
1028
  if (frame === undefined) {
685
1029
  return fn();
686
1030
  }
687
- if (!this.extensionBridge?.isConnected()) {
688
- throw new Error('iframe 穿透需要 Extension 模式');
1031
+ if (this.getMode() !== 'extension' || !this.extensionBridge?.isConnected()) {
1032
+ throw new DriverCapabilityError('iframe 穿透需要 Extension 模式,当前连接未执行 frame 解析或操作');
689
1033
  }
690
1034
  const driver = this.extensionBridge;
691
- const { frameId, offset } = await driver.resolveFrame(frame);
1035
+ const { frameId, offset, frameContext } = await driver.resolveFrame(frame, deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
692
1036
  const previousFrameId = driver.getCurrentFrameId();
693
1037
  const previousFrameOffset = this.currentFrameOffset;
694
1038
  const previousRequireExtension = this.requireExtension;
@@ -700,6 +1044,11 @@ class UnifiedSessionManager {
700
1044
  try {
701
1045
  return await fn();
702
1046
  }
1047
+ catch (error) {
1048
+ throw setErrorPageContext(error, {
1049
+ frameContext: { selection: frame, frameId, ...frameContext },
1050
+ });
1051
+ }
703
1052
  finally {
704
1053
  // 字段赋值不会 throw,driver.setCurrentFrameId 是同步函数也不会 throw,无需嵌套 try
705
1054
  this.requireExtension = previousRequireExtension;
@@ -750,8 +1099,10 @@ class UnifiedSessionManager {
750
1099
  /**
751
1100
  * 按下键盘按键
752
1101
  */
753
- async keyDown(key, commands) {
754
- const driver = await this.getDriver();
1102
+ async keyDown(key, commands, timeout) {
1103
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
1104
+ const driver = await this.getDriver(timeout);
1105
+ const remaining = () => (deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
755
1106
  const isExt = this.isExtensionConnected();
756
1107
  // 预检查:stealth + commands 必然抛错,要在任何状态变更前抛出,避免 modifiers 污染
757
1108
  if (isExt && this.inputMode === 'stealth' && commands && commands.length > 0) {
@@ -760,8 +1111,14 @@ class UnifiedSessionManager {
760
1111
  // Puppeteer 风格:连续 keyDown 同 key → rawKeyDown + autoRepeat(长按重复)
761
1112
  const isRepeat = this.pressedKeys.has(key);
762
1113
  const nextModifiers = MODIFIER_KEYS[key] ? this.modifiers | MODIFIER_KEYS[key] : this.modifiers;
1114
+ if (!isExt) {
1115
+ await getCdpSession().keyDown(key, commands, { rawKeyDown: isRepeat, autoRepeat: isRepeat }, remaining());
1116
+ this.modifiers = nextModifiers;
1117
+ this.pressedKeys.add(key);
1118
+ return;
1119
+ }
763
1120
  if (isExt && this.inputMode === 'stealth') {
764
- await driver.stealthKey(key, 'down', this.getModifierNames(nextModifiers));
1121
+ await driver.stealthKey(key, 'down', this.getModifierNames(nextModifiers), remaining());
765
1122
  this.modifiers = nextModifiers;
766
1123
  this.pressedKeys.add(key);
767
1124
  return;
@@ -775,19 +1132,24 @@ class UnifiedSessionManager {
775
1132
  modifiers: nextModifiers,
776
1133
  commands,
777
1134
  autoRepeat: isRepeat || undefined,
778
- });
1135
+ }, remaining());
779
1136
  this.modifiers = nextModifiers;
780
1137
  this.pressedKeys.add(key);
781
1138
  }
782
1139
  /**
783
1140
  * 释放键盘按键
784
1141
  */
785
- async keyUp(key) {
786
- const driver = await this.getDriver();
1142
+ async keyUp(key, timeout) {
1143
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
1144
+ const driver = await this.getDriver(timeout);
1145
+ const remaining = () => (deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
787
1146
  const isExt = this.isExtensionConnected();
788
1147
  const nextModifiers = MODIFIER_KEYS[key] ? this.modifiers & ~MODIFIER_KEYS[key] : this.modifiers;
789
- if (isExt && this.inputMode === 'stealth') {
790
- await driver.stealthKey(key, 'up', this.getModifierNames(nextModifiers));
1148
+ if (!isExt) {
1149
+ await getCdpSession().keyUp(key, remaining());
1150
+ }
1151
+ else if (this.inputMode === 'stealth') {
1152
+ await driver.stealthKey(key, 'up', this.getModifierNames(nextModifiers), remaining());
791
1153
  }
792
1154
  else {
793
1155
  const def = getKeyDefinition(key);
@@ -796,7 +1158,7 @@ class UnifiedSessionManager {
796
1158
  code: def.code,
797
1159
  windowsVirtualKeyCode: def.keyCode,
798
1160
  modifiers: nextModifiers,
799
- });
1161
+ }, remaining());
800
1162
  }
801
1163
  this.modifiers = nextModifiers;
802
1164
  this.pressedKeys.delete(key);
@@ -804,28 +1166,35 @@ class UnifiedSessionManager {
804
1166
  /**
805
1167
  * 输入文本
806
1168
  */
807
- async typeText(text, delay = 0) {
1169
+ async typeText(text, delay = 0, timeout) {
1170
+ const startedAt = Date.now();
808
1171
  const driver = await this.getDriver();
1172
+ const remaining = timeout === undefined ? undefined : Math.max(0, timeout - (Date.now() - startedAt));
809
1173
  const isExt = this.isExtensionConnected();
810
1174
  if (isExt && this.inputMode === 'stealth') {
811
- await driver.stealthType(text, delay);
1175
+ await driver.stealthType(text, delay, remaining);
812
1176
  }
813
1177
  else {
814
- await driver.inputType(text, delay);
1178
+ await driver.inputType(text, delay, remaining);
815
1179
  }
816
1180
  }
817
1181
  /**
818
1182
  * 鼠标移动
819
1183
  */
820
- async mouseMove(x, y) {
1184
+ async mouseMove(x, y, timeout) {
1185
+ const startedAt = Date.now();
1186
+ const driver = await this.getDriver(timeout);
1187
+ const remaining = timeout === undefined ? undefined : timeout - (Date.now() - startedAt);
1188
+ if (remaining !== undefined && remaining <= 0) {
1189
+ throw new TimeoutError('input timeout before mouse movement');
1190
+ }
821
1191
  this.currentMousePosition = { x, y }; // 更新位置
822
- const driver = await this.getDriver();
823
1192
  const isExt = this.isExtensionConnected();
824
1193
  if (isExt && this.inputMode === 'stealth') {
825
- await driver.stealthMouse('mousemove', x, y);
1194
+ await driver.stealthMouse('mousemove', x, y, undefined, remaining);
826
1195
  }
827
1196
  else {
828
- await driver.inputMouse('mouseMoved', x, y, { modifiers: this.modifiers });
1197
+ await driver.inputMouse('mouseMoved', x, y, { modifiers: this.modifiers }, remaining);
829
1198
  }
830
1199
  }
831
1200
  /**
@@ -890,18 +1259,31 @@ class UnifiedSessionManager {
890
1259
  * Turnstile 点击:同页控件走页面鼠标;Cloudflare iframe 只在已聚焦窗口的活动受控 tab 上使用系统鼠标
891
1260
  */
892
1261
  // noinspection JSUnusedGlobalSymbols — resolveChallenge 通过 ChallengeHost 结构类型调用
893
- async clickTurnstile(snapshot) {
1262
+ async clickTurnstile(snapshot, timeout) {
1263
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
1264
+ const remaining = () => (deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
894
1265
  if (snapshot.clickSource !== 'iframe') {
895
1266
  const point = snapshot.clickPoint;
896
1267
  if (!point) {
897
1268
  throw new OsMouseError('TURNSTILE_OS_CLICK_UNAVAILABLE', '页面未返回可点击的 Turnstile 坐标', '重新检查页面状态后再重试;交互式验证码无法自动完成');
898
1269
  }
1270
+ const driver = await withNavigationBudget(() => this.getDriver(remaining()), deadline);
1271
+ if (this.isExtensionConnected()) {
1272
+ await withNavigationBudget(() => driver.stealthClick(point.x, point.y, 'left', 1, undefined, remaining()), deadline);
1273
+ return;
1274
+ }
899
1275
  const frameOffset = this.currentFrameOffset;
900
1276
  const clickPoint = frameOffset && this.inputMode !== 'stealth'
901
1277
  ? { x: point.x + frameOffset.x, y: point.y + frameOffset.y }
902
1278
  : point;
903
- await this.mouseMove(clickPoint.x, clickPoint.y);
904
- await this.mouseClick('left');
1279
+ this.currentMousePosition = clickPoint;
1280
+ await withNavigationBudget(() => driver.inputMouse('mouseMoved', clickPoint.x, clickPoint.y, { modifiers: this.modifiers }), deadline);
1281
+ await withNavigationBudget(() => getCdpSession().inputMouse('mousePressed', clickPoint.x, clickPoint.y, {
1282
+ button: 'left',
1283
+ clickCount: 1,
1284
+ modifiers: this.modifiers,
1285
+ releaseAfterPress: true,
1286
+ }, remaining()), deadline);
905
1287
  return;
906
1288
  }
907
1289
  if (this.getMode() !== 'extension' || !this.extensionBridge) {
@@ -911,7 +1293,7 @@ class UnifiedSessionManager {
911
1293
  if (!targetId) {
912
1294
  throw new OsMouseError('TURNSTILE_OS_CLICK_UNAVAILABLE', '没有当前受控页面,无法使用系统鼠标点击 Turnstile', '先 browse attach 到受控测试页,把该页放到已经聚焦的窗口并保持为活动 tab 后重试');
913
1295
  }
914
- const topology = await this.listTopology();
1296
+ const topology = await this.listTopology(remaining());
915
1297
  const windowInfo = topology?.windows.find((item) => item.tabs.some((tab) => String(tab.id) === targetId || tab.targetId === targetId));
916
1298
  const tab = windowInfo?.tabs.find((item) => String(item.id) === targetId || item.targetId === targetId);
917
1299
  if (!windowInfo || !tab) {
@@ -927,9 +1309,9 @@ class UnifiedSessionManager {
927
1309
  if (tab.active !== true && (activeTabId === undefined || String(activeTabId) !== targetId)) {
928
1310
  throw new OsMouseError('TURNSTILE_OS_CLICK_UNAVAILABLE', '受控测试页不是当前窗口的活动 tab,拒绝系统鼠标点击', '先把受控测试页设为该窗口的活动 tab,且窗口已经聚焦后再重试');
929
1311
  }
930
- await this.extensionBridge.debuggerDetach();
931
- const viewport = await this.readViewportMetrics(0);
932
- const refreshedTopology = await this.listTopology();
1312
+ await withNavigationBudget(() => this.extensionBridge.debuggerDetach(undefined, remaining()), deadline);
1313
+ const viewport = await withNavigationBudget(() => this.readViewportMetrics(0), deadline);
1314
+ const refreshedTopology = await this.listTopology(remaining());
933
1315
  const refreshedWindow = refreshedTopology?.windows.find((item) => item.tabs.some((candidate) => String(candidate.id) === targetId || candidate.targetId === targetId));
934
1316
  const refreshedTab = refreshedWindow?.tabs.find((candidate) => String(candidate.id) === targetId || candidate.targetId === targetId);
935
1317
  const refreshedActiveTabId = refreshedWindow?.activeTabId;
@@ -943,21 +1325,37 @@ class UnifiedSessionManager {
943
1325
  const clickPoint = snapshot.clickPoint && frameOffset
944
1326
  ? { x: snapshot.clickPoint.x + frameOffset.x, y: snapshot.clickPoint.y + frameOffset.y }
945
1327
  : snapshot.clickPoint;
946
- const screen = await resolveTurnstileOsClickPoint({
1328
+ const screen = await withNavigationBudget(() => resolveTurnstileOsClickPoint({
947
1329
  ...snapshot,
948
1330
  clickPoint,
949
1331
  screenPoint: null,
950
1332
  viewport,
951
- });
952
- await osLeftClick(screen.x, screen.y);
1333
+ }, { deadline }), deadline);
1334
+ await withNavigationBudget(() => osLeftClick(screen.x, screen.y, { deadline }), deadline);
953
1335
  }
954
1336
  // noinspection JSUnusedGlobalSymbols — resolveChallenge 通过 ChallengeHost 结构类型调用
955
1337
  async inspectChallenge(options, timeout) {
956
1338
  if (this.getMode() !== 'extension' || !this.extensionBridge) {
957
1339
  throw new Error('challenge_inspect 仅在 Extension 模式可用');
958
1340
  }
959
- await this.extensionBridge.debuggerDetach();
960
- return this.extensionBridge.inspectChallenge(options, timeout);
1341
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
1342
+ const state = await withNavigationBudget(() => this.getLiveState(), deadline);
1343
+ const title = (state?.title ?? '').trim().toLowerCase().replace(/…/g, '...');
1344
+ const challengeTitle = options.titleNeedles.some((needle) => title.includes(needle.toLowerCase()));
1345
+ const detach = () => withNavigationBudget(() => this.extensionBridge.debuggerDetach(undefined, deadline === undefined ? undefined : remainingNavigationTimeout(deadline)), deadline);
1346
+ if (challengeTitle) {
1347
+ await detach();
1348
+ }
1349
+ const snapshot = await this.extensionBridge.inspectChallenge(options, deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
1350
+ if (!challengeTitle && snapshot && typeof snapshot === 'object') {
1351
+ const evidence = snapshot;
1352
+ if (evidence.turnstilePresent ||
1353
+ (!evidence.originResponsePending &&
1354
+ ((evidence.selectorHits?.length ?? 0) > 0 || (evidence.textHits?.length ?? 0) > 0))) {
1355
+ await detach();
1356
+ }
1357
+ }
1358
+ return snapshot;
961
1359
  }
962
1360
  /**
963
1361
  * 鼠标滚轮
@@ -1058,15 +1456,34 @@ class UnifiedSessionManager {
1058
1456
  const driver = await this.getDriver();
1059
1457
  return driver.debuggerSend(method, params);
1060
1458
  }
1459
+ extensionReadBridge() {
1460
+ if (this.getMode() !== 'extension' || !this.extensionBridge?.isConnected()) {
1461
+ throw new DriverCapabilityError('定向读取需要已连接的 Extension');
1462
+ }
1463
+ return this.extensionBridge;
1464
+ }
1465
+ metadataKey(targetId) {
1466
+ return `${this.getMode()}:${targetId}`;
1467
+ }
1468
+ recordPageUse(targetId, created = false) {
1469
+ const metadata = this.getPageMetadata(targetId);
1470
+ this.pageMetadata.set(this.metadataKey(targetId), {
1471
+ ...metadata,
1472
+ createdBy: created ? 'mcp-chrome' : metadata.createdBy,
1473
+ createdAt: created ? new Date().toISOString() : metadata.createdAt,
1474
+ lastUsedAt: new Date().toISOString(),
1475
+ });
1476
+ }
1061
1477
  evaluateViaCdp(script, args, timeout) {
1062
1478
  return getCdpSession().evaluate(script, args, timeout);
1063
1479
  }
1064
- async evaluateViaExtensionPrecise(code, expression, args, timeout, staleContextRetry = 'never') {
1065
- const hasArgs = args !== undefined && args.length > 0;
1480
+ async evaluateViaExtensionPrecise(code, expression, args, timeout, options = {}) {
1481
+ const hasArgs = args !== undefined;
1066
1482
  const currentFrameId = this.extensionBridge.getCurrentFrameId();
1483
+ const staleContextRetry = options.staleContextRetry ?? 'never';
1067
1484
  // precise + args + 主 frame:使用 callFunctionOn 避免大 payload 字符串拼接
1068
1485
  if (hasArgs && currentFrameId === 0) {
1069
- return this.callFunctionOn(code, args, timeout);
1486
+ return this.callFunctionOn(code, args, timeout, options);
1070
1487
  }
1071
1488
  if (currentFrameId !== 0) {
1072
1489
  // iframe:args 仍用字符串拼接(evaluateInFrame 使用 expression 字符串)
@@ -1098,7 +1515,7 @@ class UnifiedSessionManager {
1098
1515
  if (result.exceptionDetails) {
1099
1516
  throw new Error(formatCdpException(result.exceptionDetails));
1100
1517
  }
1101
- return this.materializeCdpResult(result.result, timeout);
1518
+ return this.materializeCdpResult(result.result, timeout, options.fileOutput);
1102
1519
  }
1103
1520
  async evaluateViaExtensionStealth(expression, timeout) {
1104
1521
  return (await this.extensionBridge.evaluate(expression, undefined, timeout));
@@ -1171,12 +1588,19 @@ class UnifiedSessionManager {
1171
1588
  }
1172
1589
  return extractCdpValue(result.result);
1173
1590
  }
1174
- async materializeCdpResult(result, timeout) {
1591
+ async materializeCdpResult(result, timeout, fileOutput = false) {
1175
1592
  if (!result?.objectId) {
1176
1593
  return extractCdpValue(result);
1177
1594
  }
1178
1595
  try {
1179
- return await this.materializeRemoteObject(result, timeout, { seen: new Set(), nodes: 0, chars: 0 }, 0);
1596
+ return await this.materializeRemoteObject(result, timeout, {
1597
+ seen: new Set(),
1598
+ nodes: 0,
1599
+ chars: 0,
1600
+ maxChars: fileOutput
1601
+ ? UnifiedSessionManager.CDP_MATERIALIZE_MAX_FILE_CHARS
1602
+ : UnifiedSessionManager.CDP_MATERIALIZE_MAX_CHARS,
1603
+ }, 0);
1180
1604
  }
1181
1605
  finally {
1182
1606
  this.extensionBridge.debuggerSend('Runtime.releaseObject', { objectId: result.objectId }).catch(() => { });
@@ -1273,7 +1697,7 @@ class UnifiedSessionManager {
1273
1697
  assertMaterializeBudget(state, depth, result) {
1274
1698
  if (depth > UnifiedSessionManager.CDP_MATERIALIZE_MAX_DEPTH ||
1275
1699
  state.nodes > UnifiedSessionManager.CDP_MATERIALIZE_MAX_NODES ||
1276
- state.chars > UnifiedSessionManager.CDP_MATERIALIZE_MAX_CHARS) {
1700
+ state.chars > state.maxChars) {
1277
1701
  this.throwMaterializeLimit(state, depth, result);
1278
1702
  }
1279
1703
  }
@@ -1290,7 +1714,7 @@ class UnifiedSessionManager {
1290
1714
  chars: state.chars,
1291
1715
  maxDepth: UnifiedSessionManager.CDP_MATERIALIZE_MAX_DEPTH,
1292
1716
  maxNodes: UnifiedSessionManager.CDP_MATERIALIZE_MAX_NODES,
1293
- maxChars: UnifiedSessionManager.CDP_MATERIALIZE_MAX_CHARS,
1717
+ maxChars: state.maxChars,
1294
1718
  type: result?.type,
1295
1719
  subtype: result?.subtype,
1296
1720
  className: result?.className,
@@ -1324,6 +1748,19 @@ class UnifiedSessionManager {
1324
1748
  * 避免工具 timeout 被连接等待吞掉,不传则使用默认 30s
1325
1749
  */
1326
1750
  async getDriver(timeout) {
1751
+ const scopedMode = this.tabLockContext.getStore()?.mode;
1752
+ if (scopedMode === 'extension') {
1753
+ if (!this.extensionBridge?.isConnected()) {
1754
+ throw new DriverCapabilityError('Extension 已断开,当前请求保留原后端,未改用 CDP');
1755
+ }
1756
+ return this.extensionBridge;
1757
+ }
1758
+ if (scopedMode === 'cdp') {
1759
+ if (!getCdpSession().isConnected()) {
1760
+ throw new DriverCapabilityError('CDP 已断开,当前请求保留原后端,未改用 Extension');
1761
+ }
1762
+ return getCdpSession();
1763
+ }
1327
1764
  if (this.activeMode === 'cdp' && this.cdpExplicitlySelected && getCdpSession().isConnected()) {
1328
1765
  this.assertCdpFallbackAllowed();
1329
1766
  return getCdpSession();
@@ -1383,7 +1820,7 @@ class UnifiedSessionManager {
1383
1820
  * 参数通过 CDP 协议结构化传递,避免大 payload 字符串拼接导致的长度限制和转义问题,
1384
1821
  * 要求 code 必须是函数表达式(如 "(x) => x + 1")
1385
1822
  */
1386
- async callFunctionOn(code, args, timeout) {
1823
+ async callFunctionOn(code, args, timeout, options = {}) {
1387
1824
  const buildFallbackExpression = () => `(${code})(${args.map((a) => JSON.stringify(a)).join(', ')})`;
1388
1825
  const globalResult = (await this.extensionBridge.debuggerSend('Runtime.evaluate', {
1389
1826
  expression: 'globalThis',
@@ -1393,7 +1830,7 @@ class UnifiedSessionManager {
1393
1830
  if (!globalObjectId) {
1394
1831
  console.warn('[MCP] Runtime.evaluate 未返回 globalThis objectId,改用表达式传递 evaluate args');
1395
1832
  const fallbackExpression = buildFallbackExpression();
1396
- return this.evaluateViaExtensionPrecise(fallbackExpression, fallbackExpression, undefined, timeout);
1833
+ return this.evaluateViaExtensionPrecise(fallbackExpression, fallbackExpression, undefined, timeout, options);
1397
1834
  }
1398
1835
  try {
1399
1836
  const params = {
@@ -1410,7 +1847,7 @@ class UnifiedSessionManager {
1410
1847
  if (result.exceptionDetails) {
1411
1848
  throw new Error(formatCdpException(result.exceptionDetails));
1412
1849
  }
1413
- return await this.materializeCdpResult(result.result, timeout);
1850
+ return await this.materializeCdpResult(result.result, timeout, options.fileOutput);
1414
1851
  }
1415
1852
  finally {
1416
1853
  this.extensionBridge.debuggerSend('Runtime.releaseObject', {
@@ -1418,27 +1855,6 @@ class UnifiedSessionManager {
1418
1855
  }).catch(() => { });
1419
1856
  }
1420
1857
  }
1421
- /**
1422
- * 串行化所有 tab 切换操作,防止并发请求互相覆盖 currentTabId,
1423
- * 调用者:selectPage/activatePage/newPage/closePage/navigate/reload/launch/withTabId
1424
- *
1425
- * 注意:此锁不可重入,fn() 内禁止调用任何使用 withTabLock 的方法,否则会死锁,
1426
- * 当前所有 fn() 只调用 bridge 的原子操作(createTab/navigate/evaluate 等),不存在此问题
1427
- */
1428
- async withTabLock(fn) {
1429
- const previousLock = this.tabSwitchLock;
1430
- let releaseLock;
1431
- this.tabSwitchLock = new Promise((resolve) => {
1432
- releaseLock = resolve;
1433
- });
1434
- try {
1435
- await previousLock;
1436
- return await fn();
1437
- }
1438
- finally {
1439
- releaseLock();
1440
- }
1441
- }
1442
1858
  }
1443
1859
  /**
1444
1860
  * 获取统一会话管理器实例