@pyrokine/mcp-chrome 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +721 -303
  2. package/README_zh.md +750 -292
  3. package/dist/cdp/client.d.ts +7 -3
  4. package/dist/cdp/client.d.ts.map +1 -1
  5. package/dist/cdp/client.js +252 -63
  6. package/dist/cdp/client.js.map +1 -1
  7. package/dist/cdp/launcher.d.ts +1 -1
  8. package/dist/cdp/launcher.d.ts.map +1 -1
  9. package/dist/cdp/launcher.js +33 -12
  10. package/dist/cdp/launcher.js.map +1 -1
  11. package/dist/core/auto-wait.d.ts.map +1 -1
  12. package/dist/core/auto-wait.js +88 -52
  13. package/dist/core/auto-wait.js.map +1 -1
  14. package/dist/core/browser-driver.d.ts +76 -18
  15. package/dist/core/browser-driver.d.ts.map +1 -1
  16. package/dist/core/browser-driver.js.map +1 -1
  17. package/dist/core/browser-event-schema.d.ts +287 -0
  18. package/dist/core/browser-event-schema.d.ts.map +1 -0
  19. package/dist/core/browser-event-schema.js +104 -0
  20. package/dist/core/browser-event-schema.js.map +1 -0
  21. package/dist/core/browser-events.d.ts +99 -0
  22. package/dist/core/browser-events.d.ts.map +1 -0
  23. package/dist/core/browser-events.js +1312 -0
  24. package/dist/core/browser-events.js.map +1 -0
  25. package/dist/core/challenge-page.d.ts +39 -0
  26. package/dist/core/challenge-page.d.ts.map +1 -0
  27. package/dist/core/challenge-page.js +226 -0
  28. package/dist/core/challenge-page.js.map +1 -0
  29. package/dist/core/dom-helpers.d.ts +28 -0
  30. package/dist/core/dom-helpers.d.ts.map +1 -0
  31. package/dist/core/dom-helpers.js +311 -0
  32. package/dist/core/dom-helpers.js.map +1 -0
  33. package/dist/core/errors.d.ts +10 -4
  34. package/dist/core/errors.d.ts.map +1 -1
  35. package/dist/core/errors.js +63 -13
  36. package/dist/core/errors.js.map +1 -1
  37. package/dist/core/file-upload.d.ts +22 -0
  38. package/dist/core/file-upload.d.ts.map +1 -0
  39. package/dist/core/file-upload.js +194 -0
  40. package/dist/core/file-upload.js.map +1 -0
  41. package/dist/core/locator.d.ts +17 -2
  42. package/dist/core/locator.d.ts.map +1 -1
  43. package/dist/core/locator.js +156 -212
  44. package/dist/core/locator.js.map +1 -1
  45. package/dist/core/os-mouse.d.ts +11 -0
  46. package/dist/core/os-mouse.d.ts.map +1 -1
  47. package/dist/core/os-mouse.js +102 -29
  48. package/dist/core/os-mouse.js.map +1 -1
  49. package/dist/core/retry.d.ts.map +1 -1
  50. package/dist/core/retry.js +4 -1
  51. package/dist/core/retry.js.map +1 -1
  52. package/dist/core/session.d.ts +65 -14
  53. package/dist/core/session.d.ts.map +1 -1
  54. package/dist/core/session.js +1089 -273
  55. package/dist/core/session.js.map +1 -1
  56. package/dist/core/types.d.ts +5 -1
  57. package/dist/core/types.d.ts.map +1 -1
  58. package/dist/core/types.js +16 -1
  59. package/dist/core/types.js.map +1 -1
  60. package/dist/core/unified-session.d.ts +50 -41
  61. package/dist/core/unified-session.d.ts.map +1 -1
  62. package/dist/core/unified-session.js +938 -285
  63. package/dist/core/unified-session.js.map +1 -1
  64. package/dist/core/utils.d.ts +5 -4
  65. package/dist/core/utils.d.ts.map +1 -1
  66. package/dist/core/utils.js +73 -18
  67. package/dist/core/utils.js.map +1 -1
  68. package/dist/extension/bridge.d.ts +50 -19
  69. package/dist/extension/bridge.d.ts.map +1 -1
  70. package/dist/extension/bridge.js +289 -57
  71. package/dist/extension/bridge.js.map +1 -1
  72. package/dist/extension/http-server.d.ts +7 -2
  73. package/dist/extension/http-server.d.ts.map +1 -1
  74. package/dist/extension/http-server.js +219 -48
  75. package/dist/extension/http-server.js.map +1 -1
  76. package/dist/index.js +14 -1
  77. package/dist/index.js.map +1 -1
  78. package/dist/tools/browse.d.ts.map +1 -1
  79. package/dist/tools/browse.js +66 -32
  80. package/dist/tools/browse.js.map +1 -1
  81. package/dist/tools/browser-event-output.d.ts +7 -0
  82. package/dist/tools/browser-event-output.d.ts.map +1 -0
  83. package/dist/tools/browser-event-output.js +19 -0
  84. package/dist/tools/browser-event-output.js.map +1 -0
  85. package/dist/tools/challenge.d.ts +17 -5
  86. package/dist/tools/challenge.d.ts.map +1 -1
  87. package/dist/tools/challenge.js +113 -195
  88. package/dist/tools/challenge.js.map +1 -1
  89. package/dist/tools/cookies.d.ts.map +1 -1
  90. package/dist/tools/cookies.js +33 -8
  91. package/dist/tools/cookies.js.map +1 -1
  92. package/dist/tools/diagnostics.d.ts.map +1 -1
  93. package/dist/tools/diagnostics.js +14 -0
  94. package/dist/tools/diagnostics.js.map +1 -1
  95. package/dist/tools/evaluate.d.ts +6 -5
  96. package/dist/tools/evaluate.d.ts.map +1 -1
  97. package/dist/tools/evaluate.js +102 -52
  98. package/dist/tools/evaluate.js.map +1 -1
  99. package/dist/tools/extract.d.ts.map +1 -1
  100. package/dist/tools/extract.js +178 -124
  101. package/dist/tools/extract.js.map +1 -1
  102. package/dist/tools/input.d.ts.map +1 -1
  103. package/dist/tools/input.js +623 -271
  104. package/dist/tools/input.js.map +1 -1
  105. package/dist/tools/logs.d.ts.map +1 -1
  106. package/dist/tools/logs.js +50 -11
  107. package/dist/tools/logs.js.map +1 -1
  108. package/dist/tools/manage.d.ts.map +1 -1
  109. package/dist/tools/manage.js +127 -46
  110. package/dist/tools/manage.js.map +1 -1
  111. package/dist/tools/network-sanitizer.d.ts +1 -0
  112. package/dist/tools/network-sanitizer.d.ts.map +1 -1
  113. package/dist/tools/network-sanitizer.js +30 -1
  114. package/dist/tools/network-sanitizer.js.map +1 -1
  115. package/dist/tools/page-context.d.ts +4 -3
  116. package/dist/tools/page-context.d.ts.map +1 -1
  117. package/dist/tools/page-context.js +56 -14
  118. package/dist/tools/page-context.js.map +1 -1
  119. package/dist/tools/post-condition.d.ts +1 -1
  120. package/dist/tools/post-condition.d.ts.map +1 -1
  121. package/dist/tools/post-condition.js +153 -47
  122. package/dist/tools/post-condition.js.map +1 -1
  123. package/dist/tools/schema.d.ts +7 -4
  124. package/dist/tools/schema.d.ts.map +1 -1
  125. package/dist/tools/schema.js +32 -122
  126. package/dist/tools/schema.js.map +1 -1
  127. package/dist/tools/target-diagnostics.d.ts +10 -2
  128. package/dist/tools/target-diagnostics.d.ts.map +1 -1
  129. package/dist/tools/target-diagnostics.js +74 -21
  130. package/dist/tools/target-diagnostics.js.map +1 -1
  131. package/dist/tools/wait.d.ts.map +1 -1
  132. package/dist/tools/wait.js +108 -42
  133. package/dist/tools/wait.js.map +1 -1
  134. package/extension/dist/assets/{content.ts-C4imZ6A9.js → content.ts-BAMOcF3R.js} +1 -1
  135. package/extension/dist/assets/{content.ts-loader-CnJuCGhl.js → content.ts-loader-4F9a1EWZ.js} +1 -1
  136. package/extension/dist/assets/index.ts-B79g2ikq.js +19820 -0
  137. package/extension/dist/assets/{page-scripts-CMIY1zhd.js → page-scripts-CSxn58h1.js} +300 -410
  138. package/extension/dist/assets/{popup.html-CgtWL6Py.js → popup.html-DwwHo00N.js} +8 -6
  139. package/extension/dist/manifest.json +4 -4
  140. package/extension/dist/service-worker-loader.js +1 -1
  141. package/extension/dist/src/popup/popup.html +3 -3
  142. package/package.json +15 -7
  143. package/scripts/start-chrome.ps1 +9 -1
  144. package/extension/dist/assets/index.ts-GeHNZBml.js +0 -8972
@@ -8,15 +8,18 @@
8
8
  * - 日志收集
9
9
  */
10
10
  import { randomUUID } from 'node:crypto';
11
+ import { BROWSER_EVENT_METHODS, BrowserEventController, eventRefTarget, } from './browser-events.js';
12
+ import { browserEventCommandSchema } from './browser-event-schema.js';
13
+ import { installDomHelpers } from './dom-helpers.js';
11
14
  import { BehaviorSimulator, getAntiDetectionScript } from '../anti-detection/index.js';
12
- import { assertScreenshotBase64Budget, assertScreenshotBudget } from '../tools/png.js';
13
15
  import { BrowserLauncher, CDPClient, getBrowserWSEndpoint, getTargets } from '../cdp/index.js';
16
+ import { assertScreenshotBase64Budget, assertScreenshotBudget } from '../tools/png.js';
14
17
  import { AutoWait } from './auto-wait.js';
15
18
  import { DriverCapabilityError, } from './browser-driver.js';
16
- import { CDPError, creationError, StructuredToolError, NavigationError, NavigationTimeoutError, PagePreconditionError, SessionNotFoundError, TargetNotFoundError, TimeoutError, } from './errors.js';
19
+ import { CDPError, creationError, ElementNotFoundError, formatErrorResponse, NavigationError, NavigationTimeoutError, PagePreconditionError, SessionNotFoundError, setErrorSource, StructuredToolError, TargetNotFoundError, TimeoutError, } from './errors.js';
17
20
  import { Locator } from './locator.js';
18
21
  import { DEFAULT_TIMEOUT, extractCdpValue, formatCdpException, MODIFIER_KEYS, } from './types.js';
19
- import { remainingNavigationTimeout, waitForNavigationQueue, withNavigationBudget } from './utils.js';
22
+ import { remainingNavigationTimeout, waitForNavigationQueue, withNavigationBudget, withNavigationMetadata, } from './utils.js';
20
23
  function wildcardSegmentMatches(value, segment, index) {
21
24
  if (index + segment.length > value.length) {
22
25
  return false;
@@ -70,6 +73,7 @@ class SessionManager {
70
73
  static instance;
71
74
  // 日志收集(环形缓冲区,限制最大条数避免内存泄漏)
72
75
  static MAX_LOG_ENTRIES = 1000;
76
+ requestContext;
73
77
  launcher = null;
74
78
  cdp = null;
75
79
  connectedPort = 0;
@@ -87,6 +91,7 @@ class SessionManager {
87
91
  operationLock = Promise.resolve();
88
92
  consoleLogs = [];
89
93
  networkRequests = [];
94
+ targetLogs = new Map();
90
95
  nextConsoleLogSequence = 0;
91
96
  nextNetworkRequestSequence = 0;
92
97
  challengeRequired = false;
@@ -96,6 +101,14 @@ class SessionManager {
96
101
  requestMap = new Map();
97
102
  // 监听器安装标志(防止重复安装)
98
103
  listenersInstalled = false;
104
+ targetSessions = new Map();
105
+ eventControllers = new Map();
106
+ childSessions = new Map();
107
+ frameSessions = new Map();
108
+ contexts = new Map();
109
+ frameScopes = new Map();
110
+ selectedFrame = 0;
111
+ nextFrameHandle = 0;
99
112
  constructor() { }
100
113
  /**
101
114
  * 获取当前调试端口
@@ -116,35 +129,85 @@ class SessionManager {
116
129
  * 只有连接失败时才启动新浏览器
117
130
  */
118
131
  async launch(options = {}) {
132
+ const scope = this.requestContext?.();
133
+ const signal = scope?.signal;
134
+ const deadline = Math.min(scope?.deadline ?? Infinity, Date.now() + (options.timeout ?? DEFAULT_TIMEOUT));
135
+ const remaining = () => {
136
+ signal?.throwIfAborted();
137
+ return remainingNavigationTimeout(deadline);
138
+ };
139
+ remaining();
119
140
  return this.withLock(async () => {
141
+ remaining();
120
142
  const port = options.port ?? 0;
143
+ const processParameters = [
144
+ options.executablePath,
145
+ options.headless,
146
+ options.userDataDir,
147
+ options.incognito,
148
+ ].some((value) => value !== undefined);
149
+ if (this.isConnected()) {
150
+ throw new DriverCapabilityError('已有 CDP 连接,未关闭或替换现有浏览器;请显式结束原连接后启动');
151
+ }
152
+ if (port > 0 && processParameters) {
153
+ try {
154
+ await getBrowserWSEndpoint('127.0.0.1', port, remaining(), signal);
155
+ }
156
+ catch (error) {
157
+ if (error instanceof TimeoutError) {
158
+ throw error;
159
+ }
160
+ remaining();
161
+ /* No running endpoint: the requested process options can be applied. */
162
+ }
163
+ const targets = await getTargets('127.0.0.1', port, remaining(), signal).catch((error) => {
164
+ if (error instanceof TimeoutError) {
165
+ throw error;
166
+ }
167
+ remaining();
168
+ return null;
169
+ });
170
+ remaining();
171
+ if (targets) {
172
+ throw new DriverCapabilityError('启动端口已有浏览器,无法对该进程应用显式启动参数,未创建页面');
173
+ }
174
+ }
121
175
  // 如果指定了端口,先尝试连接已运行的浏览器
122
- if (port > 0) {
176
+ if (port > 0 && !processParameters) {
177
+ let reuseClient;
123
178
  try {
124
- const endpoint = await getBrowserWSEndpoint('127.0.0.1', port);
179
+ const endpoint = await getBrowserWSEndpoint('127.0.0.1', port, remaining(), signal);
125
180
  // 连接成功,复用已有浏览器
181
+ remaining();
126
182
  this.resetState();
127
183
  this.stealthMode = options.stealth ?? 'safe';
128
- this.cdp = new CDPClient();
129
- await this.cdp.connect(endpoint, options.timeout);
184
+ reuseClient = new CDPClient(() => this.requestContext?.());
185
+ this.cdp = reuseClient;
186
+ await reuseClient.connect(endpoint, remaining());
187
+ remaining();
130
188
  // 记录端口(connect 模式没有 launcher)
131
189
  this.connectedPort = port;
132
190
  // 获取现有页面
133
- const targets = await getTargets('127.0.0.1', port);
191
+ const targets = await getTargets('127.0.0.1', port, remaining(), signal);
192
+ remaining();
134
193
  let pageTarget = targets.find((t) => t.type === 'page');
135
194
  // 如果没有页面或 attach 失败,创建新 tab
136
195
  if (pageTarget) {
137
196
  try {
138
- await this.attachToTargetInternal(pageTarget.id);
197
+ await this.attachToTargetInternal(pageTarget.id, deadline);
198
+ remaining();
139
199
  }
140
200
  catch {
201
+ remaining();
141
202
  // attach 失败,创建新 tab
142
203
  pageTarget = undefined;
143
204
  }
144
205
  }
145
206
  if (!pageTarget) {
146
207
  // 创建新 tab(在已有窗口)
208
+ remaining();
147
209
  const newTarget = await this.newPageInternal();
210
+ remaining();
148
211
  return {
149
212
  ...newTarget,
150
213
  reused: true,
@@ -160,35 +223,65 @@ class SessionManager {
160
223
  targetCreated: false,
161
224
  };
162
225
  }
163
- catch {
226
+ catch (error) {
227
+ reuseClient?.close();
228
+ if (this.cdp === reuseClient) {
229
+ this.cdp = null;
230
+ }
231
+ if (error instanceof TimeoutError) {
232
+ throw error;
233
+ }
234
+ remaining();
164
235
  // 连接失败,继续启动新浏览器
165
236
  }
166
237
  }
167
238
  // 关闭现有会话
239
+ remaining();
168
240
  this.resetState();
169
241
  // 保存 stealth 模式
170
242
  this.stealthMode = options.stealth ?? 'safe';
171
243
  // 启动浏览器
172
- this.launcher = new BrowserLauncher();
173
- const endpoint = await this.launcher.launch(options);
174
- // 连接 CDP
175
- this.cdp = new CDPClient();
176
- await this.cdp.connect(endpoint, options.timeout);
177
- // 获取第一个页面
178
- const targets = await getTargets('127.0.0.1', this.launcher.port);
179
- const pageTarget = targets.find((t) => t.type === 'page');
180
- if (!pageTarget) {
181
- throw new Error('未找到页面');
244
+ remaining();
245
+ const launcher = new BrowserLauncher();
246
+ this.launcher = launcher;
247
+ let client;
248
+ try {
249
+ const endpoint = await launcher.launch({ ...options, timeout: remaining() }, signal, deadline);
250
+ remaining();
251
+ // 连接 CDP
252
+ client = new CDPClient(() => this.requestContext?.());
253
+ this.cdp = client;
254
+ await client.connect(endpoint, remaining());
255
+ remaining();
256
+ // 获取第一个页面
257
+ const targets = await getTargets('127.0.0.1', launcher.port, remaining(), signal);
258
+ remaining();
259
+ const pageTarget = targets.find((t) => t.type === 'page');
260
+ if (!pageTarget) {
261
+ throw new Error('未找到页面');
262
+ }
263
+ // 附加到页面
264
+ await this.attachToTargetInternal(pageTarget.id, deadline);
265
+ remaining();
266
+ return {
267
+ targetId: pageTarget.id,
268
+ type: pageTarget.type,
269
+ url: pageTarget.url,
270
+ title: pageTarget.title,
271
+ };
182
272
  }
183
- // 附加到页面
184
- await this.attachToTargetInternal(pageTarget.id);
185
- return {
186
- targetId: pageTarget.id,
187
- type: pageTarget.type,
188
- url: pageTarget.url,
189
- title: pageTarget.title,
190
- };
191
- });
273
+ catch (error) {
274
+ client?.close();
275
+ if (this.cdp === client) {
276
+ this.cdp = null;
277
+ }
278
+ launcher.close();
279
+ if (this.launcher === launcher) {
280
+ this.launcher = null;
281
+ }
282
+ throw error;
283
+ }
284
+ }, deadline);
192
285
  }
193
286
  /**
194
287
  * 连接到已运行的浏览器
@@ -203,7 +296,7 @@ class SessionManager {
203
296
  // 获取 WebSocket 端点
204
297
  const endpoint = await getBrowserWSEndpoint(host, port);
205
298
  // 连接 CDP
206
- this.cdp = new CDPClient();
299
+ this.cdp = new CDPClient(() => this.requestContext?.());
207
300
  await this.cdp.connect(endpoint, timeout);
208
301
  this.connectedPort = port;
209
302
  // 获取第一个页面
@@ -229,6 +322,12 @@ class SessionManager {
229
322
  this.ensureConnected();
230
323
  // 从 CDP 获取 targets
231
324
  const { targetInfos } = (await this.sendBrowserCommand('Target.getTargets', undefined, timeout));
325
+ const liveIds = new Set(targetInfos.map((target) => target.targetId));
326
+ for (const targetId of this.targetLogs.keys()) {
327
+ if (!liveIds.has(targetId)) {
328
+ this.targetLogs.delete(targetId);
329
+ }
330
+ }
232
331
  return targetInfos
233
332
  .filter((t) => t.type === 'page')
234
333
  .map((t) => ({
@@ -255,12 +354,15 @@ class SessionManager {
255
354
  this.ensureSession();
256
355
  const { wait = 'load' } = options;
257
356
  const abortController = new AbortController();
258
- const navigationWait = this.startNavigationWait(wait, remainingNavigationTimeout(deadline), abortController.signal, false);
357
+ const requestSignal = this.requestContext?.()?.signal;
358
+ requestSignal?.throwIfAborted();
359
+ const navigationWait = this.startNavigationWait(wait, remainingNavigationTimeout(deadline), requestSignal ? AbortSignal.any([abortController.signal, requestSignal]) : abortController.signal, false);
259
360
  navigationWait.promise.catch(() => { });
260
361
  navigationWait.markActionStarted();
261
362
  try {
262
363
  const { frameId, loaderId, errorText } = (await this.send('Page.navigate', { url }, remainingNavigationTimeout(deadline)));
263
364
  if (errorText) {
365
+ // noinspection ExceptionCaughtLocallyJS -- Report failure
264
366
  throw new NavigationError(url, errorText);
265
367
  }
266
368
  if (loaderId) {
@@ -275,7 +377,7 @@ class SessionManager {
275
377
  throw error;
276
378
  }
277
379
  await navigationWait.promise;
278
- await this.updateState(remainingNavigationTimeout(deadline));
380
+ await withNavigationMetadata(() => this.updateState(remainingNavigationTimeout(deadline)));
279
381
  }, deadline);
280
382
  }
281
383
  /**
@@ -285,7 +387,7 @@ class SessionManager {
285
387
  */
286
388
  async waitForNetworkIdle(timeout, idleTime = 500) {
287
389
  this.ensureSession();
288
- return this.buildNetworkIdlePromise(this.cdp, timeout, idleTime);
390
+ return this.buildNetworkIdlePromise(this.cdp, timeout, idleTime, this.requestContext?.()?.signal);
289
391
  }
290
392
  /**
291
393
  * 等待导航完成(跨文档导航或同文档导航)
@@ -305,14 +407,21 @@ class SessionManager {
305
407
  if (currentIndex <= 0) {
306
408
  return { navigated: false };
307
409
  }
410
+ const abortController = new AbortController();
411
+ const requestSignal = this.requestContext?.()?.signal;
308
412
  // 跨文档加载、主 frame BFCache 恢复和同文档导航分别提供完成事件
309
- const waitPromise = this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument', 'Page.frameNavigated'], remainingNavigationTimeout(deadline));
310
- // 预注册 rejection handler:若 send() 抛错导致 waitPromise 永远不被 await,
311
- // 其 timer reject 不会成为 unhandled rejection(Node 20 默认会退出进程)
413
+ const waitPromise = this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument', 'Page.frameNavigated'], remainingNavigationTimeout(deadline), requestSignal ? AbortSignal.any([abortController.signal, requestSignal]) : abortController.signal);
414
+ // 预注册 rejection handler,发送失败时局部取消也会使等待 Promise reject
312
415
  waitPromise.catch(() => { });
313
- await this.send('Page.navigateToHistoryEntry', { entryId: entries[currentIndex - 1].id }, remainingNavigationTimeout(deadline));
416
+ try {
417
+ await this.send('Page.navigateToHistoryEntry', { entryId: entries[currentIndex - 1].id }, remainingNavigationTimeout(deadline));
418
+ }
419
+ catch (error) {
420
+ abortController.abort(error);
421
+ throw error;
422
+ }
314
423
  await waitPromise;
315
- await this.updateState(remainingNavigationTimeout(deadline));
424
+ await withNavigationMetadata(() => this.updateState(remainingNavigationTimeout(deadline)));
316
425
  return { navigated: true };
317
426
  }, deadline);
318
427
  }
@@ -327,12 +436,20 @@ class SessionManager {
327
436
  if (currentIndex >= entries.length - 1) {
328
437
  return { navigated: false };
329
438
  }
439
+ const abortController = new AbortController();
440
+ const requestSignal = this.requestContext?.()?.signal;
330
441
  // 跨文档加载、主 frame BFCache 恢复和同文档导航分别提供完成事件
331
- const waitPromise = this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument', 'Page.frameNavigated'], remainingNavigationTimeout(deadline));
442
+ const waitPromise = this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument', 'Page.frameNavigated'], remainingNavigationTimeout(deadline), requestSignal ? AbortSignal.any([abortController.signal, requestSignal]) : abortController.signal);
332
443
  waitPromise.catch(() => { });
333
- await this.send('Page.navigateToHistoryEntry', { entryId: entries[currentIndex + 1].id }, remainingNavigationTimeout(deadline));
444
+ try {
445
+ await this.send('Page.navigateToHistoryEntry', { entryId: entries[currentIndex + 1].id }, remainingNavigationTimeout(deadline));
446
+ }
447
+ catch (error) {
448
+ abortController.abort(error);
449
+ throw error;
450
+ }
334
451
  await waitPromise;
335
- await this.updateState(remainingNavigationTimeout(deadline));
452
+ await withNavigationMetadata(() => this.updateState(remainingNavigationTimeout(deadline)));
336
453
  return { navigated: true };
337
454
  }, deadline);
338
455
  }
@@ -344,7 +461,9 @@ class SessionManager {
344
461
  return this.withLock(async () => {
345
462
  this.ensureSession();
346
463
  const abortController = new AbortController();
347
- const navigationWait = this.startNavigationWait(waitUntil, remainingNavigationTimeout(deadline), abortController.signal, true);
464
+ const requestSignal = this.requestContext?.()?.signal;
465
+ requestSignal?.throwIfAborted();
466
+ const navigationWait = this.startNavigationWait(waitUntil, remainingNavigationTimeout(deadline), requestSignal ? AbortSignal.any([abortController.signal, requestSignal]) : abortController.signal, true);
348
467
  navigationWait.promise.catch(() => { });
349
468
  navigationWait.markActionStarted();
350
469
  try {
@@ -355,7 +474,7 @@ class SessionManager {
355
474
  throw error;
356
475
  }
357
476
  await navigationWait.promise;
358
- await this.updateState(remainingNavigationTimeout(deadline));
477
+ await withNavigationMetadata(() => this.updateState(remainingNavigationTimeout(deadline)));
359
478
  }, deadline);
360
479
  }
361
480
  /**
@@ -363,7 +482,23 @@ class SessionManager {
363
482
  */
364
483
  createLocator(target, options) {
365
484
  this.ensureSession();
366
- return new Locator(this.cdp, target, this.sessionId, {
485
+ const frame = this.frameScopes.get(this.selectedFrame);
486
+ return new Locator(this.cdp, target, frame?.sessionId ?? this.sessionId, {
487
+ contextId: frame?.contextId,
488
+ localPoint: frame
489
+ ? async (timeout) => {
490
+ const deadline = Date.now() + timeout;
491
+ for (const owner of frame.owners) {
492
+ if (owner.parentSessionId === frame.sessionId &&
493
+ (await this.getFrameOwnerZoom(owner, remainingNavigationTimeout(deadline))) !== 1) {
494
+ return true;
495
+ }
496
+ }
497
+ return false;
498
+ }
499
+ : undefined,
500
+ mapPoint: (point, timeout) => this.mapFramePoint(point, timeout, false, frame),
501
+ mapViewportPoint: (point, timeout) => this.mapFramePoint(point, timeout, true, frame),
367
502
  ...options,
368
503
  nth: options?.nth ?? target.nth,
369
504
  getUrl: () => this.state?.url,
@@ -374,7 +509,7 @@ class SessionManager {
374
509
  */
375
510
  createAutoWait(options) {
376
511
  this.ensureSession();
377
- return new AutoWait(this.cdp, this.sessionId, options);
512
+ return new AutoWait(this.cdp, this.frameScopes.get(this.selectedFrame)?.sessionId ?? this.sessionId, options);
378
513
  }
379
514
  /**
380
515
  * 获取行为模拟器
@@ -441,13 +576,16 @@ class SessionManager {
441
576
  modifiers: this.modifiers,
442
577
  });
443
578
  }
579
+ getModifiers() {
580
+ return this.modifiers;
581
+ }
444
582
  /**
445
583
  * 键盘按下
446
584
  *
447
585
  * options.rawKeyDown=true 配合 options.autoRepeat=true 表示长按重复(与 Puppeteer 一致),
448
586
  * 上层 unified-session 维护 pressedKeys Set 决定是否启用
449
587
  */
450
- async keyDown(key, commands, options) {
588
+ async keyDown(key, commands, options, timeout) {
451
589
  this.ensureSession();
452
590
  const nextModifiers = MODIFIER_KEYS[key] ? this.modifiers | MODIFIER_KEYS[key] : this.modifiers;
453
591
  const keyDefinition = getKeyDefinition(key);
@@ -463,22 +601,36 @@ class SessionManager {
463
601
  if (options?.autoRepeat) {
464
602
  params.autoRepeat = true;
465
603
  }
466
- await this.send('Input.dispatchKeyEvent', params);
604
+ await this.send('Input.dispatchKeyEvent', params, timeout);
467
605
  this.modifiers = nextModifiers;
468
606
  }
469
607
  /**
470
608
  * 键盘释放
471
609
  */
472
- async keyUp(key) {
473
- this.ensureSession();
610
+ async keyUp(key, timeout, inputContext) {
474
611
  const keyDefinition = getKeyDefinition(key);
475
- const nextModifiers = MODIFIER_KEYS[key] ? this.modifiers & ~MODIFIER_KEYS[key] : this.modifiers;
476
- await this.send('Input.dispatchKeyEvent', {
477
- type: 'keyUp',
478
- modifiers: nextModifiers,
479
- ...keyDefinition,
480
- });
481
- this.modifiers = nextModifiers;
612
+ const nextModifiers = inputContext?.modifiers ?? (MODIFIER_KEYS[key] ? this.modifiers & ~MODIFIER_KEYS[key] : this.modifiers);
613
+ const params = { type: 'keyUp', modifiers: nextModifiers, ...keyDefinition };
614
+ if (inputContext) {
615
+ this.ensureConnected();
616
+ const frame = inputContext.frameId ? this.frameScopes.get(inputContext.frameId) : undefined;
617
+ const sessionId = inputContext.frameId
618
+ ? frame?.targetId === inputContext.targetId
619
+ ? frame.sessionId
620
+ : undefined
621
+ : this.targetSessions.get(inputContext.targetId);
622
+ if (!sessionId) {
623
+ throw new DriverCapabilityError('Original input session is no longer available for key release');
624
+ }
625
+ this.revisions.set(inputContext.targetId, (this.revisions.get(inputContext.targetId) ?? 0) + 1);
626
+ await this.cdp.send('Input.dispatchKeyEvent', params, sessionId, timeout);
627
+ }
628
+ else {
629
+ await this.send('Input.dispatchKeyEvent', params, timeout);
630
+ }
631
+ if (!inputContext || inputContext.targetId === this.currentTargetId) {
632
+ this.modifiers = nextModifiers;
633
+ }
482
634
  }
483
635
  /**
484
636
  * 输入文本
@@ -568,40 +720,25 @@ class SessionManager {
568
720
  if (fullPage) {
569
721
  // 获取页面完整高度
570
722
  const sizeExpr = 'JSON.stringify({ width: document.documentElement.scrollWidth, ' +
571
- 'height: document.documentElement.scrollHeight })';
723
+ 'height: document.documentElement.scrollHeight, devicePixelRatio: window.devicePixelRatio })';
572
724
  const { result } = (await this.send('Runtime.evaluate', {
573
725
  expression: sizeExpr,
574
726
  returnByValue: true,
575
727
  }));
576
- let width, height;
728
+ let width, height, devicePixelRatio;
577
729
  try {
578
730
  ;
579
- ({ width, height } = JSON.parse(result.value));
731
+ ({ width, height, devicePixelRatio } = JSON.parse(result.value));
580
732
  }
581
733
  catch {
582
734
  throw new Error(`screenshot: 无法解析页面尺寸: ${result.value}`);
583
735
  }
584
- assertScreenshotBudget(width, height, scale ?? 1);
585
- // 设置视口
586
- await this.send('Emulation.setDeviceMetricsOverride', {
587
- width,
588
- height,
589
- deviceScaleFactor: scale ?? 1,
590
- mobile: false,
591
- });
592
- try {
593
- const { data } = (await this.send('Page.captureScreenshot', captureParams));
594
- assertScreenshotBase64Budget(data);
595
- return { data, format: effectiveFormat };
596
- }
597
- finally {
598
- try {
599
- await this.send('Emulation.clearDeviceMetricsOverride');
600
- }
601
- catch {
602
- // cleanup failure, ignore to preserve original error
603
- }
604
- }
736
+ assertScreenshotBudget(width, height, (scale ?? 1) * devicePixelRatio);
737
+ captureParams.clip = { x: 0, y: 0, width, height, scale: scale ?? 1 };
738
+ captureParams.captureBeyondViewport = true;
739
+ const { data } = (await this.send('Page.captureScreenshot', captureParams));
740
+ assertScreenshotBase64Budget(data);
741
+ return { data, format: effectiveFormat };
605
742
  }
606
743
  if (clip) {
607
744
  assertScreenshotBudget(clip.width, clip.height, scale ?? 1);
@@ -638,7 +775,7 @@ class SessionManager {
638
775
  const state = JSON.parse(result.value);
639
776
  // 获取可交互元素
640
777
  await this.send('Accessibility.enable');
641
- const { nodes } = (await this.send('Accessibility.getFullAXTree'));
778
+ const { nodes } = (await this.send('Accessibility.getFullAXTree', this.selectedFrame ? { frameId: this.frameScopes.get(this.selectedFrame)?.frameId } : undefined));
642
779
  const interactiveRoles = [
643
780
  'button',
644
781
  'link',
@@ -672,8 +809,9 @@ class SessionManager {
672
809
  async getPageHtml(selector, outer = true) {
673
810
  this.ensureSession();
674
811
  if (selector) {
812
+ await this.evaluate(`(${installDomHelpers.toString()})();`);
675
813
  const prop = outer ? 'outerHTML' : 'innerHTML';
676
- return this.evaluate(`((s, p) => { const el = document.querySelector(s); return el ? el[p] : '' })`, [selector, prop]);
814
+ return this.evaluate(`((s, p) => { const el = globalThis.__mcpDomHelpers.query({selector:s})[0]; return el ? el[p] : '' })`, [selector, prop]);
677
815
  }
678
816
  return this.evaluate('document.documentElement.outerHTML');
679
817
  }
@@ -683,8 +821,9 @@ class SessionManager {
683
821
  async getPageText(selector) {
684
822
  this.ensureSession();
685
823
  if (selector) {
824
+ await this.evaluate(`(${installDomHelpers.toString()})();`);
686
825
  return this.evaluate(`(s => {
687
- const element = document.querySelector(s);
826
+ const element = globalThis.__mcpDomHelpers.query({selector:s})[0];
688
827
  return element instanceof HTMLElement ? element.innerText : (element?.textContent ?? '');
689
828
  })`, [selector]);
690
829
  }
@@ -694,11 +833,17 @@ class SessionManager {
694
833
  /** Extension readPage 等价物:CDP 通过页面 DOM 构造 pageContent 和 interactiveElements */
695
834
  async readPage(options) {
696
835
  const state = await this.getPageState();
697
- const interactiveElements = await this.collectInteractiveElements(options?.depth);
836
+ const interactiveElements = await this.collectInteractiveElements(options?.depth, options?.target, options?.timeout);
698
837
  const lines = interactiveElements.map((e) => {
699
838
  let line = e.role;
700
839
  if (e.name) {
701
- line += ` "${e.name}"`;
840
+ line += ` ${JSON.stringify(e.name)}`;
841
+ }
842
+ if (e.type) {
843
+ line += ` type=${JSON.stringify(e.type)}`;
844
+ }
845
+ if (e.value !== undefined) {
846
+ line += ` value=${JSON.stringify(e.value)}`;
702
847
  }
703
848
  return line;
704
849
  });
@@ -708,9 +853,11 @@ class SessionManager {
708
853
  interactiveElements,
709
854
  };
710
855
  }
711
- async collectInteractiveElements(depth) {
856
+ async collectInteractiveElements(depth, target, timeout) {
712
857
  const maxDepth = Number.isInteger(depth) && depth !== undefined && depth >= 0 ? depth : 15;
713
- return this.evaluate(`(() => {
858
+ await this.evaluate(`(${installDomHelpers.toString()})();`, undefined, timeout);
859
+ const script = `function() {
860
+ var root = this;
714
861
  var maxDepth = ${maxDepth};
715
862
  function selectorFor(el) {
716
863
  if (!(el instanceof Element)) return '';
@@ -740,56 +887,39 @@ class SessionManager {
740
887
  function depthFor(el) {
741
888
  var depth = 0;
742
889
  var current = el;
743
- while (current.parentElement) {
890
+ while (current !== root && (current.parentElement || current.getRootNode().host)) {
744
891
  depth += 1;
745
- current = current.parentElement;
892
+ current = current.parentElement || current.getRootNode().host;
746
893
  }
747
894
  return depth;
748
895
  }
749
- function roleFor(el) {
750
- var explicit = el.getAttribute('role');
751
- if (explicit) return explicit;
752
- var tag = el.tagName.toLowerCase();
753
- var type = (el.getAttribute('type') || '').toLowerCase();
754
- if (tag === 'button' || type === 'button' || type === 'submit' || type === 'reset') return 'button';
755
- if (tag === 'a' && el.hasAttribute('href')) return 'link';
756
- if (tag === 'textarea' || (tag === 'input' && !['checkbox', 'radio', 'range'].includes(type))) {
757
- return 'textbox';
758
- }
759
- if (type === 'checkbox') return 'checkbox';
760
- if (type === 'radio') return 'radio';
761
- if (tag === 'select') return 'combobox';
762
- if (type === 'range') return 'slider';
763
- if (el.isContentEditable) return 'textbox';
764
- return tag;
765
- }
766
- function nameFor(el) {
767
- return (
768
- el.getAttribute('aria-label') ||
769
- el.getAttribute('title') ||
770
- el.getAttribute('placeholder') ||
771
- el.textContent ||
772
- ''
773
- ).replace(/\\s+/g, ' ').trim().slice(0, 160);
774
- }
775
896
  var selector = [
776
897
  'button,a[href],input,textarea,select,[role]',
777
898
  '[contenteditable="true"],[tabindex]:not([tabindex="-1"])'
778
899
  ].join(',');
779
- return Array.from(document.querySelectorAll(selector)).filter(function(el) {
900
+ var elements = globalThis.__mcpDomHelpers.query({selector:selector}, root);
901
+ if (root.nodeType === 1 && root.matches(selector)) elements.unshift(root);
902
+ return elements.filter(function(el) {
780
903
  return depthFor(el) <= maxDepth;
781
904
  }).slice(0, 100).map(function(el, index) {
782
905
  var rect = el.getBoundingClientRect();
783
906
  var cx = rect.left + rect.width / 2;
784
907
  var cy = rect.top + rect.height / 2;
785
- var top = rect.width > 0 && rect.height > 0 ? document.elementFromPoint(cx, cy) : null;
908
+ var top = rect.width > 0 && rect.height > 0
909
+ ? globalThis.__mcpDomHelpers.deepElementFromPoint(cx, cy) : null;
786
910
  var style = getComputedStyle(el);
787
911
  var visible = rect.width > 0 && rect.height > 0 &&
788
912
  style.visibility !== 'hidden' && style.display !== 'none';
913
+ var name = globalThis.__mcpDomHelpers.accessibleName(el, true);
914
+ var type = el.tagName.toLowerCase() === 'input' ? el.type : undefined;
915
+ var value = type !== undefined && !['hidden','password','file'].includes(type) &&
916
+ (!name || !['button','submit','reset'].includes(type)) ? el.value : undefined;
789
917
  return {
790
918
  refId: 'cdp-' + index,
791
- role: roleFor(el),
792
- name: nameFor(el),
919
+ role: globalThis.__mcpDomHelpers.role(el),
920
+ name: name,
921
+ ...(type !== undefined ? {type: type} : {}),
922
+ ...(value !== undefined ? {value: value} : {}),
793
923
  selector: selectorFor(el),
794
924
  visible: visible,
795
925
  disabled: Boolean(el.disabled) || el.getAttribute('aria-disabled') === 'true',
@@ -798,7 +928,20 @@ class SessionManager {
798
928
  frameId: 0
799
929
  };
800
930
  });
801
- })()`);
931
+ }`;
932
+ if (target && 'x' in target && 'y' in target) {
933
+ const elements = await this.evaluate(`(() => {
934
+ const root = globalThis.__mcpDomHelpers.deepElementFromPoint(${JSON.stringify(target.x)}, ${JSON.stringify(target.y)});
935
+ return root ? (${script}).call(root) : null;
936
+ })()`, undefined, timeout);
937
+ if (!elements) {
938
+ throw new ElementNotFoundError(target, timeout ?? DEFAULT_TIMEOUT);
939
+ }
940
+ return elements;
941
+ }
942
+ return target
943
+ ? this.createLocator(target, timeout !== undefined ? { timeout } : undefined).evaluateOn(script)
944
+ : this.evaluate(`(${script}).call(document)`, undefined, timeout);
802
945
  }
803
946
  async getFrames() {
804
947
  this.ensureSession();
@@ -826,16 +969,18 @@ class SessionManager {
826
969
  }
827
970
  /** CDP 通过 evaluate 注入函数枚举 IMG */
828
971
  async getHtmlWithImages(selector, outer = true) {
972
+ await this.evaluate(`(${installDomHelpers.toString()})();`);
829
973
  const selectorArg = JSON.stringify(selector ?? null);
830
974
  return this.evaluate(`(function() {
831
- var root = ${selectorArg} ? document.querySelector(${selectorArg}) : document.documentElement;
975
+ var root = ${selectorArg}
976
+ ? globalThis.__mcpDomHelpers.query({selector:${selectorArg}})[0] : document.documentElement;
832
977
  if (!root) return {html: '', images: []};
833
978
  var html = ${selectorArg}
834
979
  ? (${outer} ? root.outerHTML : root.innerHTML)
835
980
  : document.documentElement.outerHTML;
836
981
  var imgList = [];
837
982
  if (root.tagName === 'IMG') imgList.push(root);
838
- root.querySelectorAll('img').forEach(function(img) { imgList.push(img); });
983
+ globalThis.__mcpDomHelpers.query({selector:'img'},root).forEach(function(img) { imgList.push(img); });
839
984
  var images = [];
840
985
  for (var i = 0; i < imgList.length; i++) {
841
986
  var img = imgList[i];
@@ -897,54 +1042,24 @@ class SessionManager {
897
1042
  }
898
1043
  // ==================== IBrowserDriver: 元素查找 ====================
899
1044
  /** CDP 通过 evaluate 注入 TreeWalker 查找元素 */
900
- async find(selector, text, xpath, timeout) {
901
- return this.evaluate(`function(selector, text, xpath) {
902
- var elements;
903
- if (xpath) {
904
- elements = [];
905
- var xr = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
906
- for (var i = 0; i < xr.snapshotLength; i++) {
907
- var node = xr.snapshotItem(i);
908
- if (node instanceof Element) elements.push(node);
909
- }
910
- } else if (selector) {
911
- elements = Array.from(document.querySelectorAll(selector));
912
- } else if (text) {
913
- // text-only:用 TreeWalker 仅遍历可能含目标文本的节点,避免 querySelectorAll('*') 的全树扫描和强制 layout
914
- elements = [];
915
- var lowerText = text;
916
- var walker = document.createTreeWalker(
917
- document.body || document.documentElement,
918
- NodeFilter.SHOW_ELEMENT,
919
- {
920
- acceptNode: function (n) {
921
- var t = n.textContent || '';
922
- if (!t.includes(lowerText)) return NodeFilter.FILTER_SKIP;
923
- return NodeFilter.FILTER_ACCEPT;
924
- }
925
- });
926
- while (walker.nextNode()) {
927
- elements.push(walker.currentNode);
928
- if (elements.length >= 200) break;
929
- }
930
- } else {
931
- elements = Array.from(document.querySelectorAll('*'));
932
- }
933
- var results = [];
934
- for (var j = 0; j < elements.length; j++) {
935
- var el = elements[j];
936
- if (text && !(el.textContent || '').includes(text)) continue;
937
- var rect = el.getBoundingClientRect();
938
- results.push({
939
- refId: '',
940
- tag: el.tagName.toLowerCase(),
941
- text: (el.textContent || '').trim().substring(0, 100),
942
- rect: {x: rect.x, y: rect.y, width: rect.width, height: rect.height}
943
- });
944
- if (results.length >= 50) break;
945
- }
946
- return results;
947
- }`, [selector ?? null, text ?? null, xpath ?? null], timeout);
1045
+ async find(selector, text, xpath, timeout, semanticOrMatchIndex, matchIndex) {
1046
+ const semantic = typeof semanticOrMatchIndex === 'object' ? semanticOrMatchIndex : undefined;
1047
+ const nth = typeof semanticOrMatchIndex === 'number' ? semanticOrMatchIndex : matchIndex;
1048
+ await this.evaluate(`(${installDomHelpers.toString()})();`, undefined, timeout);
1049
+ return this.evaluate(`function(selector, text, xpath, semantic, nth) {
1050
+ const elements = globalThis.__mcpDomHelpers.query({
1051
+ selector: selector ?? undefined, text: text ?? undefined,
1052
+ xpath: xpath ?? undefined, semantic: semantic ?? undefined
1053
+ });
1054
+ return (nth == null ? elements.slice(0,50) : elements.slice(nth,nth+1)).map(el => {
1055
+ const r = el.getBoundingClientRect();
1056
+ return {
1057
+ refId: '', tag: el.tagName.toLowerCase(),
1058
+ text: (el.textContent || '').trim().slice(0,100),
1059
+ rect: {x:r.x,y:r.y,width:r.width,height:r.height}
1060
+ };
1061
+ });
1062
+ }`, [selector ?? null, text ?? null, xpath ?? null, semantic ?? null, nth ?? null], timeout);
948
1063
  }
949
1064
  // ==================== IBrowserDriver: 元素操作(refId 类,CDP 不支持) ====================
950
1065
  click(_refId) {
@@ -979,11 +1094,15 @@ class SessionManager {
979
1094
  if (!selector) {
980
1095
  throw new DriverCapabilityError('getAttribute 需要 selector');
981
1096
  }
982
- return this.evaluate(`(s, a) => { const el = document.querySelector(s); return el ? el.getAttribute(a) : null }`, [selector, attribute]);
1097
+ await this.evaluate(`(${installDomHelpers.toString()})();`);
1098
+ return this.evaluate(`(s, a) => {
1099
+ const el = globalThis.__mcpDomHelpers.query({selector:s})[0];
1100
+ return el ? el.getAttribute(a) : null;
1101
+ }`, [selector, attribute]);
983
1102
  }
984
1103
  // ==================== IBrowserDriver: 输入(precise) ====================
985
1104
  /** CDP 通用 inputKey 接口实现:直接转发 Input.dispatchKeyEvent,不维护 modifiers(由调用方提供) */
986
- async inputKey(type, options = {}) {
1105
+ async inputKey(type, options = {}, timeout) {
987
1106
  this.ensureSession();
988
1107
  const params = { type };
989
1108
  if (options.key !== undefined) {
@@ -1016,7 +1135,7 @@ class SessionManager {
1016
1135
  if (options.commands && options.commands.length > 0) {
1017
1136
  params.commands = options.commands;
1018
1137
  }
1019
- await this.send('Input.dispatchKeyEvent', params);
1138
+ await this.send('Input.dispatchKeyEvent', params, timeout);
1020
1139
  }
1021
1140
  /** CDP 通用 inputMouse 接口实现:直接转发 Input.dispatchMouseEvent */
1022
1141
  async inputMouse(type, x, y, options = {}, timeout) {
@@ -1123,6 +1242,25 @@ class SessionManager {
1123
1242
  await this.attachToTarget(targetId);
1124
1243
  await this.activateTarget(targetId);
1125
1244
  }
1245
+ async activatePageWithAffected(targetId) {
1246
+ return this.withLock(async () => {
1247
+ const before = (await this.listTargets()).find((target) => target.targetId === targetId);
1248
+ if (!before) {
1249
+ throw new TargetNotFoundError(targetId);
1250
+ }
1251
+ if (this.pendingPageCondition) {
1252
+ const condition = this.pendingPageCondition;
1253
+ await this.assertPageCondition(targetId, condition.expectedUrl, condition.expectedRevision);
1254
+ this.pendingPageCondition = null;
1255
+ }
1256
+ await this.activateTarget(targetId);
1257
+ const after = (await this.listTargets()).find((target) => target.targetId === targetId);
1258
+ if (!after) {
1259
+ throw new TargetNotFoundError(targetId);
1260
+ }
1261
+ return { targetId, before, after };
1262
+ });
1263
+ }
1126
1264
  /** IBrowserDriver 接口:选择操作目标(attach 即可) */
1127
1265
  async selectPage(targetId, timeout) {
1128
1266
  const deadline = timeout === undefined ? undefined : Date.now() + timeout;
@@ -1133,10 +1271,10 @@ class SessionManager {
1133
1271
  return this.currentTargetId;
1134
1272
  }
1135
1273
  async deselectPage(timeout) {
1136
- const deadline = timeout === undefined ? undefined : Date.now() + timeout;
1274
+ const sid = this.sessionId;
1137
1275
  try {
1138
- if (this.sessionId && this.cdp?.isConnected) {
1139
- await this.cdp.send('Target.detachFromTarget', { sessionId: this.sessionId }, undefined, deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
1276
+ if (sid && this.cdp?.isConnected && !this.eventControllers.has(sid)) {
1277
+ await this.cdp.send('Target.detachFromTarget', { sessionId: sid }, undefined, timeout);
1140
1278
  }
1141
1279
  }
1142
1280
  finally {
@@ -1184,21 +1322,288 @@ class SessionManager {
1184
1322
  throw new DriverCapabilityError('CDP 模式不支持同步切换 target,请用 selectPage(targetId) 或 attachToTarget(targetId)');
1185
1323
  }
1186
1324
  }
1187
- // ==================== IBrowserDriver: iframe(CDP 不支持) ====================
1188
- resolveFrame(_frame) {
1189
- return Promise.reject(new DriverCapabilityError('iframe 穿透需要 Extension 模式'));
1325
+ // ==================== IBrowserDriver: 原生 frame scope ====================
1326
+ async resolveFrame(frame, timeout) {
1327
+ this.ensureSession();
1328
+ const deadline = Date.now() + (timeout ?? DEFAULT_TIMEOUT);
1329
+ const rootSid = this.sessionId;
1330
+ await this.cdp.send('Target.setAutoAttach', {
1331
+ autoAttach: true,
1332
+ waitForDebuggerOnStart: false,
1333
+ flatten: true,
1334
+ filter: [{ type: 'iframe', exclude: false }],
1335
+ }, rootSid, remainingNavigationTimeout(deadline));
1336
+ await this.cdp.send('Runtime.enable', {}, rootSid, remainingNavigationTimeout(deadline));
1337
+ const tree = await this.cdp.send('Page.getFrameTree', {}, rootSid, remainingNavigationTimeout(deadline));
1338
+ let nativeFrame = tree.frameTree.frame.id;
1339
+ let sid = rootSid;
1340
+ const owners = [];
1341
+ const path = Array.isArray(frame) ? frame : [frame];
1342
+ if (!path.length) {
1343
+ throw new DriverCapabilityError('Frame path must contain at least one selection');
1344
+ }
1345
+ for (const selection of path) {
1346
+ const context = (this.contexts.get(sid) ?? []).find((c) => c.frameId === nativeFrame && c.isDefault);
1347
+ if (!context) {
1348
+ throw new DriverCapabilityError(`Default execution context unavailable for frame ${nativeFrame}`);
1349
+ }
1350
+ const query = typeof selection === 'number'
1351
+ ? `globalThis.__mcpDomHelpers.query({selector:'iframe,frame'})[${selection}]`
1352
+ : `globalThis.__mcpDomHelpers.query({selector:${JSON.stringify(selection)}})[0]`;
1353
+ const expression = `(${installDomHelpers.toString()})();${query}`;
1354
+ const resolutionContext = {
1355
+ tabId: this.currentTargetId,
1356
+ phase: 'frame_resolution',
1357
+ selection,
1358
+ path,
1359
+ actionExecuted: false,
1360
+ actionStatus: 'not_started',
1361
+ retryable: false,
1362
+ };
1363
+ const result = await this.cdp.send('Runtime.evaluate', { expression, contextId: context.id, returnByValue: false }, sid, remainingNavigationTimeout(deadline));
1364
+ if (result.exceptionDetails || !result.result.objectId) {
1365
+ const exception = result.exceptionDetails?.exception;
1366
+ const invalidSelector = exception?.className === 'SyntaxError' ||
1367
+ (exception?.className === 'DOMException' && /^SyntaxError:/.test(exception.description ?? ''));
1368
+ if (result.exceptionDetails && !invalidSelector) {
1369
+ throw new DriverCapabilityError('Frame selection failed: ' + result.exceptionDetails.text);
1370
+ }
1371
+ throw new StructuredToolError(invalidSelector ? 'INVALID_FRAME_SELECTOR' : 'FRAME_NOT_FOUND', 'Frame selection did not resolve to a current frame element', '请检查当前页面的 iframe selector 或 DOM 索引', { ...resolutionContext, selectionStatus: invalidSelector ? 'invalid-selector' : 'not-found' });
1372
+ }
1373
+ const objectSessionId = sid;
1374
+ try {
1375
+ const descriptor = await this.cdp.send('DOM.describeNode', { objectId: result.result.objectId }, sid, remainingNavigationTimeout(deadline));
1376
+ if (!['IFRAME', 'FRAME'].includes(descriptor.node.nodeName) || !descriptor.node.frameId) {
1377
+ const notFrame = !['IFRAME', 'FRAME'].includes(descriptor.node.nodeName);
1378
+ throw new StructuredToolError(notFrame ? 'FRAME_NOT_IFRAME' : 'FRAME_IDENTITY_UNAVAILABLE', 'Selected element does not identify a native child frame', '请检查所选元素及当前 iframe 文档', { ...resolutionContext, selectionStatus: notFrame ? 'not-frame' : 'found' });
1379
+ }
1380
+ nativeFrame = descriptor.node.frameId;
1381
+ sid = this.frameSessions.get(nativeFrame) ?? sid;
1382
+ await this.cdp.send('Runtime.enable', {}, sid, remainingNavigationTimeout(deadline));
1383
+ if (!(this.contexts.get(sid) ?? []).some((c) => c.frameId === nativeFrame && c.isDefault)) {
1384
+ const oopif = await this.cdp.waitForEvent('Runtime.executionContextCreated', (p) => p.context.auxData?.frameId === nativeFrame && p.context.auxData.isDefault === true, remainingNavigationTimeout(deadline), undefined, this.requestContext?.()?.signal);
1385
+ void oopif;
1386
+ sid = this.frameSessions.get(nativeFrame) ?? sid;
1387
+ }
1388
+ const childContext = (this.contexts.get(sid) ?? []).find((c) => c.frameId === nativeFrame && c.isDefault);
1389
+ if (!childContext) {
1390
+ throw new DriverCapabilityError('Frame execution context changed during selection');
1391
+ }
1392
+ owners.push({
1393
+ parentSessionId: objectSessionId,
1394
+ backendNodeId: descriptor.node.backendNodeId,
1395
+ frameId: nativeFrame,
1396
+ sessionId: sid,
1397
+ contextId: childContext.id,
1398
+ });
1399
+ }
1400
+ finally {
1401
+ void this.cdp.send('Runtime.releaseObject', { objectId: result.result.objectId }, objectSessionId).catch(() => { });
1402
+ }
1403
+ }
1404
+ const context = (this.contexts.get(sid) ?? []).find((c) => c.frameId === nativeFrame && c.isDefault);
1405
+ if (!context) {
1406
+ throw new DriverCapabilityError('Frame execution context changed during selection');
1407
+ }
1408
+ const handle = ++this.nextFrameHandle;
1409
+ if (this.frameScopes.size > 64) {
1410
+ this.frameScopes.delete(this.frameScopes.keys().next().value);
1411
+ }
1412
+ this.frameScopes.set(handle, {
1413
+ targetId: this.currentTargetId,
1414
+ frameId: nativeFrame,
1415
+ contextId: context.id,
1416
+ sessionId: sid,
1417
+ owners,
1418
+ });
1419
+ return {
1420
+ frameId: handle,
1421
+ offset: null,
1422
+ frameContext: {
1423
+ backend: 'cdp',
1424
+ frameId: nativeFrame,
1425
+ contextId: context.id,
1426
+ sessionId: sid,
1427
+ selection: frame,
1428
+ },
1429
+ };
1430
+ }
1431
+ async mapFramePoint(point, timeout = DEFAULT_TIMEOUT, viewportPoint = false, frame = this.frameScopes.get(this.selectedFrame)) {
1432
+ if (!frame) {
1433
+ return point;
1434
+ }
1435
+ const deadline = Date.now() + timeout;
1436
+ const remaining = () => remainingNavigationTimeout(deadline);
1437
+ let currentSession = frame.sessionId;
1438
+ let local = !viewportPoint;
1439
+ let mapped = point;
1440
+ try {
1441
+ for (const owner of [...frame.owners].reverse()) {
1442
+ // Same-session quads already include every ancestor in that viewport.
1443
+ const sameViewport = !local && owner.parentSessionId === currentSession;
1444
+ if (sameViewport && (await this.getFrameOwnerZoom(owner, remaining())) === 1) {
1445
+ continue;
1446
+ }
1447
+ if (sameViewport) {
1448
+ // Descendant quads omit an ancestor iframe's CSS zoom. Undo their query viewport first.
1449
+ const anchor = await this.cdp.send('Runtime.evaluate', {
1450
+ contextId: owner.contextId,
1451
+ returnByValue: false,
1452
+ expression: `(() => {
1453
+ const walk=document.createTreeWalker(document,NodeFilter.SHOW_ELEMENT);
1454
+ for(let el=walk.nextNode();el;el=walk.nextNode()) {
1455
+ const r=el.getBoundingClientRect();
1456
+ if (!(r.width>0 && r.height>0) || el.getClientRects().length!==1) continue;
1457
+ let aligned=true;
1458
+ for(let p=el;p;p=p.parentElement) {
1459
+ const s=getComputedStyle(p),m=new DOMMatrix(s.transform==='none'?undefined:s.transform);
1460
+ if(!m.is2D || Math.abs(m.b)>1e-12 || Math.abs(m.c)>1e-12 || m.a<=0 || m.d<=0 ||
1461
+ (s.rotate&&s.rotate!=='none'&&!/^(?:[xyz] )?0deg$/.test(s.rotate)) ||
1462
+ (s.scale&&s.scale!=='none'&&s.scale.split(/\\s+/).some(value=>Number(value)<=0))) {aligned=false;break}
1463
+ }
1464
+ if(aligned)return el;
1465
+ }
1466
+ return null;
1467
+ })()`,
1468
+ }, owner.sessionId, remaining());
1469
+ const objectId = anchor.result.objectId;
1470
+ if (!objectId) {
1471
+ throw new Error('Frame zoom viewport anchor is unavailable');
1472
+ }
1473
+ try {
1474
+ const { result: { value: r }, } = await this.cdp.send('Runtime.callFunctionOn', {
1475
+ objectId,
1476
+ functionDeclaration: 'function(){const r=this.getBoundingClientRect();return {x:r.x,y:r.y,width:r.width,height:r.height}}',
1477
+ returnByValue: true,
1478
+ }, owner.sessionId, remaining());
1479
+ const { model: { border: q }, } = await this.cdp.send('DOM.getBoxModel', { objectId }, owner.sessionId, remaining());
1480
+ if (!(r.width > 0 && r.height > 0) || q.length !== 8 || !q.every(Number.isFinite)) {
1481
+ throw new Error('Frame zoom viewport anchor is invalid');
1482
+ }
1483
+ const [a, b, c, d] = [
1484
+ (q[2] - q[0]) / r.width,
1485
+ (q[3] - q[1]) / r.width,
1486
+ (q[6] - q[0]) / r.height,
1487
+ (q[7] - q[1]) / r.height,
1488
+ ];
1489
+ const determinant = a * d - b * c;
1490
+ if (Math.abs(determinant) < 1e-12 ||
1491
+ Math.abs(q[4] - q[2] - q[6] + q[0]) > 0.001 ||
1492
+ Math.abs(q[5] - q[3] - q[7] + q[1]) > 0.001) {
1493
+ throw new Error('Frame zoom viewport anchor is singular or non-affine');
1494
+ }
1495
+ const dx = mapped.x - q[0], dy = mapped.y - q[1];
1496
+ mapped = { x: (d * dx - c * dy) / determinant + r.x, y: (a * dy - b * dx) / determinant + r.y };
1497
+ }
1498
+ finally {
1499
+ await this.cdp.send('Runtime.releaseObject', { objectId }, owner.sessionId, 1000).catch((error) => console.warn('[MCP] Frame zoom anchor cleanup failed:', error));
1500
+ }
1501
+ }
1502
+ if (!(this.contexts.get(owner.sessionId) ?? []).some((c) => c.id === owner.contextId && c.frameId === owner.frameId)) {
1503
+ throw new Error('Frame document identity changed before input');
1504
+ }
1505
+ const { node } = await this.cdp.send('DOM.describeNode', { backendNodeId: owner.backendNodeId }, owner.parentSessionId, remaining());
1506
+ if (node.frameId !== owner.frameId) {
1507
+ throw new Error('Frame owner identity changed before input');
1508
+ }
1509
+ const { model } = await this.cdp.send('DOM.getBoxModel', { backendNodeId: owner.backendNodeId }, owner.parentSessionId, remaining());
1510
+ const viewport = await this.cdp.send('Runtime.evaluate', {
1511
+ expression: '({width:innerWidth,height:innerHeight})',
1512
+ contextId: owner.contextId,
1513
+ returnByValue: true,
1514
+ }, owner.sessionId, remaining());
1515
+ const { width, height } = viewport.result.value ?? {};
1516
+ const q = model.content;
1517
+ if (viewport.exceptionDetails ||
1518
+ !(width > 0 && height > 0) ||
1519
+ q.length !== 8 ||
1520
+ !q.every(Number.isFinite)) {
1521
+ throw new Error('Frame content quad or viewport is unavailable');
1522
+ }
1523
+ const [a, b, c, d, e, f] = [
1524
+ (q[2] - q[0]) / width,
1525
+ (q[3] - q[1]) / width,
1526
+ (q[6] - q[0]) / height,
1527
+ (q[7] - q[1]) / height,
1528
+ q[0],
1529
+ q[1],
1530
+ ];
1531
+ if (Math.abs(a * d - b * c) < 1e-12 ||
1532
+ Math.abs(q[4] - q[2] - q[6] + q[0]) > 0.001 ||
1533
+ Math.abs(q[5] - q[3] - q[7] + q[1]) > 0.001) {
1534
+ throw new Error('Frame content quad is singular or non-affine');
1535
+ }
1536
+ mapped = { x: a * mapped.x + c * mapped.y + e, y: b * mapped.x + d * mapped.y + f };
1537
+ currentSession = owner.parentSessionId;
1538
+ local = false;
1539
+ }
1540
+ return mapped;
1541
+ }
1542
+ catch (error) {
1543
+ throw new StructuredToolError('FRAME_GEOMETRY_UNAVAILABLE', error instanceof Error ? error.message : String(error), '重新读取 frame 的文档和布局后再执行输入', { actionExecuted: false, actionStatus: 'not_started', retryable: false });
1544
+ }
1190
1545
  }
1191
1546
  getCurrentFrameId() {
1192
- // CDP 模式没有 frameId 概念,统一返回 0(主框架)
1193
- return 0;
1547
+ return this.selectedFrame;
1194
1548
  }
1195
1549
  setCurrentFrameId(frameId) {
1196
- if (frameId !== 0) {
1197
- throw new DriverCapabilityError('iframe 穿透需要 Extension 模式');
1550
+ if (frameId && this.frameScopes.get(frameId)?.targetId !== this.currentTargetId) {
1551
+ throw new DriverCapabilityError('CDP frame scope is no longer available');
1552
+ }
1553
+ this.selectedFrame = frameId;
1554
+ }
1555
+ async evaluateInFrame(frameId, expression, timeout, _staleContextRetry) {
1556
+ const frame = this.frameScopes.get(frameId);
1557
+ if (!frame) {
1558
+ throw new DriverCapabilityError('CDP frame scope is no longer available');
1198
1559
  }
1560
+ return this.cdp.send('Runtime.evaluate', { expression, contextId: frame.contextId, returnByValue: true, awaitPromise: true, timeout }, frame.sessionId, timeout);
1199
1561
  }
1200
- evaluateInFrame(_frameId, _expression, _timeout, _staleContextRetry) {
1201
- return Promise.reject(new DriverCapabilityError('iframe 穿透需要 Extension 模式'));
1562
+ async browserEvents(action, command, targetId, timeout) {
1563
+ this.ensureConnected();
1564
+ browserEventCommandSchema.parse({ action, command });
1565
+ const target = command.ref ? eventRefTarget(command.ref) : undefined;
1566
+ if (target && (target.backend !== 'cdp' || (targetId && target.targetId !== targetId))) {
1567
+ throw new DriverCapabilityError('Browser event ref target mismatch');
1568
+ }
1569
+ const id = target?.targetId ?? targetId ?? this.currentTargetId;
1570
+ const sid = id && this.targetSessions.get(id);
1571
+ if (!id || !sid) {
1572
+ throw new DriverCapabilityError('No observed CDP session for this target');
1573
+ }
1574
+ const controller = this.ensureEventController(id, sid);
1575
+ const scope = this.requestContext?.();
1576
+ scope?.signal?.throwIfAborted();
1577
+ if (scope?.deadline !== undefined && Date.now() >= scope.deadline) {
1578
+ throw new TimeoutError('Browser event deadline exceeded');
1579
+ }
1580
+ const abort = () => {
1581
+ void controller.abortPending('request cancelled');
1582
+ };
1583
+ scope?.signal?.addEventListener('abort', abort, { once: true });
1584
+ try {
1585
+ return await controller.command(action, {
1586
+ ...command,
1587
+ ...(action === 'download' && command.op === 'wait' && timeout
1588
+ ? { timeout: Math.min(Number(command.timeout ?? timeout), timeout) }
1589
+ : {}),
1590
+ }, scope?.signal);
1591
+ }
1592
+ finally {
1593
+ scope?.signal?.removeEventListener('abort', abort);
1594
+ }
1595
+ }
1596
+ async browserFetchCommand(method, params, targetId) {
1597
+ const id = targetId ?? this.currentTargetId;
1598
+ const sid = id && this.targetSessions.get(id);
1599
+ if (!id || !sid) {
1600
+ throw new DriverCapabilityError('No observed CDP session for this target');
1601
+ }
1602
+ return this.ensureEventController(id, sid).rawFetch(method, params);
1603
+ }
1604
+ async suspendBrowserEventsForChallenge() {
1605
+ this.ensureSession();
1606
+ return this.ensureEventController(this.currentTargetId, this.sessionId).suspend('Cloudflare challenge');
1202
1607
  }
1203
1608
  // ==================== IBrowserDriver: CDP 直通 ====================
1204
1609
  /**
@@ -1207,6 +1612,10 @@ class SessionManager {
1207
1612
  * browser-level 域(Target/Browser/SystemInfo/DeviceAccess/IO)走 sendBrowserCommand
1208
1613
  */
1209
1614
  async debuggerSend(method, params, _tabId, timeout) {
1615
+ if (method.startsWith('Fetch.')) {
1616
+ this.ensureSession();
1617
+ return this.ensureEventController(this.currentTargetId, this.sessionId).rawFetch(method, params);
1618
+ }
1210
1619
  const domain = method.split('.')[0];
1211
1620
  const browserLevelDomains = ['Target', 'Browser', 'SystemInfo', 'DeviceAccess', 'IO'];
1212
1621
  if (browserLevelDomains.includes(domain)) {
@@ -1236,13 +1645,38 @@ class SessionManager {
1236
1645
  * 获取 Cookies
1237
1646
  */
1238
1647
  async getCookies(filter) {
1648
+ if (![filter?.name, filter?.domain, filter?.url].some((value) => value !== undefined && value.trim().length > 0)) {
1649
+ throw new StructuredToolError('INVALID_ARGUMENT', 'cookies action=get 必须带非空 name、domain 或 url 过滤参数', '指定读取范围后再获取 Cookie', { actionExecuted: false, actionStatus: 'not_started', retryable: false });
1650
+ }
1239
1651
  this.ensureSession();
1240
1652
  const urls = filter?.url ? [filter.url] : undefined;
1241
- const { cookies } = (await this.send('Network.getCookies', urls ? { urls } : {}));
1653
+ const contextId = await this.cookieContext(filter);
1654
+ const scoped = filter?.targetId !== undefined || filter?.browserContextId !== undefined;
1655
+ const { cookies } = scoped
1656
+ ? await this.sendBrowserCommand('Storage.getCookies', contextId ? { browserContextId: contextId } : {})
1657
+ : await this.send('Network.getCookies', urls ? { urls } : {});
1242
1658
  if (!filter) {
1243
1659
  return cookies;
1244
1660
  }
1245
1661
  return cookies.filter((c) => {
1662
+ if (filter.url && scoped) {
1663
+ const url = new URL(filter.url);
1664
+ const domain = c.domain.replace(/^\./, '');
1665
+ if (url.hostname !== domain && !(c.domain.startsWith('.') && url.hostname.endsWith('.' + domain))) {
1666
+ return false;
1667
+ }
1668
+ const pathMatches = url.pathname === c.path ||
1669
+ (url.pathname.startsWith(c.path) && (c.path.endsWith('/') || url.pathname[c.path.length] === '/'));
1670
+ if (!pathMatches || (c.secure && url.protocol !== 'https:')) {
1671
+ return false;
1672
+ }
1673
+ }
1674
+ const partition = c.partitionKey;
1675
+ if (filter.partitionKey &&
1676
+ (!partition ||
1677
+ Object.entries(filter.partitionKey).some(([key, value]) => partition[key] !== value))) {
1678
+ return false;
1679
+ }
1246
1680
  if (filter.name && c.name !== filter.name) {
1247
1681
  return false;
1248
1682
  }
@@ -1275,7 +1709,8 @@ class SessionManager {
1275
1709
  this.ensureSession();
1276
1710
  const url = params.url ?? this.state?.url ?? 'http://localhost';
1277
1711
  const { name, value, domain, path, httpOnly, secure, sameSite, expirationDate } = params;
1278
- await this.send('Network.setCookie', {
1712
+ const contextId = await this.cookieContext(params);
1713
+ const cookie = {
1279
1714
  name,
1280
1715
  value,
1281
1716
  url,
@@ -1285,40 +1720,194 @@ class SessionManager {
1285
1720
  ...(secure !== undefined && { secure }),
1286
1721
  ...(sameSite !== undefined && { sameSite }),
1287
1722
  ...(expirationDate !== undefined && { expires: expirationDate }),
1288
- });
1723
+ ...(params.partitionKey ? { partitionKey: params.partitionKey } : {}),
1724
+ };
1725
+ if (params.targetId !== undefined || params.browserContextId !== undefined) {
1726
+ await this.sendBrowserCommand('Storage.setCookies', {
1727
+ cookies: [cookie],
1728
+ ...(contextId ? { browserContextId: contextId } : {}),
1729
+ });
1730
+ }
1731
+ else {
1732
+ const result = await this.send('Network.setCookie', cookie);
1733
+ if (!result.success) {
1734
+ throw new CDPError('Browser rejected the cookie');
1735
+ }
1736
+ }
1289
1737
  }
1290
- async deleteCookie(url, name) {
1738
+ async deleteCookie(url, name, scope, exact) {
1291
1739
  this.ensureSession();
1292
- const effectiveUrl = url || this.state?.url || 'http://localhost';
1293
- await this.send('Network.deleteCookies', { name, url: effectiveUrl });
1740
+ const contextId = await this.cookieContext(scope);
1741
+ const target = scope?.targetId ?? this.currentTargetId;
1742
+ const { targetInfo } = await this.sendBrowserCommand('Target.getTargetInfo', { targetId: target });
1743
+ if (scope?.browserContextId !== undefined && contextId !== targetInfo.browserContextId) {
1744
+ throw new DriverCapabilityError('Cookie deletion requires a target in the selected browser context');
1745
+ }
1746
+ const cdp = this.cdp;
1747
+ let sid = this.targetSessions.get(target);
1748
+ let temporary = false;
1749
+ if (!sid) {
1750
+ sid = (await cdp.send('Target.attachToTarget', { targetId: target, flatten: true }))
1751
+ .sessionId;
1752
+ temporary = true;
1753
+ }
1754
+ let failure;
1755
+ let failed = false;
1756
+ try {
1757
+ exact?.onDeleteAttempt?.();
1758
+ await this.cdp.send('Network.deleteCookies', {
1759
+ name,
1760
+ ...(exact
1761
+ ? { domain: exact.domain, path: exact.path }
1762
+ : { url: url || this.state?.url || 'http://localhost' }),
1763
+ ...(scope?.partitionKey ? { partitionKey: scope.partitionKey } : {}),
1764
+ }, sid);
1765
+ exact?.onAcknowledged?.();
1766
+ }
1767
+ catch (error) {
1768
+ failed = true;
1769
+ failure = error;
1770
+ }
1771
+ if (temporary) {
1772
+ try {
1773
+ await cdp.send('Target.detachFromTarget', { sessionId: sid }, undefined, 1000, true);
1774
+ }
1775
+ catch (error) {
1776
+ if (!failed) {
1777
+ throw error;
1778
+ }
1779
+ const original = JSON.parse(formatErrorResponse(failure).content[0].text).error;
1780
+ throw new StructuredToolError(original.code, original.message, original.suggestion ?? '核对 Cookie 状态与目标连接,勿自动重放清除', { ...original.context, cleanupError: JSON.parse(formatErrorResponse(error).content[0].text).error });
1781
+ }
1782
+ }
1783
+ if (failed) {
1784
+ throw failure;
1785
+ }
1294
1786
  }
1295
1787
  async clearCookies(filter) {
1296
- this.ensureSession();
1297
- // Driver 级护栏:必须按 URL 或域名限定范围,name 只能进一步缩小范围
1298
1788
  if (!filter || (!filter.url && !filter.domain)) {
1299
- throw new Error('clearCookies 必须带 url 或 domain 过滤参数,name 只能在该范围内进一步过滤(防止跨站误清同名 cookie)');
1789
+ throw new Error('clearCookies requires url or domain');
1300
1790
  }
1301
- const urls = filter.url ? [filter.url] : undefined;
1302
- const { cookies } = (await this.send('Network.getCookies', urls ? { urls } : {}));
1303
- let count = 0;
1791
+ this.ensureSession();
1792
+ const scope = { ...filter, targetId: filter.targetId ?? this.currentTargetId };
1793
+ const cookies = await this.getCookies(scope);
1794
+ if (cookies.some((cookie) => 'partitionKeyOpaque' in cookie && !cookie.partitionKey)) {
1795
+ throw new DriverCapabilityError('Cookie 分区身份不可序列化,未执行清除');
1796
+ }
1797
+ const progress = {
1798
+ count: 0,
1799
+ matched: cookies.length,
1800
+ attempted: 0,
1801
+ acknowledged: 0,
1802
+ alreadyAbsent: 0,
1803
+ failed: 0,
1804
+ unknown: 0,
1805
+ unprocessed: cookies.length,
1806
+ countSemantics: 'observed_present_then_absent',
1807
+ };
1304
1808
  for (const cookie of cookies) {
1305
- if (filter.domain) {
1306
- const fd = filter.domain.replace(/^\./, '');
1307
- const cd = cookie.domain.replace(/^\./, '');
1308
- if (cd !== fd && !cd.endsWith('.' + fd)) {
1809
+ const partitionKey = cookie.partitionKey;
1810
+ const identityFilter = {
1811
+ ...scope,
1812
+ name: cookie.name,
1813
+ domain: cookie.domain,
1814
+ path: cookie.path,
1815
+ partitionKey,
1816
+ };
1817
+ const matches = (candidate) => {
1818
+ const candidatePartition = candidate.partitionKey;
1819
+ return (candidate.name === cookie.name &&
1820
+ candidate.domain === cookie.domain &&
1821
+ candidate.path === cookie.path &&
1822
+ Boolean(candidatePartition) === Boolean(partitionKey) &&
1823
+ candidatePartition?.topLevelSite === partitionKey?.topLevelSite &&
1824
+ candidatePartition?.hasCrossSiteAncestor === partitionKey?.hasCrossSiteAncestor);
1825
+ };
1826
+ let phase = 'precheck';
1827
+ let deleteAttempted = false;
1828
+ let acknowledged = false;
1829
+ let cleanupFailure;
1830
+ try {
1831
+ this.requestContext?.()?.signal?.throwIfAborted();
1832
+ if (!(await this.getCookies(identityFilter)).some(matches)) {
1833
+ ++progress.alreadyAbsent;
1834
+ --progress.unprocessed;
1309
1835
  continue;
1310
1836
  }
1837
+ phase = 'delete';
1838
+ ++progress.attempted;
1839
+ --progress.unprocessed;
1840
+ try {
1841
+ await this.deleteCookie('', cookie.name, { ...scope, partitionKey }, {
1842
+ domain: cookie.domain,
1843
+ path: cookie.path,
1844
+ onDeleteAttempt: () => {
1845
+ deleteAttempted = true;
1846
+ },
1847
+ onAcknowledged: () => {
1848
+ acknowledged = true;
1849
+ ++progress.acknowledged;
1850
+ },
1851
+ });
1852
+ }
1853
+ catch (error) {
1854
+ if (!acknowledged) {
1855
+ throw error;
1856
+ }
1857
+ cleanupFailure = { error };
1858
+ }
1859
+ phase = 'verification';
1860
+ if ((await this.getCookies(identityFilter)).some(matches)) {
1861
+ throw new StructuredToolError('COOKIE_STILL_PRESENT', '浏览器确认请求后仍存在相同身份的 Cookie', '读取该 Cookie 核对实际状态,勿自动重放清除', {});
1862
+ }
1863
+ ++progress.count;
1864
+ if (cleanupFailure) {
1865
+ phase = 'cleanup';
1866
+ throw cleanupFailure.error;
1867
+ }
1311
1868
  }
1312
- if (filter.name && cookie.name !== filter.name) {
1313
- continue;
1869
+ catch (error) {
1870
+ const cause = JSON.parse(formatErrorResponse(error).content[0].text).error;
1871
+ if (phase === 'delete') {
1872
+ if (!deleteAttempted ||
1873
+ cause.context?.actionExecuted === false ||
1874
+ cause.context?.protocolError === true) {
1875
+ ++progress.failed;
1876
+ }
1877
+ else {
1878
+ ++progress.unknown;
1879
+ }
1880
+ }
1881
+ else if (phase === 'verification') {
1882
+ if (cause.code === 'COOKIE_STILL_PRESENT') {
1883
+ ++progress.failed;
1884
+ }
1885
+ else {
1886
+ ++progress.unknown;
1887
+ }
1888
+ }
1889
+ const actionExecuted = progress.acknowledged > 0 ? true : progress.unknown > 0 ? 'unknown' : false;
1890
+ throw new StructuredToolError('COOKIE_CLEAR_PARTIAL', 'Cookie 清除未全部完成', '按清除进度读取实际 Cookie 状态,勿自动重放整个清除请求', {
1891
+ ...progress,
1892
+ phase,
1893
+ cause,
1894
+ ...(cleanupFailure && phase !== 'cleanup'
1895
+ ? {
1896
+ cleanupError: JSON.parse(formatErrorResponse(cleanupFailure.error).content[0].text)
1897
+ .error,
1898
+ }
1899
+ : {}),
1900
+ actionExecuted,
1901
+ actionStatus: actionExecuted === false
1902
+ ? 'not_started'
1903
+ : actionExecuted === 'unknown'
1904
+ ? 'unknown'
1905
+ : 'partial',
1906
+ retryable: false,
1907
+ });
1314
1908
  }
1315
- const protocol = cookie.secure ? 'https:' : 'http:';
1316
- const domain = cookie.domain.startsWith('.') ? cookie.domain.slice(1) : cookie.domain;
1317
- const deleteUrl = `${protocol}//${domain}${cookie.path}`;
1318
- await this.send('Network.deleteCookies', { name: cookie.name, url: deleteUrl });
1319
- count++;
1320
1909
  }
1321
- return { count };
1910
+ return progress;
1322
1911
  }
1323
1912
  async getConsoleLogs(options = {}) {
1324
1913
  let logs = this.consoleLogs;
@@ -1347,7 +1936,6 @@ class SessionManager {
1347
1936
  const result = requests;
1348
1937
  if (clear) {
1349
1938
  this.networkRequests = [];
1350
- this.requestMap.clear();
1351
1939
  }
1352
1940
  return result;
1353
1941
  }
@@ -1360,12 +1948,11 @@ class SessionManager {
1360
1948
  clearLogs() {
1361
1949
  this.consoleLogs = [];
1362
1950
  this.networkRequests = [];
1363
- this.requestMap.clear();
1364
1951
  }
1365
1952
  /**
1366
1953
  * 执行 JavaScript
1367
1954
  */
1368
- async evaluate(script, args, timeout) {
1955
+ async evaluate(script, args, timeout, userAction) {
1369
1956
  this.ensureSession();
1370
1957
  // CDP 命令超时需大于脚本执行超时,给 WebSocket 通信留余量
1371
1958
  const CDP_MARGIN = 5000;
@@ -1387,9 +1974,9 @@ class SessionManager {
1387
1974
  if (timeout !== undefined) {
1388
1975
  callParams.timeout = timeout;
1389
1976
  }
1390
- const { result, exceptionDetails } = (await this.send('Runtime.callFunctionOn', callParams, sendTimeout));
1977
+ const { result, exceptionDetails } = (await this.send('Runtime.callFunctionOn', callParams, sendTimeout, userAction));
1391
1978
  if (exceptionDetails) {
1392
- throw new Error(formatCdpException(exceptionDetails));
1979
+ throw setErrorSource(new Error(formatCdpException(exceptionDetails)), 'page');
1393
1980
  }
1394
1981
  return extractCdpValue(result);
1395
1982
  }
@@ -1405,9 +1992,9 @@ class SessionManager {
1405
1992
  if (timeout !== undefined) {
1406
1993
  evalParams.timeout = timeout;
1407
1994
  }
1408
- const { result, exceptionDetails } = (await this.send('Runtime.evaluate', evalParams, sendTimeout));
1995
+ const { result, exceptionDetails } = (await this.send('Runtime.evaluate', evalParams, sendTimeout, userAction));
1409
1996
  if (exceptionDetails) {
1410
- throw new Error(formatCdpException(exceptionDetails));
1997
+ throw setErrorSource(new Error(formatCdpException(exceptionDetails)), 'page');
1411
1998
  }
1412
1999
  return extractCdpValue(result);
1413
2000
  }
@@ -1437,16 +2024,25 @@ class SessionManager {
1437
2024
  */
1438
2025
  async clearCache(type = 'all') {
1439
2026
  this.ensureSession();
2027
+ if (type !== 'cache') {
2028
+ this.ensureEventController(this.currentTargetId, this.sessionId).assertNativeReady();
2029
+ }
1440
2030
  if (type === 'all' || type === 'cache') {
1441
2031
  await this.send('Network.clearBrowserCache');
1442
2032
  }
1443
2033
  if (type === 'all' || type === 'storage') {
1444
- await this.send('Runtime.evaluate', {
1445
- expression: `
1446
- localStorage.clear();
1447
- sessionStorage.clear();
1448
- `,
2034
+ const result = await this.send('Runtime.evaluate', {
2035
+ expression: `localStorage.clear(); sessionStorage.clear();`,
1449
2036
  });
2037
+ if (result.exceptionDetails) {
2038
+ throw new CDPError(`Storage cleanup failed: ${formatCdpException(result.exceptionDetails)}`, {
2039
+ cacheCleared: type === 'all',
2040
+ storageStatus: 'failed_or_partial',
2041
+ actionExecuted: type === 'all' ? true : 'unknown',
2042
+ actionStatus: type === 'all' ? 'partial' : 'unknown',
2043
+ retryable: false,
2044
+ });
2045
+ }
1450
2046
  }
1451
2047
  }
1452
2048
  /**
@@ -1455,7 +2051,7 @@ class SessionManager {
1455
2051
  * IBrowserDriver 接口:可选 url 参数,url 提供时新建后立即导航
1456
2052
  */
1457
2053
  async newPage(url, timeout, options = {}) {
1458
- if (Object.values(options).some((value) => value !== undefined)) {
2054
+ if (Object.entries(options).some(([key, value]) => value !== undefined && key !== 'taskHint' && key !== 'note')) {
1459
2055
  throw new DriverCapabilityError('CDP 模式不支持 Chrome UI 的 newPage 配置参数,未创建页面;请使用 Extension 模式');
1460
2056
  }
1461
2057
  const target = await this.withLock(async () => this.newPageInternal());
@@ -1506,7 +2102,8 @@ class SessionManager {
1506
2102
  return this.withLock(async () => {
1507
2103
  this.ensureConnected();
1508
2104
  const targets = await this.listTargets();
1509
- if (!targets.some((target) => target.targetId === targetId)) {
2105
+ const before = targets.find((target) => target.targetId === targetId);
2106
+ if (!before) {
1510
2107
  throw new TargetNotFoundError(targetId);
1511
2108
  }
1512
2109
  const id = targetId;
@@ -1515,15 +2112,25 @@ class SessionManager {
1515
2112
  await this.assertPageCondition(id, condition.expectedUrl, condition.expectedRevision);
1516
2113
  this.pendingPageCondition = null;
1517
2114
  }
2115
+ const sid = this.targetSessions.get(id);
2116
+ if (sid) {
2117
+ await this.eventControllers.get(sid)?.dispose('page closed');
2118
+ }
1518
2119
  const result = (await this.cdp.send('Target.closeTarget', { targetId: id }));
1519
2120
  if (!result.success) {
1520
2121
  throw new TargetNotFoundError(targetId);
1521
2122
  }
1522
2123
  this.revisions.delete(id);
2124
+ if (sid) {
2125
+ this.eventControllers.delete(sid);
2126
+ this.targetSessions.delete(id);
2127
+ }
1523
2128
  // 如果关闭的是当前页面,清除会话状态
1524
2129
  if (id === this.currentTargetId) {
1525
2130
  this.clearAttachedTargetState();
1526
2131
  }
2132
+ this.targetLogs.delete(id);
2133
+ return { targetId: id, before, after: null };
1527
2134
  });
1528
2135
  }
1529
2136
  /**
@@ -1535,6 +2142,7 @@ class SessionManager {
1535
2142
  * 2. 通过 withLock 串行化状态清理:等 withLock 中的操作处理完错误后再置空引用
1536
2143
  */
1537
2144
  async close() {
2145
+ await Promise.all([...this.eventControllers.values()].map((controller) => controller.suspend('connection closing')));
1538
2146
  // Phase 1: 立即关闭 CDP 连接(reject pending callbacks,清除 event listeners)
1539
2147
  if (this.cdp) {
1540
2148
  this.cdp.close();
@@ -1576,7 +2184,7 @@ class SessionManager {
1576
2184
  * 多步操作(type 循环、fullPage 截图等)的 await 间隙可能被 close() 打断,
1577
2185
  * ensureSession() 确保在当前 tick 内 this.cdp 非空
1578
2186
  */
1579
- async send(method, params, timeout) {
2187
+ async send(method, params, timeout, dispatchedAction) {
1580
2188
  const deadline = timeout === undefined ? undefined : Date.now() + timeout;
1581
2189
  this.ensureSession();
1582
2190
  const mutation = method === 'Page.navigate' ||
@@ -1598,10 +2206,30 @@ class SessionManager {
1598
2206
  this.pendingPageCondition = null;
1599
2207
  }
1600
2208
  const remaining = deadline === undefined ? undefined : remainingNavigationTimeout(deadline);
2209
+ const cleanupType = params?.type;
2210
+ const blocking = /^(?:Runtime\.(?:evaluate|callFunctionOn)|Input\.)/.test(method) &&
2211
+ !['mouseReleased', 'keyUp', 'touchEnd', 'touchCancel'].includes(cleanupType ?? '');
2212
+ if (blocking) {
2213
+ this.ensureEventController(this.currentTargetId, this.sessionId).assertNativeReady();
2214
+ }
1601
2215
  if (mutation && this.currentTargetId) {
1602
2216
  this.revisions.set(this.currentTargetId, (this.revisions.get(this.currentTargetId) ?? 0) + 1);
1603
2217
  }
1604
- return this.cdp.send(method, params, this.sessionId ?? undefined, remaining);
2218
+ const frame = this.frameScopes.get(this.selectedFrame);
2219
+ const scoped = frame && (/^(?:Runtime|DOM|Accessibility)\./.test(method) || method === 'Input.dispatchKeyEvent');
2220
+ const sessionId = scoped ? frame.sessionId : this.sessionId;
2221
+ const nativeParams = scoped && method === 'Runtime.evaluate' ? { ...params, contextId: frame.contextId } : params;
2222
+ const operation = this.cdp.send(method, nativeParams, sessionId, remaining, false, dispatchedAction);
2223
+ return blocking
2224
+ ? this.ensureEventController(this.currentTargetId, this.sessionId)
2225
+ .race(operation)
2226
+ .catch((error) => {
2227
+ if (error.code === 'DIALOG_OPEN') {
2228
+ throw new StructuredToolError('DIALOG_OPEN', error.message, 'Read logs type=dialog and handle the observed ref; do not replay the original action', error.context);
2229
+ }
2230
+ throw error;
2231
+ })
2232
+ : operation;
1605
2233
  }
1606
2234
  /**
1607
2235
  * 发送 browser-level CDP 命令(不携带 sessionId)
@@ -1614,6 +2242,63 @@ class SessionManager {
1614
2242
  /**
1615
2243
  * 派发 CDP Input.dispatchTouchEvent,临时启用 touch 模拟避免命令挂起
1616
2244
  */
2245
+ async getFrameOwnerZoom(owner, timeout) {
2246
+ const deadline = Date.now() + timeout;
2247
+ let objectId;
2248
+ try {
2249
+ const { object } = await this.cdp.send('DOM.resolveNode', { backendNodeId: owner.backendNodeId }, owner.parentSessionId, remainingNavigationTimeout(deadline));
2250
+ objectId = object.objectId;
2251
+ if (!objectId) {
2252
+ throw new Error('Frame owner object is unavailable');
2253
+ }
2254
+ const { result, exceptionDetails } = await this.cdp.send('Runtime.callFunctionOn', { objectId, functionDeclaration: 'function(){return this.currentCSSZoom ?? 1}', returnByValue: true }, owner.parentSessionId, remainingNavigationTimeout(deadline));
2255
+ if (exceptionDetails ||
2256
+ typeof result.value !== 'number' ||
2257
+ !Number.isFinite(result.value) ||
2258
+ result.value <= 0) {
2259
+ throw new Error('Frame owner CSS zoom is unavailable');
2260
+ }
2261
+ return result.value;
2262
+ }
2263
+ catch (error) {
2264
+ throw new StructuredToolError('FRAME_GEOMETRY_UNAVAILABLE', error instanceof Error ? error.message : String(error), '重新读取 frame 的文档和布局后再执行输入', { actionExecuted: false, actionStatus: 'not_started', retryable: false });
2265
+ }
2266
+ finally {
2267
+ if (objectId) {
2268
+ await this.cdp.send('Runtime.releaseObject', { objectId }, owner.parentSessionId, 1000).catch((error) => console.warn('[MCP] Frame zoom object cleanup failed:', error));
2269
+ }
2270
+ }
2271
+ }
2272
+ ensureEventController(targetId, sessionId) {
2273
+ let controller = this.eventControllers.get(sessionId);
2274
+ if (!controller) {
2275
+ controller = new BrowserEventController({
2276
+ backend: 'cdp',
2277
+ targetId,
2278
+ owner: this.revisionEpoch,
2279
+ nativeSessionId: sessionId,
2280
+ generation: randomUUID(),
2281
+ }, (method, params, childSessionId) => this.cdp.send(method, params, childSessionId ?? sessionId));
2282
+ this.eventControllers.set(sessionId, controller);
2283
+ }
2284
+ return controller;
2285
+ }
2286
+ async cookieContext(scope) {
2287
+ if (scope?.storeId !== undefined) {
2288
+ throw new DriverCapabilityError('CookieStore IDs belong to Extension; CDP uses browserContextId');
2289
+ }
2290
+ if (scope?.partitionKey && !scope.partitionKey.topLevelSite) {
2291
+ throw new DriverCapabilityError('CDP partitionKey requires topLevelSite');
2292
+ }
2293
+ if (!scope?.targetId) {
2294
+ return scope?.browserContextId;
2295
+ }
2296
+ const { targetInfo } = await this.sendBrowserCommand('Target.getTargetInfo', { targetId: scope.targetId });
2297
+ if (scope.browserContextId !== undefined && scope.browserContextId !== targetInfo.browserContextId) {
2298
+ throw new DriverCapabilityError('Cookie target browser context does not match browserContextId');
2299
+ }
2300
+ return targetInfo.browserContextId;
2301
+ }
1617
2302
  async dispatchTouch(params) {
1618
2303
  await this.send('Emulation.setTouchEmulationEnabled', { enabled: true });
1619
2304
  try {
@@ -1628,11 +2313,20 @@ class SessionManager {
1628
2313
  }
1629
2314
  }
1630
2315
  }
2316
+ navigationTimeout(wait, timeout, deadline) {
2317
+ const error = new NavigationTimeoutError(wait, timeout);
2318
+ const scope = this.requestContext?.();
2319
+ if (scope?.deadline !== undefined && deadline >= scope.deadline) {
2320
+ scope.budgetError ??= setErrorSource(error, 'budget');
2321
+ }
2322
+ return error;
2323
+ }
1631
2324
  /** 在触发导航前注册相应等待器,并按主 frame loader 过滤生命周期事件 */
1632
2325
  startNavigationWait(wait, timeout, signal, bindFromFrameNavigation) {
1633
2326
  this.ensureSession();
1634
2327
  const cdp = this.cdp;
1635
2328
  const sessionId = this.sessionId;
2329
+ const deadline = Date.now() + timeout;
1636
2330
  const baselineLoaderId = this.mainFrameLoaderId;
1637
2331
  const lifecycleName = wait === 'domcontentloaded' ? 'DOMContentLoaded' : wait === 'load' ? 'load' : 'networkIdle';
1638
2332
  const seenLifecycle = new Set();
@@ -1768,8 +2462,8 @@ class SessionManager {
1768
2462
  if (!actionStarted || eventSessionId !== sessionId) {
1769
2463
  return;
1770
2464
  }
1771
- const requestId = params.requestId;
1772
- if (requestId) {
2465
+ const { requestId, loaderId } = params;
2466
+ if (requestId && loaderId !== '') {
1773
2467
  sameDocumentPendingRequests.add(requestId);
1774
2468
  checkSameDocumentIdle();
1775
2469
  }
@@ -1788,7 +2482,11 @@ class SessionManager {
1788
2482
  fail(signal?.reason instanceof Error ? signal.reason : new Error('导航等待已取消'));
1789
2483
  };
1790
2484
  const onDisconnected = () => fail(new Error('CDP 连接已关闭'));
1791
- const timeoutId = setTimeout(() => fail(new NavigationTimeoutError(wait, timeout)), timeout);
2485
+ const timeoutId = setTimeout(() => {
2486
+ if (!settled) {
2487
+ fail(this.navigationTimeout(wait, timeout, deadline));
2488
+ }
2489
+ }, timeout);
1792
2490
  cdp.onEvent('Page.frameNavigated', onFrameNavigated);
1793
2491
  cdp.onEvent('Page.lifecycleEvent', onLifecycleEvent);
1794
2492
  cdp.onEvent('Page.navigatedWithinDocument', onNavigatedWithinDocument);
@@ -1819,8 +2517,10 @@ class SessionManager {
1819
2517
  * close() 时通过 'disconnected' 信号立即 reject
1820
2518
  */
1821
2519
  buildNetworkIdlePromise(cdp, timeout, idleTime, signal) {
1822
- const localPendingRequests = new Set();
2520
+ // CDP 用空 loaderId 标识 Worker 请求,页面 session 可能只收到其开始事件
2521
+ const localPendingRequests = new Set([...this.requestMap].filter(([, request]) => request.loaderId !== '').map(([requestId]) => requestId));
1823
2522
  const sessionId = this.sessionId;
2523
+ const deadline = Date.now() + timeout;
1824
2524
  return new Promise((resolve, reject) => {
1825
2525
  let idleTimer = null;
1826
2526
  let timeoutTimer = null;
@@ -1844,7 +2544,10 @@ class SessionManager {
1844
2544
  if (eventSessionId !== sessionId) {
1845
2545
  return;
1846
2546
  }
1847
- const { requestId } = params;
2547
+ const { requestId, loaderId } = params;
2548
+ if (loaderId === '') {
2549
+ return;
2550
+ }
1848
2551
  localPendingRequests.add(requestId);
1849
2552
  checkIdle();
1850
2553
  };
@@ -1875,7 +2578,7 @@ class SessionManager {
1875
2578
  };
1876
2579
  timeoutTimer = setTimeout(() => {
1877
2580
  cleanup();
1878
- reject(new NavigationTimeoutError('networkidle', timeout));
2581
+ reject(this.navigationTimeout('networkidle', timeout, deadline));
1879
2582
  }, timeout);
1880
2583
  const onDisconnected = () => {
1881
2584
  cleanup();
@@ -1902,25 +2605,21 @@ class SessionManager {
1902
2605
  if (this.currentTargetId === targetId && this.sessionId) {
1903
2606
  return;
1904
2607
  }
1905
- // 如果有之前的 session,先分离
1906
- if (this.sessionId) {
1907
- try {
1908
- await this.sendBrowserCommand('Target.detachFromTarget', {
1909
- sessionId: this.sessionId,
1910
- }, deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
1911
- }
1912
- catch {
1913
- // 忽略分离错误
1914
- }
2608
+ if (!this.targetSessions.has(targetId) && this.targetSessions.size >= 32) {
2609
+ throw new DriverCapabilityError('CDP observed page capacity reached (32); close unused pages before attaching');
1915
2610
  }
1916
2611
  this.clearAttachedTargetState();
1917
- // 附加到目标
1918
- const { sessionId } = (await this.sendBrowserCommand('Target.attachToTarget', {
1919
- targetId,
1920
- flatten: true,
1921
- }, deadline === undefined ? undefined : remainingNavigationTimeout(deadline)));
2612
+ let sessionId = this.targetSessions.get(targetId);
2613
+ if (!sessionId) {
2614
+ const attached = await this.sendBrowserCommand('Target.attachToTarget', { targetId, flatten: true }, deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
2615
+ sessionId = attached.sessionId;
2616
+ this.targetSessions.set(targetId, sessionId);
2617
+ }
1922
2618
  this.sessionId = sessionId;
1923
2619
  this.currentTargetId = targetId;
2620
+ const logs = this.targetLogs.get(targetId);
2621
+ this.consoleLogs = logs?.console ?? [];
2622
+ this.networkRequests = logs?.network ?? [];
1924
2623
  // 初始化会话
1925
2624
  await this.initSession(deadline);
1926
2625
  }
@@ -1963,13 +2662,19 @@ class SessionManager {
1963
2662
  };
1964
2663
  }
1965
2664
  clearAttachedTargetState() {
1966
- this.clearLogs();
2665
+ if (this.currentTargetId) {
2666
+ this.targetLogs.set(this.currentTargetId, { console: this.consoleLogs, network: this.networkRequests });
2667
+ }
2668
+ this.consoleLogs = [];
2669
+ this.networkRequests = [];
2670
+ this.requestMap.clear();
1967
2671
  this.challengeRequired = false;
1968
2672
  this.runtimeEnabled = false;
1969
2673
  this.mainFrameId = null;
1970
2674
  this.mainFrameLoaderId = null;
1971
2675
  this.modifiers = 0;
1972
2676
  this.sessionId = null;
2677
+ this.selectedFrame = 0;
1973
2678
  this.currentTargetId = null;
1974
2679
  this.state = null;
1975
2680
  }
@@ -1992,6 +2697,17 @@ class SessionManager {
1992
2697
  this.launcher = null;
1993
2698
  }
1994
2699
  this.clearAttachedTargetState();
2700
+ for (const controller of this.eventControllers.values()) {
2701
+ void controller.dispose('connection closed').catch(() => { });
2702
+ }
2703
+ this.eventControllers.clear();
2704
+ this.targetSessions.clear();
2705
+ this.childSessions.clear();
2706
+ this.frameSessions.clear();
2707
+ this.contexts.clear();
2708
+ this.frameScopes.clear();
2709
+ this.selectedFrame = 0;
2710
+ this.targetLogs.clear();
1995
2711
  this.revisionEpoch = randomUUID();
1996
2712
  this.revisions.clear();
1997
2713
  this.pendingPageCondition = null;
@@ -2003,6 +2719,8 @@ class SessionManager {
2003
2719
  * 串行执行操作(防止并发竞态)
2004
2720
  */
2005
2721
  async withLock(fn, deadline) {
2722
+ const signal = this.requestContext?.()?.signal;
2723
+ signal?.throwIfAborted();
2006
2724
  const previousLock = this.operationLock;
2007
2725
  let releaseLock;
2008
2726
  this.operationLock = new Promise((resolve) => {
@@ -2010,8 +2728,9 @@ class SessionManager {
2010
2728
  });
2011
2729
  let acquired = false;
2012
2730
  try {
2013
- await waitForNavigationQueue(previousLock, deadline);
2731
+ await waitForNavigationQueue(previousLock, deadline, signal);
2014
2732
  acquired = true;
2733
+ signal?.throwIfAborted();
2015
2734
  return await fn();
2016
2735
  }
2017
2736
  catch (error) {
@@ -2042,7 +2761,9 @@ class SessionManager {
2042
2761
  * 接受完成事件后清理所有监听器和超时定时器
2043
2762
  * close() 时通过 'disconnected' 信号立即 reject,不必等 timer 超时
2044
2763
  */
2045
- waitForAnyEvent(events, timeout) {
2764
+ waitForAnyEvent(events, timeout, signal = this.requestContext?.()?.signal) {
2765
+ const deadline = Date.now() + timeout;
2766
+ signal?.throwIfAborted();
2046
2767
  // 捕获当前 cdp 引用,防止 close() 并发置 null 导致回调崩溃
2047
2768
  const cdp = this.cdp;
2048
2769
  const sessionId = this.sessionId;
@@ -2053,20 +2774,30 @@ class SessionManager {
2053
2774
  const listeners = [];
2054
2775
  const cleanup = () => {
2055
2776
  clearTimeout(timer);
2777
+ signal?.removeEventListener('abort', onAbort);
2056
2778
  for (const { event, listener } of listeners) {
2057
2779
  cdp.offEvent(event, listener);
2058
2780
  }
2059
2781
  cdp.removeListener('disconnected', onDisconnected);
2060
2782
  };
2783
+ const onAbort = () => {
2784
+ cleanup();
2785
+ reject(signal?.reason ?? new Error('Request cancelled'));
2786
+ };
2061
2787
  const timer = setTimeout(() => {
2062
2788
  cleanup();
2063
- reject(new NavigationTimeoutError('navigation', timeout));
2789
+ reject(this.navigationTimeout('navigation', timeout, deadline));
2064
2790
  }, timeout);
2065
2791
  const onDisconnected = () => {
2066
2792
  cleanup();
2067
2793
  reject(new Error('CDP 连接已关闭'));
2068
2794
  };
2069
2795
  cdp.once('disconnected', onDisconnected);
2796
+ signal?.addEventListener('abort', onAbort, { once: true });
2797
+ if (signal?.aborted) {
2798
+ onAbort();
2799
+ return;
2800
+ }
2070
2801
  for (const event of events) {
2071
2802
  const listener = (params, eventSessionId) => {
2072
2803
  if (eventSessionId !== sessionId) {
@@ -2097,6 +2828,8 @@ class SessionManager {
2097
2828
  */
2098
2829
  async initSession(deadline) {
2099
2830
  const remaining = () => (deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
2831
+ this.setupEventListeners();
2832
+ this.ensureEventController(this.currentTargetId, this.sessionId);
2100
2833
  // 启用必要的域
2101
2834
  await Promise.all([
2102
2835
  this.send('Page.enable', undefined, remaining()),
@@ -2128,22 +2861,94 @@ class SessionManager {
2128
2861
  return;
2129
2862
  }
2130
2863
  this.listenersInstalled = true;
2864
+ for (const method of BROWSER_EVENT_METHODS) {
2865
+ this.cdp.onEvent(method, (params, sid) => {
2866
+ const root = sid && (this.childSessions.get(sid) ?? sid);
2867
+ if (root) {
2868
+ this.eventControllers.get(root)?.handle(method, params, sid);
2869
+ }
2870
+ });
2871
+ }
2872
+ this.cdp.onEvent('Runtime.executionContextCreated', (raw, sid) => {
2873
+ const c = raw.context;
2874
+ if (sid && c.auxData?.frameId) {
2875
+ const contexts = this.contexts.get(sid) ?? [];
2876
+ contexts.push({ id: c.id, frameId: c.auxData.frameId, isDefault: c.auxData.isDefault === true });
2877
+ this.contexts.set(sid, contexts);
2878
+ }
2879
+ });
2880
+ this.cdp.onEvent('Runtime.executionContextDestroyed', (raw, sid) => {
2881
+ if (sid) {
2882
+ this.contexts.set(sid, (this.contexts.get(sid) ?? []).filter((c) => c.id !== raw.executionContextId));
2883
+ }
2884
+ });
2885
+ this.cdp.onEvent('Runtime.executionContextsCleared', (_, sid) => {
2886
+ if (sid) {
2887
+ this.contexts.delete(sid);
2888
+ }
2889
+ });
2890
+ this.cdp.onEvent('Target.attachedToTarget', (raw, parent) => {
2891
+ const p = raw;
2892
+ if (!parent || p.targetInfo.type !== 'iframe') {
2893
+ return;
2894
+ }
2895
+ const root = this.childSessions.get(parent) ?? parent;
2896
+ this.childSessions.set(p.sessionId, root);
2897
+ this.frameSessions.set(p.targetInfo.targetId, p.sessionId);
2898
+ void (async () => {
2899
+ await this.cdp.send('Runtime.enable', {}, p.sessionId);
2900
+ await this.cdp.send('Target.setAutoAttach', {
2901
+ autoAttach: true,
2902
+ waitForDebuggerOnStart: false,
2903
+ flatten: true,
2904
+ filter: [{ type: 'iframe', exclude: false }],
2905
+ }, p.sessionId);
2906
+ })().catch((error) => console.warn('[MCP] OOPIF context setup failed:', error));
2907
+ });
2908
+ this.cdp.onEvent('Target.detachedFromTarget', (raw) => {
2909
+ const sid = raw.sessionId;
2910
+ for (const [targetId, session] of this.targetSessions) {
2911
+ if (session !== sid) {
2912
+ continue;
2913
+ }
2914
+ const controller = this.eventControllers.get(sid);
2915
+ this.targetSessions.delete(targetId);
2916
+ this.eventControllers.delete(sid);
2917
+ if (this.currentTargetId === targetId) {
2918
+ this.clearAttachedTargetState();
2919
+ }
2920
+ if (controller) {
2921
+ void controller
2922
+ .dispose('native target detached')
2923
+ .catch((error) => console.warn('[MCP] Native target event cleanup outcome:', error));
2924
+ }
2925
+ }
2926
+ this.contexts.delete(sid);
2927
+ this.childSessions.delete(sid);
2928
+ for (const [id, session] of this.frameSessions) {
2929
+ if (session === sid) {
2930
+ this.frameSessions.delete(id);
2931
+ }
2932
+ }
2933
+ });
2131
2934
  this.cdp.onEvent('Page.frameNavigated', (params, eventSessionId) => {
2132
- if (!this.isCurrentSessionEvent(eventSessionId)) {
2935
+ const targetId = [...this.targetSessions].find(([, sid]) => sid === eventSessionId)?.[0];
2936
+ if (!targetId) {
2133
2937
  return;
2134
2938
  }
2135
2939
  const frame = params.frame;
2136
2940
  if (frame?.id && !frame.parentId) {
2137
- this.mainFrameId = frame.id;
2138
- this.mainFrameLoaderId = frame.loaderId ?? null;
2139
- if (this.currentTargetId) {
2140
- this.revisions.set(this.currentTargetId, (this.revisions.get(this.currentTargetId) ?? 0) + 1);
2941
+ if (targetId === this.currentTargetId) {
2942
+ this.mainFrameId = frame.id;
2943
+ this.mainFrameLoaderId = frame.loaderId ?? null;
2141
2944
  }
2945
+ this.revisions.set(targetId, (this.revisions.get(targetId) ?? 0) + 1);
2142
2946
  }
2143
2947
  });
2144
2948
  this.cdp.onEvent('Page.navigatedWithinDocument', (_params, eventSessionId) => {
2145
- if (this.isCurrentSessionEvent(eventSessionId) && this.currentTargetId) {
2146
- this.revisions.set(this.currentTargetId, (this.revisions.get(this.currentTargetId) ?? 0) + 1);
2949
+ const targetId = [...this.targetSessions].find(([, sid]) => sid === eventSessionId)?.[0];
2950
+ if (targetId) {
2951
+ this.revisions.set(targetId, (this.revisions.get(targetId) ?? 0) + 1);
2147
2952
  }
2148
2953
  });
2149
2954
  // 控制台日志
@@ -2165,6 +2970,24 @@ class SessionManager {
2165
2970
  this.consoleLogs.splice(0, this.consoleLogs.length - 800);
2166
2971
  }
2167
2972
  });
2973
+ this.cdp.onEvent('Runtime.exceptionThrown', (params, eventSessionId) => {
2974
+ if (!this.isCurrentSessionEvent(eventSessionId)) {
2975
+ return;
2976
+ }
2977
+ const p = params;
2978
+ this.consoleLogs.push({
2979
+ sequence: ++this.nextConsoleLogSequence,
2980
+ source: 'javascript',
2981
+ level: 'error',
2982
+ text: formatCdpException(p.exceptionDetails),
2983
+ timestamp: Math.round(p.timestamp),
2984
+ url: p.exceptionDetails.url,
2985
+ lineNumber: p.exceptionDetails.lineNumber,
2986
+ });
2987
+ if (this.consoleLogs.length > SessionManager.MAX_LOG_ENTRIES) {
2988
+ this.consoleLogs.splice(0, this.consoleLogs.length - 800);
2989
+ }
2990
+ });
2168
2991
  // 网络请求
2169
2992
  this.cdp.onEvent('Network.requestWillBeSent', (params, eventSessionId) => {
2170
2993
  if (!this.isCurrentSessionEvent(eventSessionId)) {
@@ -2177,6 +3000,7 @@ class SessionManager {
2177
3000
  type: p.type,
2178
3001
  timestamp: Math.round(p.wallTime * 1000), // wallTime 是 epoch 秒 → epoch 毫秒
2179
3002
  frameId: p.frameId,
3003
+ loaderId: p.loaderId,
2180
3004
  _monotonic: p.timestamp, // MonotonicTime 用于 duration 计算
2181
3005
  });
2182
3006
  });
@@ -2187,28 +3011,17 @@ class SessionManager {
2187
3011
  const p = params;
2188
3012
  const request = this.requestMap.get(p.requestId);
2189
3013
  if (request) {
2190
- const { _monotonic, frameId, ...requestData } = request;
2191
3014
  const challenge = isCloudflareChallenge(p.response.headers);
2192
- if (requestData.type.toLowerCase() === 'document' && frameId === this.mainFrameId) {
3015
+ if (request.type.toLowerCase() === 'document' && request.frameId === this.mainFrameId) {
2193
3016
  // 仅新的主文档响应可以解除已知 Challenge,清空日志不能解除该状态
2194
3017
  this.challengeRequired = challenge;
2195
3018
  }
2196
- this.networkRequests.push({
2197
- sequence: ++this.nextNetworkRequestSequence,
2198
- ...requestData,
2199
- status: p.response.status,
2200
- challenge,
2201
- duration: Math.round((p.timestamp - _monotonic) * 1000),
2202
- });
2203
- // 环形缓冲区:批量裁剪到 800 条,均摊 O(n) 开销
2204
- if (this.networkRequests.length > SessionManager.MAX_LOG_ENTRIES) {
2205
- this.networkRequests.splice(0, this.networkRequests.length - 800);
2206
- }
2207
- this.requestMap.delete(p.requestId);
3019
+ request.status = p.response.status;
3020
+ request.challenge = challenge;
2208
3021
  }
2209
3022
  });
2210
3023
  // 网络请求失败时写入日志再清理 requestMap,防止 diagnostics 丢失失败请求
2211
- this.cdp.onEvent('Network.loadingFailed', (params, eventSessionId) => {
3024
+ const finalizeRequest = (params, eventSessionId) => {
2212
3025
  if (!this.isCurrentSessionEvent(eventSessionId)) {
2213
3026
  return;
2214
3027
  }
@@ -2217,6 +3030,7 @@ class SessionManager {
2217
3030
  if (request) {
2218
3031
  const { _monotonic, ...requestData } = request;
2219
3032
  delete requestData.frameId;
3033
+ delete requestData.loaderId;
2220
3034
  this.networkRequests.push({
2221
3035
  sequence: ++this.nextNetworkRequestSequence,
2222
3036
  ...requestData,
@@ -2229,7 +3043,9 @@ class SessionManager {
2229
3043
  }
2230
3044
  }
2231
3045
  this.requestMap.delete(p.requestId);
2232
- });
3046
+ };
3047
+ this.cdp.onEvent('Network.loadingFinished', finalizeRequest);
3048
+ this.cdp.onEvent('Network.loadingFailed', finalizeRequest);
2233
3049
  }
2234
3050
  /**
2235
3051
  * 更新页面状态