@pyrokine/mcp-chrome 2.4.4 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +401 -102
  2. package/README_zh.md +319 -79
  3. package/dist/anti-detection/injection.js +3 -3
  4. package/dist/cdp/client.d.ts +1 -1
  5. package/dist/cdp/client.d.ts.map +1 -1
  6. package/dist/cdp/client.js +18 -7
  7. package/dist/cdp/client.js.map +1 -1
  8. package/dist/cdp/launcher.d.ts +2 -3
  9. package/dist/cdp/launcher.d.ts.map +1 -1
  10. package/dist/cdp/launcher.js +84 -24
  11. package/dist/cdp/launcher.js.map +1 -1
  12. package/dist/core/auto-wait.d.ts +3 -3
  13. package/dist/core/auto-wait.d.ts.map +1 -1
  14. package/dist/core/auto-wait.js +45 -20
  15. package/dist/core/auto-wait.js.map +1 -1
  16. package/dist/core/browser-driver.d.ts +101 -12
  17. package/dist/core/browser-driver.d.ts.map +1 -1
  18. package/dist/core/browser-driver.js.map +1 -1
  19. package/dist/core/errors.d.ts +16 -0
  20. package/dist/core/errors.d.ts.map +1 -1
  21. package/dist/core/errors.js +77 -0
  22. package/dist/core/errors.js.map +1 -1
  23. package/dist/core/locator.d.ts.map +1 -1
  24. package/dist/core/locator.js +6 -4
  25. package/dist/core/locator.js.map +1 -1
  26. package/dist/core/os-mouse.d.ts +15 -2
  27. package/dist/core/os-mouse.d.ts.map +1 -1
  28. package/dist/core/os-mouse.js +52 -8
  29. package/dist/core/os-mouse.js.map +1 -1
  30. package/dist/core/session.d.ts +34 -19
  31. package/dist/core/session.d.ts.map +1 -1
  32. package/dist/core/session.js +574 -130
  33. package/dist/core/session.js.map +1 -1
  34. package/dist/core/types.d.ts +2 -0
  35. package/dist/core/types.d.ts.map +1 -1
  36. package/dist/core/types.js.map +1 -1
  37. package/dist/core/unified-session.d.ts +95 -20
  38. package/dist/core/unified-session.d.ts.map +1 -1
  39. package/dist/core/unified-session.js +489 -117
  40. package/dist/core/unified-session.js.map +1 -1
  41. package/dist/core/utils.d.ts +5 -0
  42. package/dist/core/utils.d.ts.map +1 -1
  43. package/dist/core/utils.js +475 -54
  44. package/dist/core/utils.js.map +1 -1
  45. package/dist/extension/bridge.d.ts +46 -36
  46. package/dist/extension/bridge.d.ts.map +1 -1
  47. package/dist/extension/bridge.js +269 -112
  48. package/dist/extension/bridge.js.map +1 -1
  49. package/dist/extension/http-server.d.ts +3 -0
  50. package/dist/extension/http-server.d.ts.map +1 -1
  51. package/dist/extension/http-server.js +19 -2
  52. package/dist/extension/http-server.js.map +1 -1
  53. package/dist/index.js +7 -0
  54. package/dist/index.js.map +1 -1
  55. package/dist/tools/browse.d.ts.map +1 -1
  56. package/dist/tools/browse.js +241 -171
  57. package/dist/tools/browse.js.map +1 -1
  58. package/dist/tools/challenge.d.ts +1 -1
  59. package/dist/tools/challenge.d.ts.map +1 -1
  60. package/dist/tools/challenge.js +75 -37
  61. package/dist/tools/challenge.js.map +1 -1
  62. package/dist/tools/cookies.d.ts.map +1 -1
  63. package/dist/tools/cookies.js +5 -3
  64. package/dist/tools/cookies.js.map +1 -1
  65. package/dist/tools/diagnostics.d.ts +3 -3
  66. package/dist/tools/diagnostics.d.ts.map +1 -1
  67. package/dist/tools/diagnostics.js +13 -12
  68. package/dist/tools/diagnostics.js.map +1 -1
  69. package/dist/tools/evaluate.d.ts.map +1 -1
  70. package/dist/tools/evaluate.js +57 -26
  71. package/dist/tools/evaluate.js.map +1 -1
  72. package/dist/tools/extract.d.ts.map +1 -1
  73. package/dist/tools/extract.js +107 -175
  74. package/dist/tools/extract.js.map +1 -1
  75. package/dist/tools/input.d.ts +1 -1
  76. package/dist/tools/input.d.ts.map +1 -1
  77. package/dist/tools/input.js +380 -158
  78. package/dist/tools/input.js.map +1 -1
  79. package/dist/tools/logs.d.ts.map +1 -1
  80. package/dist/tools/logs.js +5 -5
  81. package/dist/tools/logs.js.map +1 -1
  82. package/dist/tools/manage.d.ts.map +1 -1
  83. package/dist/tools/manage.js +380 -57
  84. package/dist/tools/manage.js.map +1 -1
  85. package/dist/tools/page-context.d.ts +17 -0
  86. package/dist/tools/page-context.d.ts.map +1 -0
  87. package/dist/tools/page-context.js +103 -0
  88. package/dist/tools/page-context.js.map +1 -0
  89. package/dist/tools/png.d.ts +5 -0
  90. package/dist/tools/png.d.ts.map +1 -1
  91. package/dist/tools/png.js +84 -19
  92. package/dist/tools/png.js.map +1 -1
  93. package/dist/tools/post-condition.d.ts.map +1 -1
  94. package/dist/tools/post-condition.js +5 -2
  95. package/dist/tools/post-condition.js.map +1 -1
  96. package/dist/tools/schema.d.ts +9 -0
  97. package/dist/tools/schema.d.ts.map +1 -1
  98. package/dist/tools/schema.js +15 -0
  99. package/dist/tools/schema.js.map +1 -1
  100. package/dist/tools/target-diagnostics.d.ts.map +1 -1
  101. package/dist/tools/target-diagnostics.js +32 -19
  102. package/dist/tools/target-diagnostics.js.map +1 -1
  103. package/dist/tools/wait.d.ts.map +1 -1
  104. package/dist/tools/wait.js +19 -25
  105. package/dist/tools/wait.js.map +1 -1
  106. package/extension/dist/assets/content.ts-C4imZ6A9.js +13 -0
  107. package/extension/dist/assets/content.ts-loader-CnJuCGhl.js +13 -0
  108. package/extension/dist/assets/{index.ts-Bqcu2qiN.js → index.ts-GeHNZBml.js} +2040 -2111
  109. package/extension/dist/assets/page-scripts-CMIY1zhd.js +1379 -0
  110. package/extension/dist/assets/{popup.html-B81xccfq.js → popup.html-CgtWL6Py.js} +48 -1
  111. package/extension/dist/manifest.json +4 -3
  112. package/extension/dist/service-worker-loader.js +1 -1
  113. package/extension/dist/src/popup/popup.html +11 -1
  114. package/package.json +9 -7
  115. package/scripts/start-chrome.ps1 +58 -0
  116. package/extension/dist/assets/content.ts-Cj_iiU2s.js +0 -25
@@ -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) {
@@ -100,6 +106,35 @@ class UnifiedSessionManager {
100
106
  }
101
107
  return null;
102
108
  }
109
+ getPageMetadata(targetId) {
110
+ return (this.pageMetadata.get(this.metadataKey(targetId)) ?? {
111
+ createdBy: 'unknown',
112
+ createdAt: null,
113
+ lastUsedAt: null,
114
+ });
115
+ }
116
+ async setPageMetadata(targetId, updates) {
117
+ await this.getPageSnapshot(targetId);
118
+ const metadata = { ...this.getPageMetadata(targetId) };
119
+ if (updates.taskHint !== undefined) {
120
+ if (updates.taskHint === null) {
121
+ delete metadata.taskHint;
122
+ }
123
+ else {
124
+ metadata.taskHint = updates.taskHint;
125
+ }
126
+ }
127
+ if (updates.note !== undefined) {
128
+ if (updates.note === null) {
129
+ delete metadata.note;
130
+ }
131
+ else {
132
+ metadata.note = updates.note;
133
+ }
134
+ }
135
+ this.pageMetadata.set(this.metadataKey(targetId), metadata);
136
+ return metadata;
137
+ }
103
138
  /**
104
139
  * 获取当前 iframe 在主页面的偏移量(仅 withFrame 期间有效)
105
140
  */
@@ -158,6 +193,7 @@ class UnifiedSessionManager {
158
193
  });
159
194
  this.activeMode = 'extension';
160
195
  this.cdpExplicitlySelected = false;
196
+ this.recordPageUse(result.targetId, true);
161
197
  return {
162
198
  targetId: result.targetId,
163
199
  type: result.type ?? 'page',
@@ -171,6 +207,7 @@ class UnifiedSessionManager {
171
207
  const target = await getCdpSession().launch(options);
172
208
  this.activeMode = 'cdp';
173
209
  this.cdpExplicitlySelected = false;
210
+ this.recordPageUse(target.targetId, target.targetCreated ?? target.reused !== true);
174
211
  return {
175
212
  ...target,
176
213
  mode: 'cdp',
@@ -179,52 +216,61 @@ class UnifiedSessionManager {
179
216
  /**
180
217
  * 列出所有页面
181
218
  */
182
- async listTargets() {
219
+ async listTargets(timeout) {
183
220
  const mode = this.getMode();
184
221
  if (mode === 'none') {
185
222
  return [];
186
223
  }
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,
224
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
225
+ const driver = await this.getDriver(timeout);
226
+ const targets = await driver.listTargets(deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
227
+ const liveKeys = new Set(targets.map((t) => `${mode}:${t.targetId ?? String(t.id)}`));
228
+ for (const key of this.pageMetadata.keys()) {
229
+ if (key.startsWith(`${mode}:`) && !liveKeys.has(key)) {
230
+ this.pageMetadata.delete(key);
231
+ }
232
+ }
233
+ return targets.map(({ id, ...target }) => ({
234
+ ...target,
235
+ targetId: target.targetId ?? String(id),
236
+ type: target.type ?? 'page',
194
237
  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,
238
+ ...(mode === 'extension' ? { isActive: target.active ?? false } : {}),
239
+ metadata: this.getPageMetadata(target.targetId ?? String(id)),
202
240
  }));
203
241
  }
204
- async listTopology() {
242
+ async listTopology(timeout) {
205
243
  const mode = this.getMode();
206
244
  if (mode === 'none') {
207
245
  return null;
208
246
  }
209
- const driver = await this.getDriver();
247
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
248
+ const driver = await this.getDriver(timeout);
210
249
  if (!driver.listWindows) {
211
250
  return null;
212
251
  }
213
- return driver.listWindows();
252
+ return driver.listWindows(deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
253
+ }
254
+ async setReadAccess(targetId, allow) {
255
+ const driver = await this.getDriver();
256
+ if (!driver.setReadAccess) {
257
+ throw new DriverCapabilityError('普通只读授权仅支持 Extension 模式,未执行');
258
+ }
259
+ return this.withTabLock(() => driver.setReadAccess(targetId, allow));
214
260
  }
215
261
  async adoptPage(targetId) {
216
262
  const driver = await this.getDriver();
217
263
  if (!driver.adoptPage) {
218
264
  throw new DriverCapabilityError('adoptPage 仅支持 Extension 模式');
219
265
  }
220
- return driver.adoptPage(targetId);
266
+ return this.withTabLock(() => driver.adoptPage(targetId));
221
267
  }
222
268
  async releasePage(targetId) {
223
269
  const driver = await this.getDriver();
224
270
  if (!driver.releasePage) {
225
271
  throw new DriverCapabilityError('releasePage 仅支持 Extension 模式');
226
272
  }
227
- return driver.releasePage(targetId);
273
+ return this.withTabLock(() => driver.releasePage(targetId));
228
274
  }
229
275
  async movePage(targetId, options) {
230
276
  const driver = await this.getDriver();
@@ -233,6 +279,41 @@ class UnifiedSessionManager {
233
279
  }
234
280
  return driver.movePage(targetId, options);
235
281
  }
282
+ async updatePage(targetId, options) {
283
+ const driver = await this.getDriver();
284
+ if (!driver.updatePage) {
285
+ throw new DriverCapabilityError('updatePage 原生 tab 配置仅支持 Extension 模式');
286
+ }
287
+ return this.withTabLock(() => driver.updatePage(targetId, options));
288
+ }
289
+ async groupPages(targetIds, options) {
290
+ const driver = await this.getDriver();
291
+ if (!driver.groupPages) {
292
+ throw new DriverCapabilityError('groupPages 仅支持 Extension 模式');
293
+ }
294
+ return this.withTabLock(() => driver.groupPages(targetIds, options));
295
+ }
296
+ async ungroupPages(targetIds) {
297
+ const driver = await this.getDriver();
298
+ if (!driver.ungroupPages) {
299
+ throw new DriverCapabilityError('ungroupPages 仅支持 Extension 模式');
300
+ }
301
+ return this.withTabLock(() => driver.ungroupPages(targetIds));
302
+ }
303
+ async updateGroup(groupId, options) {
304
+ const driver = await this.getDriver();
305
+ if (!driver.updateGroup) {
306
+ throw new DriverCapabilityError('updateGroup 仅支持 Extension 模式');
307
+ }
308
+ return this.withTabLock(() => driver.updateGroup(groupId, options));
309
+ }
310
+ async moveGroup(groupId, options) {
311
+ const driver = await this.getDriver();
312
+ if (!driver.moveGroup) {
313
+ throw new DriverCapabilityError('moveGroup 仅支持 Extension 模式');
314
+ }
315
+ return this.withTabLock(() => driver.moveGroup(groupId, options));
316
+ }
236
317
  async reorderPage(targetId, index) {
237
318
  const driver = await this.getDriver();
238
319
  if (!driver.reorderPage) {
@@ -269,40 +350,72 @@ class UnifiedSessionManager {
269
350
  }
270
351
  return driver.resizeWindow(windowId, options);
271
352
  }
353
+ async updateWindow(windowId, options) {
354
+ const driver = await this.getDriver();
355
+ if (!driver.updateWindow) {
356
+ throw new DriverCapabilityError('updateWindow 仅支持 Extension 模式');
357
+ }
358
+ return this.withTabLock(() => driver.updateWindow(windowId, options));
359
+ }
272
360
  async newWindow(options) {
273
361
  const driver = await this.getDriver();
274
362
  if (!driver.newWindow) {
275
363
  throw new DriverCapabilityError('newWindow 仅支持 Extension 模式');
276
364
  }
277
- return this.withTabLock(() => driver.newWindow(options));
365
+ return this.withTabLock(async () => {
366
+ const result = await driver.newWindow(options);
367
+ if (result.after && 'tabs' in result.after) {
368
+ for (const tab of result.after.tabs) {
369
+ const targetId = tab.targetId ?? String(tab.id);
370
+ this.recordPageUse(targetId, targetId !== options.targetId);
371
+ }
372
+ }
373
+ else if (result.targetId) {
374
+ this.recordPageUse(result.targetId, options.targetId === undefined);
375
+ }
376
+ return result;
377
+ });
278
378
  }
279
379
  async closeWindow(windowId) {
280
380
  const driver = await this.getDriver();
281
381
  if (!driver.closeWindow) {
282
382
  throw new DriverCapabilityError('closeWindow 仅支持 Extension 模式');
283
383
  }
284
- return this.withTabLock(() => driver.closeWindow(windowId));
384
+ return this.withTabLock(async () => {
385
+ const result = await driver.closeWindow(windowId);
386
+ if (result.before && 'tabs' in result.before) {
387
+ for (const tab of result.before.tabs) {
388
+ this.pageMetadata.delete(this.metadataKey(tab.targetId ?? String(tab.id)));
389
+ }
390
+ }
391
+ return result;
392
+ });
285
393
  }
286
394
  /**
287
395
  * 导航到 URL
288
396
  */
289
397
  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));
398
+ const deadline = Date.now() + (options.timeout ?? DEFAULT_TIMEOUT);
399
+ const driver = await this.getDriver(remainingNavigationTimeout(deadline));
400
+ const navigate = () => driver.navigate(url, { wait: options.wait, timeout: remainingNavigationTimeout(deadline) });
401
+ await (this.getMode() === 'extension' ? this.withTabLock(navigate, deadline) : navigate());
402
+ }
403
+ async goBack(timeout = DEFAULT_TIMEOUT) {
404
+ const deadline = Date.now() + timeout;
405
+ const driver = await this.getDriver(remainingNavigationTimeout(deadline));
406
+ const result = await this.withTabLock(() => driver.goBack(remainingNavigationTimeout(deadline)), deadline);
296
407
  return { navigated: result.navigated };
297
408
  }
298
- async goForward(timeout) {
299
- const driver = await this.getDriver(timeout);
300
- const result = await this.withTabLock(() => driver.goForward(timeout));
409
+ async goForward(timeout = DEFAULT_TIMEOUT) {
410
+ const deadline = Date.now() + timeout;
411
+ const driver = await this.getDriver(remainingNavigationTimeout(deadline));
412
+ const result = await this.withTabLock(() => driver.goForward(remainingNavigationTimeout(deadline)), deadline);
301
413
  return { navigated: result.navigated };
302
414
  }
303
415
  async reload(options = {}) {
304
- const driver = await this.getDriver(options.timeout);
305
- await this.withTabLock(() => driver.reload(options.ignoreCache, options.waitUntil, options.timeout));
416
+ const deadline = Date.now() + (options.timeout ?? DEFAULT_TIMEOUT);
417
+ const driver = await this.getDriver(remainingNavigationTimeout(deadline));
418
+ await this.withTabLock(() => driver.reload(options.ignoreCache, options.waitUntil, remainingNavigationTimeout(deadline)), deadline);
306
419
  }
307
420
  /**
308
421
  * 读取页面(Accessibility Tree)
@@ -329,9 +442,24 @@ class UnifiedSessionManager {
329
442
  *
330
443
  * 返回结构化结果,让调用方知道操作是否真正生效
331
444
  */
332
- async actionableClick(refId, force) {
445
+ async actionableClick(refId, force = false, button = 'left', clickCount = 1) {
333
446
  const driver = await this.getDriver();
334
- return driver.actionableClick(refId, force);
447
+ if (button === 'left' && clickCount === 1) {
448
+ return driver.actionableClick(refId, force);
449
+ }
450
+ if (!force) {
451
+ const result = await driver.checkActionability(refId);
452
+ if (!result.success)
453
+ return result;
454
+ }
455
+ if (force) {
456
+ const { x, y } = this.currentMousePosition;
457
+ await driver.stealthClick(x, y, button, clickCount, refId);
458
+ }
459
+ else {
460
+ await this.mouseClick(button, clickCount, refId);
461
+ }
462
+ return { success: true };
335
463
  }
336
464
  /**
337
465
  * dispatch 模式输入(ISOLATED 世界,兼容 React/Vue 受控组件)
@@ -391,7 +519,7 @@ class UnifiedSessionManager {
391
519
  const entryStart = Date.now();
392
520
  this.lastEvaluationMetadata = undefined;
393
521
  const effectiveMode = mode ?? this.inputMode;
394
- const hasArgs = args && args.length > 0;
522
+ const hasArgs = args !== undefined;
395
523
  // stealth 模式:args 只能通过字符串拼接(chrome.scripting 不支持协议级参数传递)
396
524
  let expression = code;
397
525
  if (hasArgs && effectiveMode === 'stealth') {
@@ -415,7 +543,7 @@ class UnifiedSessionManager {
415
543
  }
416
544
  // Extension 路径
417
545
  if (effectiveMode === 'precise') {
418
- return this.evaluateViaExtensionPrecise(code, expression, args, timeout, options.staleContextRetry ?? 'never');
546
+ return this.evaluateViaExtensionPrecise(code, expression, args, timeout, options);
419
547
  }
420
548
  return this.evaluateViaExtensionStealth(expression, timeout);
421
549
  }
@@ -456,6 +584,24 @@ class UnifiedSessionManager {
456
584
  async getHtml(selector, outer = true) {
457
585
  return (await this.getDriver()).getPageHtml(selector, outer);
458
586
  }
587
+ async getTextByRef(refId) {
588
+ return this.extensionReadBridge().getText(undefined, refId);
589
+ }
590
+ async getHtmlByRef(refId, outer = true) {
591
+ return this.extensionReadBridge().getHtml(undefined, outer, refId);
592
+ }
593
+ async getAttributeByRef(refId, attribute) {
594
+ return this.extensionReadBridge().getAttribute(undefined, refId, attribute);
595
+ }
596
+ async getComputedStyleByRef(refId, prop) {
597
+ return this.extensionReadBridge().getComputedStyle(refId, prop);
598
+ }
599
+ async findAtPoint(x, y, matchIndex, timeout) {
600
+ return this.extensionReadBridge().find(undefined, undefined, undefined, timeout, { x, y }, matchIndex);
601
+ }
602
+ async getHtmlWithImagesByRef(refId) {
603
+ return this.extensionReadBridge().getHtmlWithImages(undefined, true, refId);
604
+ }
459
605
  /**
460
606
  * 获取页面 HTML + 图片元信息
461
607
  */
@@ -468,7 +614,13 @@ class UnifiedSessionManager {
468
614
  */
469
615
  async getMetadata() {
470
616
  const driver = await this.getDriver();
471
- return driver.getMetadata();
617
+ const targetId = this.getCurrentTargetId();
618
+ const metadata = await driver.getMetadata();
619
+ const target = (await this.listTargets()).find((page) => page.targetId === targetId);
620
+ if (!target) {
621
+ throw new TargetNotFoundError(targetId ?? 'current');
622
+ }
623
+ return { ...metadata, managed: target.managed ?? false, metadata: target.metadata };
472
624
  }
473
625
  /**
474
626
  * 批量从浏览器缓存获取资源内容
@@ -518,7 +670,10 @@ class UnifiedSessionManager {
518
670
  * @param xpath XPath 表达式
519
671
  * @param timeout 端到端预算(毫秒),包含连接等待和请求超时,传给 bridge.find → sendCommand
520
672
  */
521
- async find(selector, text, xpath, timeout) {
673
+ async find(selector, text, xpath, timeout, matchIndex) {
674
+ if (matchIndex !== undefined) {
675
+ return this.extensionReadBridge().find(selector, text, xpath, timeout, undefined, matchIndex);
676
+ }
522
677
  if (timeout !== undefined) {
523
678
  // 轮询上下文:快速失败,端到端预算受控
524
679
  if (this.isExtensionConnected()) {
@@ -567,12 +722,14 @@ class UnifiedSessionManager {
567
722
  /**
568
723
  * 创建新页面
569
724
  */
570
- async newPage(url) {
725
+ async newPage(url, options, timeout) {
571
726
  const driver = await this.getDriver();
572
727
  const isExt = this.isExtensionConnected();
573
728
  const op = async () => {
574
- const result = await driver.newPage(url);
729
+ const result = await driver.newPage(url, timeout, options);
730
+ this.recordPageUse(result.targetId, true);
575
731
  return {
732
+ ...result,
576
733
  targetId: result.targetId,
577
734
  type: result.type ?? 'page',
578
735
  url: result.url,
@@ -587,9 +744,16 @@ class UnifiedSessionManager {
587
744
  * 关闭页面
588
745
  */
589
746
  async closePage(targetId) {
747
+ if (!targetId) {
748
+ throw new DriverCapabilityError('closePage 需要显式 targetId,未关闭页面');
749
+ }
590
750
  const driver = await this.getDriver();
591
751
  const isExt = this.isExtensionConnected();
592
- const op = () => driver.closePage(targetId);
752
+ const op = async () => {
753
+ const result = await driver.closePage(targetId);
754
+ this.pageMetadata.delete(this.metadataKey(targetId));
755
+ return result;
756
+ };
593
757
  if (isExt) {
594
758
  return this.withTabLock(op);
595
759
  }
@@ -622,6 +786,40 @@ class UnifiedSessionManager {
622
786
  else {
623
787
  await op();
624
788
  }
789
+ this.recordPageUse(targetId);
790
+ }
791
+ /**
792
+ * 串行化所有 tab 切换操作,防止并发请求互相覆盖 currentTabId,
793
+ * 调用者:selectPage/activatePage/adoptPage/releasePage/newPage/closePage/navigate/reload/launch/withTabId
794
+ *
795
+ * 同一请求内的嵌套调用可重入,恢复状态只保存在当前请求的 AsyncLocalStorage 中
796
+ */
797
+ async withTabLock(fn, deadline) {
798
+ if (this.tabLockContext.getStore()?.session === this) {
799
+ if (deadline !== undefined) {
800
+ remainingNavigationTimeout(deadline);
801
+ }
802
+ return fn();
803
+ }
804
+ const previousLock = this.tabSwitchLock;
805
+ let releaseLock;
806
+ this.tabSwitchLock = new Promise((resolve) => {
807
+ releaseLock = resolve;
808
+ });
809
+ let acquired = false;
810
+ try {
811
+ await waitForNavigationQueue(previousLock, deadline);
812
+ acquired = true;
813
+ return await this.tabLockContext.run({ session: this }, fn);
814
+ }
815
+ finally {
816
+ if (acquired) {
817
+ releaseLock();
818
+ }
819
+ else {
820
+ void previousLock.then(releaseLock, releaseLock);
821
+ }
822
+ }
625
823
  }
626
824
  /**
627
825
  * 临时切换操作目标 tab,执行完后恢复
@@ -632,44 +830,178 @@ class UnifiedSessionManager {
632
830
  * 即使不传 tabId,也需要加锁:fn() 内调用 bridge 方法会读取 currentTabId,
633
831
  * 不加锁则并发的 withTabId(someId, ...) 可能在 fn() 执行中途修改 currentTabId
634
832
  */
635
- async withTabId(tabId, fn) {
636
- // Extension 未连接时不需要锁和 tab 切换(CDP 模式无 currentTabId 竞态)
637
- if (!this.extensionBridge?.isConnected()) {
638
- if (tabId) {
833
+ async withTabId(targetId, fn, deadline) {
834
+ return this.withTabLock(async () => {
835
+ const remaining = () => (deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
836
+ const mode = this.getMode();
837
+ if (!targetId) {
838
+ const current = this.getCurrentTargetId();
839
+ if (current) {
840
+ this.recordPageUse(current);
841
+ }
639
842
  const previousRequireExtension = this.requireExtension;
640
- this.requireExtension = true;
843
+ const previousCdpSelection = this.cdpExplicitlySelected;
844
+ if (mode === 'extension') {
845
+ this.requireExtension = true;
846
+ }
847
+ else if (mode === 'cdp') {
848
+ this.cdpExplicitlySelected = true;
849
+ }
641
850
  try {
642
- this.assertCdpFallbackAllowed();
851
+ return await fn();
643
852
  }
644
853
  finally {
645
854
  this.requireExtension = previousRequireExtension;
855
+ this.cdpExplicitlySelected = previousCdpSelection;
646
856
  }
647
857
  }
648
- return fn();
858
+ if (mode === 'none') {
859
+ throw new DriverCapabilityError('浏览器未连接,无法选择目标页面');
860
+ }
861
+ const driver = mode === 'extension' ? this.extensionBridge : getCdpSession();
862
+ const targets = await driver.listTargets(remaining());
863
+ if (!targets.some((target) => (target.targetId ?? String(target.id)) === targetId)) {
864
+ throw new DriverCapabilityError(`目标页面 ${targetId} 不存在于当前 ${mode} 连接`);
865
+ }
866
+ const previousId = driver.getCurrentTargetId();
867
+ const previousRequireExtension = this.requireExtension;
868
+ const previousCdpSelection = this.cdpExplicitlySelected;
869
+ const previousMode = this.activeMode;
870
+ if (mode === 'extension') {
871
+ this.requireExtension = true;
872
+ }
873
+ else {
874
+ this.cdpExplicitlySelected = true;
875
+ }
876
+ try {
877
+ if (targetId !== previousId) {
878
+ await driver.selectPage(targetId, remaining());
879
+ }
880
+ this.activeMode = mode;
881
+ this.recordPageUse(targetId);
882
+ return await fn();
883
+ }
884
+ finally {
885
+ this.requireExtension = previousRequireExtension;
886
+ this.cdpExplicitlySelected = previousCdpSelection;
887
+ this.activeMode = previousMode;
888
+ if (targetId !== previousId) {
889
+ const restoration = {
890
+ status: previousId ? 'restored' : 'cleared',
891
+ previousTargetId: previousId,
892
+ temporaryTargetId: targetId,
893
+ currentTargetId: null,
894
+ };
895
+ let clearTarget = true;
896
+ try {
897
+ if (previousId) {
898
+ const targets = await driver.listTargets(remaining());
899
+ if (targets.some((target) => (target.targetId ?? String(target.id)) === previousId)) {
900
+ await driver.selectPage(previousId, remaining());
901
+ clearTarget = false;
902
+ }
903
+ else {
904
+ restoration.status = 'previous_target_closed';
905
+ }
906
+ }
907
+ }
908
+ catch (error) {
909
+ restoration.status = 'failed';
910
+ restoration.error = error instanceof Error ? error.message : String(error);
911
+ }
912
+ if (clearTarget) {
913
+ try {
914
+ if (mode === 'extension') {
915
+ driver.setCurrentTargetId(null);
916
+ }
917
+ else {
918
+ await getCdpSession().deselectPage(deadline === undefined ? undefined : Math.max(0, deadline - Date.now()));
919
+ }
920
+ }
921
+ catch (error) {
922
+ const message = error instanceof Error ? error.message : String(error);
923
+ if (restoration.error) {
924
+ restoration.cleanupError = message;
925
+ }
926
+ else {
927
+ restoration.status = 'failed';
928
+ restoration.error = message;
929
+ }
930
+ }
931
+ }
932
+ restoration.currentTargetId = driver.getCurrentTargetId();
933
+ this.tabLockContext.getStore().targetRestoration = restoration;
934
+ }
935
+ }
936
+ }, deadline);
937
+ }
938
+ getTargetRestoration() {
939
+ return this.tabLockContext.getStore()?.targetRestoration;
940
+ }
941
+ async getPageSnapshot(targetId, timeout) {
942
+ const mode = this.getMode();
943
+ if (mode === 'none') {
944
+ throw new DriverCapabilityError('浏览器未连接,无法读取页面状态');
649
945
  }
650
- if (!tabId) {
651
- // 不切换 tab,但需要加锁保护 currentTabId 不被并发修改
652
- return this.withTabLock(fn);
946
+ const id = targetId ?? this.getCurrentTargetId();
947
+ if (!id) {
948
+ throw new DriverCapabilityError('没有操作目标,请先选择页面');
949
+ }
950
+ const snapshot = mode === 'extension'
951
+ ? await this.extensionBridge.getPageSnapshot(id, timeout)
952
+ : await getCdpSession().getPageSnapshot(id, timeout);
953
+ this.recordPageUse(id);
954
+ return snapshot;
955
+ }
956
+ async withPageCondition(condition, fn, deadline) {
957
+ if (condition.expectedUrl === undefined && condition.expectedRevision === undefined) {
958
+ return fn();
653
959
  }
654
- const driver = this.extensionBridge;
655
960
  return this.withTabLock(async () => {
656
- const previousTargetId = driver.getCurrentTargetId();
657
- // 临时切换用 setCurrentTargetId,跳过 managed 校验(tabId 仅用于读取/执行,不改变持久 attach 目标)
658
- driver.setCurrentTargetId(tabId);
659
- // tabId 明确指定时,禁止 CDP 回退(CDP 不感知 Extension tab)
961
+ const mode = this.getMode();
962
+ const targetId = condition.targetId ?? this.getCurrentTargetId();
963
+ if (mode === 'none' || !targetId) {
964
+ throw new DriverCapabilityError('没有操作目标,请先选择页面');
965
+ }
966
+ const driver = mode === 'extension' ? this.extensionBridge : getCdpSession();
660
967
  const previousRequireExtension = this.requireExtension;
661
- const previousActiveMode = this.activeMode;
662
- this.requireExtension = true;
663
- this.activeMode = 'extension';
968
+ const previousCdpSelection = this.cdpExplicitlySelected;
969
+ const previousMode = this.activeMode;
970
+ if (mode === 'extension') {
971
+ this.requireExtension = true;
972
+ }
973
+ else {
974
+ this.cdpExplicitlySelected = true;
975
+ }
664
976
  try {
977
+ const snapshot = await driver.getPageSnapshot(targetId, deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
978
+ if (snapshot.revision === null) {
979
+ throw new StructuredToolError('DRIVER_CAPABILITY_ERROR', '当前 Extension 不支持原子页面条件,未执行操作', '更新 Extension 后再使用 expectedUrl 或 expectedRevision', { targetId, actionExecuted: false, actionStatus: 'not_started', failureStage: 'precondition' });
980
+ }
981
+ if ((condition.expectedUrl !== undefined && snapshot.url !== condition.expectedUrl) ||
982
+ (condition.expectedRevision !== undefined && snapshot.revision !== condition.expectedRevision)) {
983
+ throw new PagePreconditionError({
984
+ targetId,
985
+ expectedUrl: condition.expectedUrl ?? null,
986
+ expectedRevision: condition.expectedRevision ?? null,
987
+ actualUrl: snapshot.url,
988
+ actualRevision: snapshot.revision,
989
+ });
990
+ }
991
+ driver.setPageCondition({
992
+ targetId,
993
+ expectedUrl: condition.expectedUrl,
994
+ expectedRevision: condition.expectedRevision,
995
+ });
665
996
  return await fn();
666
997
  }
667
998
  finally {
999
+ driver.setPageCondition(null);
668
1000
  this.requireExtension = previousRequireExtension;
669
- this.activeMode = previousActiveMode;
670
- driver.setCurrentTargetId(previousTargetId);
1001
+ this.cdpExplicitlySelected = previousCdpSelection;
1002
+ this.activeMode = previousMode;
671
1003
  }
672
- });
1004
+ }, deadline);
673
1005
  }
674
1006
  /**
675
1007
  * 临时切换操作目标 iframe,执行完后恢复
@@ -688,7 +1020,7 @@ class UnifiedSessionManager {
688
1020
  throw new Error('iframe 穿透需要 Extension 模式');
689
1021
  }
690
1022
  const driver = this.extensionBridge;
691
- const { frameId, offset } = await driver.resolveFrame(frame);
1023
+ const { frameId, offset, frameContext } = await driver.resolveFrame(frame);
692
1024
  const previousFrameId = driver.getCurrentFrameId();
693
1025
  const previousFrameOffset = this.currentFrameOffset;
694
1026
  const previousRequireExtension = this.requireExtension;
@@ -700,6 +1032,11 @@ class UnifiedSessionManager {
700
1032
  try {
701
1033
  return await fn();
702
1034
  }
1035
+ catch (error) {
1036
+ throw setErrorPageContext(error, {
1037
+ frameContext: { selection: frame, frameId, ...frameContext },
1038
+ });
1039
+ }
703
1040
  finally {
704
1041
  // 字段赋值不会 throw,driver.setCurrentFrameId 是同步函数也不会 throw,无需嵌套 try
705
1042
  this.requireExtension = previousRequireExtension;
@@ -760,6 +1097,12 @@ class UnifiedSessionManager {
760
1097
  // Puppeteer 风格:连续 keyDown 同 key → rawKeyDown + autoRepeat(长按重复)
761
1098
  const isRepeat = this.pressedKeys.has(key);
762
1099
  const nextModifiers = MODIFIER_KEYS[key] ? this.modifiers | MODIFIER_KEYS[key] : this.modifiers;
1100
+ if (!isExt) {
1101
+ await getCdpSession().keyDown(key, commands, { rawKeyDown: isRepeat, autoRepeat: isRepeat });
1102
+ this.modifiers = nextModifiers;
1103
+ this.pressedKeys.add(key);
1104
+ return;
1105
+ }
763
1106
  if (isExt && this.inputMode === 'stealth') {
764
1107
  await driver.stealthKey(key, 'down', this.getModifierNames(nextModifiers));
765
1108
  this.modifiers = nextModifiers;
@@ -786,7 +1129,10 @@ class UnifiedSessionManager {
786
1129
  const driver = await this.getDriver();
787
1130
  const isExt = this.isExtensionConnected();
788
1131
  const nextModifiers = MODIFIER_KEYS[key] ? this.modifiers & ~MODIFIER_KEYS[key] : this.modifiers;
789
- if (isExt && this.inputMode === 'stealth') {
1132
+ if (!isExt) {
1133
+ await getCdpSession().keyUp(key);
1134
+ }
1135
+ else if (this.inputMode === 'stealth') {
790
1136
  await driver.stealthKey(key, 'up', this.getModifierNames(nextModifiers));
791
1137
  }
792
1138
  else {
@@ -804,28 +1150,35 @@ class UnifiedSessionManager {
804
1150
  /**
805
1151
  * 输入文本
806
1152
  */
807
- async typeText(text, delay = 0) {
1153
+ async typeText(text, delay = 0, timeout) {
1154
+ const startedAt = Date.now();
808
1155
  const driver = await this.getDriver();
1156
+ const remaining = timeout === undefined ? undefined : Math.max(0, timeout - (Date.now() - startedAt));
809
1157
  const isExt = this.isExtensionConnected();
810
1158
  if (isExt && this.inputMode === 'stealth') {
811
- await driver.stealthType(text, delay);
1159
+ await driver.stealthType(text, delay, remaining);
812
1160
  }
813
1161
  else {
814
- await driver.inputType(text, delay);
1162
+ await driver.inputType(text, delay, remaining);
815
1163
  }
816
1164
  }
817
1165
  /**
818
1166
  * 鼠标移动
819
1167
  */
820
- async mouseMove(x, y) {
1168
+ async mouseMove(x, y, timeout) {
1169
+ const startedAt = Date.now();
1170
+ const driver = await this.getDriver(timeout);
1171
+ const remaining = timeout === undefined ? undefined : timeout - (Date.now() - startedAt);
1172
+ if (remaining !== undefined && remaining <= 0) {
1173
+ throw new TimeoutError('input timeout before mouse movement');
1174
+ }
821
1175
  this.currentMousePosition = { x, y }; // 更新位置
822
- const driver = await this.getDriver();
823
1176
  const isExt = this.isExtensionConnected();
824
1177
  if (isExt && this.inputMode === 'stealth') {
825
- await driver.stealthMouse('mousemove', x, y);
1178
+ await driver.stealthMouse('mousemove', x, y, undefined, remaining);
826
1179
  }
827
1180
  else {
828
- await driver.inputMouse('mouseMoved', x, y, { modifiers: this.modifiers });
1181
+ await driver.inputMouse('mouseMoved', x, y, { modifiers: this.modifiers }, remaining);
829
1182
  }
830
1183
  }
831
1184
  /**
@@ -890,18 +1243,31 @@ class UnifiedSessionManager {
890
1243
  * Turnstile 点击:同页控件走页面鼠标;Cloudflare iframe 只在已聚焦窗口的活动受控 tab 上使用系统鼠标
891
1244
  */
892
1245
  // noinspection JSUnusedGlobalSymbols — resolveChallenge 通过 ChallengeHost 结构类型调用
893
- async clickTurnstile(snapshot) {
1246
+ async clickTurnstile(snapshot, timeout) {
1247
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
1248
+ const remaining = () => (deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
894
1249
  if (snapshot.clickSource !== 'iframe') {
895
1250
  const point = snapshot.clickPoint;
896
1251
  if (!point) {
897
1252
  throw new OsMouseError('TURNSTILE_OS_CLICK_UNAVAILABLE', '页面未返回可点击的 Turnstile 坐标', '重新检查页面状态后再重试;交互式验证码无法自动完成');
898
1253
  }
1254
+ const driver = await withNavigationBudget(() => this.getDriver(remaining()), deadline);
1255
+ if (this.isExtensionConnected()) {
1256
+ await withNavigationBudget(() => driver.stealthClick(point.x, point.y, 'left', 1, undefined, remaining()), deadline);
1257
+ return;
1258
+ }
899
1259
  const frameOffset = this.currentFrameOffset;
900
1260
  const clickPoint = frameOffset && this.inputMode !== 'stealth'
901
1261
  ? { x: point.x + frameOffset.x, y: point.y + frameOffset.y }
902
1262
  : point;
903
- await this.mouseMove(clickPoint.x, clickPoint.y);
904
- await this.mouseClick('left');
1263
+ this.currentMousePosition = clickPoint;
1264
+ await withNavigationBudget(() => driver.inputMouse('mouseMoved', clickPoint.x, clickPoint.y, { modifiers: this.modifiers }), deadline);
1265
+ await withNavigationBudget(() => getCdpSession().inputMouse('mousePressed', clickPoint.x, clickPoint.y, {
1266
+ button: 'left',
1267
+ clickCount: 1,
1268
+ modifiers: this.modifiers,
1269
+ releaseAfterPress: true,
1270
+ }, remaining()), deadline);
905
1271
  return;
906
1272
  }
907
1273
  if (this.getMode() !== 'extension' || !this.extensionBridge) {
@@ -911,7 +1277,7 @@ class UnifiedSessionManager {
911
1277
  if (!targetId) {
912
1278
  throw new OsMouseError('TURNSTILE_OS_CLICK_UNAVAILABLE', '没有当前受控页面,无法使用系统鼠标点击 Turnstile', '先 browse attach 到受控测试页,把该页放到已经聚焦的窗口并保持为活动 tab 后重试');
913
1279
  }
914
- const topology = await this.listTopology();
1280
+ const topology = await this.listTopology(remaining());
915
1281
  const windowInfo = topology?.windows.find((item) => item.tabs.some((tab) => String(tab.id) === targetId || tab.targetId === targetId));
916
1282
  const tab = windowInfo?.tabs.find((item) => String(item.id) === targetId || item.targetId === targetId);
917
1283
  if (!windowInfo || !tab) {
@@ -927,9 +1293,9 @@ class UnifiedSessionManager {
927
1293
  if (tab.active !== true && (activeTabId === undefined || String(activeTabId) !== targetId)) {
928
1294
  throw new OsMouseError('TURNSTILE_OS_CLICK_UNAVAILABLE', '受控测试页不是当前窗口的活动 tab,拒绝系统鼠标点击', '先把受控测试页设为该窗口的活动 tab,且窗口已经聚焦后再重试');
929
1295
  }
930
- await this.extensionBridge.debuggerDetach();
931
- const viewport = await this.readViewportMetrics(0);
932
- const refreshedTopology = await this.listTopology();
1296
+ await withNavigationBudget(() => this.extensionBridge.debuggerDetach(undefined, remaining()), deadline);
1297
+ const viewport = await withNavigationBudget(() => this.readViewportMetrics(0), deadline);
1298
+ const refreshedTopology = await this.listTopology(remaining());
933
1299
  const refreshedWindow = refreshedTopology?.windows.find((item) => item.tabs.some((candidate) => String(candidate.id) === targetId || candidate.targetId === targetId));
934
1300
  const refreshedTab = refreshedWindow?.tabs.find((candidate) => String(candidate.id) === targetId || candidate.targetId === targetId);
935
1301
  const refreshedActiveTabId = refreshedWindow?.activeTabId;
@@ -943,21 +1309,22 @@ class UnifiedSessionManager {
943
1309
  const clickPoint = snapshot.clickPoint && frameOffset
944
1310
  ? { x: snapshot.clickPoint.x + frameOffset.x, y: snapshot.clickPoint.y + frameOffset.y }
945
1311
  : snapshot.clickPoint;
946
- const screen = await resolveTurnstileOsClickPoint({
1312
+ const screen = await withNavigationBudget(() => resolveTurnstileOsClickPoint({
947
1313
  ...snapshot,
948
1314
  clickPoint,
949
1315
  screenPoint: null,
950
1316
  viewport,
951
- });
952
- await osLeftClick(screen.x, screen.y);
1317
+ }, { deadline }), deadline);
1318
+ await withNavigationBudget(() => osLeftClick(screen.x, screen.y, { deadline }), deadline);
953
1319
  }
954
1320
  // noinspection JSUnusedGlobalSymbols — resolveChallenge 通过 ChallengeHost 结构类型调用
955
1321
  async inspectChallenge(options, timeout) {
956
1322
  if (this.getMode() !== 'extension' || !this.extensionBridge) {
957
1323
  throw new Error('challenge_inspect 仅在 Extension 模式可用');
958
1324
  }
959
- await this.extensionBridge.debuggerDetach();
960
- return this.extensionBridge.inspectChallenge(options, timeout);
1325
+ const deadline = timeout === undefined ? undefined : Date.now() + timeout;
1326
+ await withNavigationBudget(() => this.extensionBridge.debuggerDetach(undefined, deadline === undefined ? undefined : remainingNavigationTimeout(deadline)), deadline);
1327
+ return this.extensionBridge.inspectChallenge(options, deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
961
1328
  }
962
1329
  /**
963
1330
  * 鼠标滚轮
@@ -1058,15 +1425,34 @@ class UnifiedSessionManager {
1058
1425
  const driver = await this.getDriver();
1059
1426
  return driver.debuggerSend(method, params);
1060
1427
  }
1428
+ extensionReadBridge() {
1429
+ if (this.getMode() !== 'extension' || !this.extensionBridge?.isConnected()) {
1430
+ throw new DriverCapabilityError('定向读取需要已连接的 Extension');
1431
+ }
1432
+ return this.extensionBridge;
1433
+ }
1434
+ metadataKey(targetId) {
1435
+ return `${this.getMode()}:${targetId}`;
1436
+ }
1437
+ recordPageUse(targetId, created = false) {
1438
+ const metadata = this.getPageMetadata(targetId);
1439
+ this.pageMetadata.set(this.metadataKey(targetId), {
1440
+ ...metadata,
1441
+ createdBy: created ? 'mcp-chrome' : metadata.createdBy,
1442
+ createdAt: created ? new Date().toISOString() : metadata.createdAt,
1443
+ lastUsedAt: new Date().toISOString(),
1444
+ });
1445
+ }
1061
1446
  evaluateViaCdp(script, args, timeout) {
1062
1447
  return getCdpSession().evaluate(script, args, timeout);
1063
1448
  }
1064
- async evaluateViaExtensionPrecise(code, expression, args, timeout, staleContextRetry = 'never') {
1065
- const hasArgs = args !== undefined && args.length > 0;
1449
+ async evaluateViaExtensionPrecise(code, expression, args, timeout, options = {}) {
1450
+ const hasArgs = args !== undefined;
1066
1451
  const currentFrameId = this.extensionBridge.getCurrentFrameId();
1452
+ const staleContextRetry = options.staleContextRetry ?? 'never';
1067
1453
  // precise + args + 主 frame:使用 callFunctionOn 避免大 payload 字符串拼接
1068
1454
  if (hasArgs && currentFrameId === 0) {
1069
- return this.callFunctionOn(code, args, timeout);
1455
+ return this.callFunctionOn(code, args, timeout, options);
1070
1456
  }
1071
1457
  if (currentFrameId !== 0) {
1072
1458
  // iframe:args 仍用字符串拼接(evaluateInFrame 使用 expression 字符串)
@@ -1098,7 +1484,7 @@ class UnifiedSessionManager {
1098
1484
  if (result.exceptionDetails) {
1099
1485
  throw new Error(formatCdpException(result.exceptionDetails));
1100
1486
  }
1101
- return this.materializeCdpResult(result.result, timeout);
1487
+ return this.materializeCdpResult(result.result, timeout, options.fileOutput);
1102
1488
  }
1103
1489
  async evaluateViaExtensionStealth(expression, timeout) {
1104
1490
  return (await this.extensionBridge.evaluate(expression, undefined, timeout));
@@ -1171,12 +1557,19 @@ class UnifiedSessionManager {
1171
1557
  }
1172
1558
  return extractCdpValue(result.result);
1173
1559
  }
1174
- async materializeCdpResult(result, timeout) {
1560
+ async materializeCdpResult(result, timeout, fileOutput = false) {
1175
1561
  if (!result?.objectId) {
1176
1562
  return extractCdpValue(result);
1177
1563
  }
1178
1564
  try {
1179
- return await this.materializeRemoteObject(result, timeout, { seen: new Set(), nodes: 0, chars: 0 }, 0);
1565
+ return await this.materializeRemoteObject(result, timeout, {
1566
+ seen: new Set(),
1567
+ nodes: 0,
1568
+ chars: 0,
1569
+ maxChars: fileOutput
1570
+ ? UnifiedSessionManager.CDP_MATERIALIZE_MAX_FILE_CHARS
1571
+ : UnifiedSessionManager.CDP_MATERIALIZE_MAX_CHARS,
1572
+ }, 0);
1180
1573
  }
1181
1574
  finally {
1182
1575
  this.extensionBridge.debuggerSend('Runtime.releaseObject', { objectId: result.objectId }).catch(() => { });
@@ -1273,7 +1666,7 @@ class UnifiedSessionManager {
1273
1666
  assertMaterializeBudget(state, depth, result) {
1274
1667
  if (depth > UnifiedSessionManager.CDP_MATERIALIZE_MAX_DEPTH ||
1275
1668
  state.nodes > UnifiedSessionManager.CDP_MATERIALIZE_MAX_NODES ||
1276
- state.chars > UnifiedSessionManager.CDP_MATERIALIZE_MAX_CHARS) {
1669
+ state.chars > state.maxChars) {
1277
1670
  this.throwMaterializeLimit(state, depth, result);
1278
1671
  }
1279
1672
  }
@@ -1290,7 +1683,7 @@ class UnifiedSessionManager {
1290
1683
  chars: state.chars,
1291
1684
  maxDepth: UnifiedSessionManager.CDP_MATERIALIZE_MAX_DEPTH,
1292
1685
  maxNodes: UnifiedSessionManager.CDP_MATERIALIZE_MAX_NODES,
1293
- maxChars: UnifiedSessionManager.CDP_MATERIALIZE_MAX_CHARS,
1686
+ maxChars: state.maxChars,
1294
1687
  type: result?.type,
1295
1688
  subtype: result?.subtype,
1296
1689
  className: result?.className,
@@ -1383,7 +1776,7 @@ class UnifiedSessionManager {
1383
1776
  * 参数通过 CDP 协议结构化传递,避免大 payload 字符串拼接导致的长度限制和转义问题,
1384
1777
  * 要求 code 必须是函数表达式(如 "(x) => x + 1")
1385
1778
  */
1386
- async callFunctionOn(code, args, timeout) {
1779
+ async callFunctionOn(code, args, timeout, options = {}) {
1387
1780
  const buildFallbackExpression = () => `(${code})(${args.map((a) => JSON.stringify(a)).join(', ')})`;
1388
1781
  const globalResult = (await this.extensionBridge.debuggerSend('Runtime.evaluate', {
1389
1782
  expression: 'globalThis',
@@ -1393,7 +1786,7 @@ class UnifiedSessionManager {
1393
1786
  if (!globalObjectId) {
1394
1787
  console.warn('[MCP] Runtime.evaluate 未返回 globalThis objectId,改用表达式传递 evaluate args');
1395
1788
  const fallbackExpression = buildFallbackExpression();
1396
- return this.evaluateViaExtensionPrecise(fallbackExpression, fallbackExpression, undefined, timeout);
1789
+ return this.evaluateViaExtensionPrecise(fallbackExpression, fallbackExpression, undefined, timeout, options);
1397
1790
  }
1398
1791
  try {
1399
1792
  const params = {
@@ -1410,7 +1803,7 @@ class UnifiedSessionManager {
1410
1803
  if (result.exceptionDetails) {
1411
1804
  throw new Error(formatCdpException(result.exceptionDetails));
1412
1805
  }
1413
- return await this.materializeCdpResult(result.result, timeout);
1806
+ return await this.materializeCdpResult(result.result, timeout, options.fileOutput);
1414
1807
  }
1415
1808
  finally {
1416
1809
  this.extensionBridge.debuggerSend('Runtime.releaseObject', {
@@ -1418,27 +1811,6 @@ class UnifiedSessionManager {
1418
1811
  }).catch(() => { });
1419
1812
  }
1420
1813
  }
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
1814
  }
1443
1815
  /**
1444
1816
  * 获取统一会话管理器实例