@pyrokine/mcp-chrome 3.0.1 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +678 -341
- package/README_zh.md +694 -291
- package/dist/cdp/client.d.ts +7 -3
- package/dist/cdp/client.d.ts.map +1 -1
- package/dist/cdp/client.js +252 -63
- package/dist/cdp/client.js.map +1 -1
- package/dist/cdp/launcher.d.ts +1 -1
- package/dist/cdp/launcher.d.ts.map +1 -1
- package/dist/cdp/launcher.js +33 -12
- package/dist/cdp/launcher.js.map +1 -1
- package/dist/core/auto-wait.d.ts.map +1 -1
- package/dist/core/auto-wait.js +88 -52
- package/dist/core/auto-wait.js.map +1 -1
- package/dist/core/browser-driver.d.ts +72 -15
- package/dist/core/browser-driver.d.ts.map +1 -1
- package/dist/core/browser-driver.js.map +1 -1
- package/dist/core/browser-event-schema.d.ts +287 -0
- package/dist/core/browser-event-schema.d.ts.map +1 -0
- package/dist/core/browser-event-schema.js +104 -0
- package/dist/core/browser-event-schema.js.map +1 -0
- package/dist/core/browser-events.d.ts +99 -0
- package/dist/core/browser-events.d.ts.map +1 -0
- package/dist/core/browser-events.js +1312 -0
- package/dist/core/browser-events.js.map +1 -0
- package/dist/core/challenge-page.d.ts +39 -0
- package/dist/core/challenge-page.d.ts.map +1 -0
- package/dist/core/challenge-page.js +226 -0
- package/dist/core/challenge-page.js.map +1 -0
- package/dist/core/dom-helpers.d.ts +28 -0
- package/dist/core/dom-helpers.d.ts.map +1 -0
- package/dist/core/dom-helpers.js +311 -0
- package/dist/core/dom-helpers.js.map +1 -0
- package/dist/core/errors.d.ts +4 -0
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/errors.js +51 -7
- package/dist/core/errors.js.map +1 -1
- package/dist/core/file-upload.d.ts +22 -0
- package/dist/core/file-upload.d.ts.map +1 -0
- package/dist/core/file-upload.js +194 -0
- package/dist/core/file-upload.js.map +1 -0
- package/dist/core/locator.d.ts +10 -2
- package/dist/core/locator.d.ts.map +1 -1
- package/dist/core/locator.js +121 -200
- package/dist/core/locator.js.map +1 -1
- package/dist/core/os-mouse.d.ts +11 -0
- package/dist/core/os-mouse.d.ts.map +1 -1
- package/dist/core/os-mouse.js +102 -29
- package/dist/core/os-mouse.js.map +1 -1
- package/dist/core/retry.d.ts.map +1 -1
- package/dist/core/retry.js +4 -1
- package/dist/core/retry.js.map +1 -1
- package/dist/core/session.d.ts +61 -12
- package/dist/core/session.d.ts.map +1 -1
- package/dist/core/session.js +1040 -259
- package/dist/core/session.js.map +1 -1
- package/dist/core/types.d.ts +5 -1
- package/dist/core/types.d.ts.map +1 -1
- package/dist/core/types.js +16 -1
- package/dist/core/types.js.map +1 -1
- package/dist/core/unified-session.d.ts +41 -35
- package/dist/core/unified-session.d.ts.map +1 -1
- package/dist/core/unified-session.js +872 -263
- package/dist/core/unified-session.js.map +1 -1
- package/dist/core/utils.d.ts +5 -4
- package/dist/core/utils.d.ts.map +1 -1
- package/dist/core/utils.js +73 -18
- package/dist/core/utils.js.map +1 -1
- package/dist/extension/bridge.d.ts +48 -17
- package/dist/extension/bridge.d.ts.map +1 -1
- package/dist/extension/bridge.js +239 -37
- package/dist/extension/bridge.js.map +1 -1
- package/dist/extension/http-server.d.ts +7 -2
- package/dist/extension/http-server.d.ts.map +1 -1
- package/dist/extension/http-server.js +211 -49
- package/dist/extension/http-server.js.map +1 -1
- package/dist/index.js +14 -1
- package/dist/index.js.map +1 -1
- package/dist/tools/browse.d.ts.map +1 -1
- package/dist/tools/browse.js +56 -28
- package/dist/tools/browse.js.map +1 -1
- package/dist/tools/browser-event-output.d.ts +7 -0
- package/dist/tools/browser-event-output.d.ts.map +1 -0
- package/dist/tools/browser-event-output.js +19 -0
- package/dist/tools/browser-event-output.js.map +1 -0
- package/dist/tools/challenge.d.ts +17 -5
- package/dist/tools/challenge.d.ts.map +1 -1
- package/dist/tools/challenge.js +110 -189
- package/dist/tools/challenge.js.map +1 -1
- package/dist/tools/cookies.d.ts.map +1 -1
- package/dist/tools/cookies.js +33 -8
- package/dist/tools/cookies.js.map +1 -1
- package/dist/tools/diagnostics.d.ts.map +1 -1
- package/dist/tools/diagnostics.js +14 -0
- package/dist/tools/diagnostics.js.map +1 -1
- package/dist/tools/evaluate.d.ts +6 -5
- package/dist/tools/evaluate.d.ts.map +1 -1
- package/dist/tools/evaluate.js +92 -52
- package/dist/tools/evaluate.js.map +1 -1
- package/dist/tools/extract.d.ts.map +1 -1
- package/dist/tools/extract.js +149 -103
- package/dist/tools/extract.js.map +1 -1
- package/dist/tools/input.d.ts.map +1 -1
- package/dist/tools/input.js +555 -229
- package/dist/tools/input.js.map +1 -1
- package/dist/tools/logs.d.ts.map +1 -1
- package/dist/tools/logs.js +50 -11
- package/dist/tools/logs.js.map +1 -1
- package/dist/tools/manage.d.ts.map +1 -1
- package/dist/tools/manage.js +111 -16
- package/dist/tools/manage.js.map +1 -1
- package/dist/tools/network-sanitizer.d.ts +1 -0
- package/dist/tools/network-sanitizer.d.ts.map +1 -1
- package/dist/tools/network-sanitizer.js +30 -1
- package/dist/tools/network-sanitizer.js.map +1 -1
- package/dist/tools/page-context.d.ts +4 -3
- package/dist/tools/page-context.d.ts.map +1 -1
- package/dist/tools/page-context.js +56 -14
- package/dist/tools/page-context.js.map +1 -1
- package/dist/tools/post-condition.d.ts +1 -1
- package/dist/tools/post-condition.d.ts.map +1 -1
- package/dist/tools/post-condition.js +136 -44
- package/dist/tools/post-condition.js.map +1 -1
- package/dist/tools/schema.d.ts +7 -4
- package/dist/tools/schema.d.ts.map +1 -1
- package/dist/tools/schema.js +32 -122
- package/dist/tools/schema.js.map +1 -1
- package/dist/tools/target-diagnostics.d.ts +3 -3
- package/dist/tools/target-diagnostics.d.ts.map +1 -1
- package/dist/tools/target-diagnostics.js +17 -7
- package/dist/tools/target-diagnostics.js.map +1 -1
- package/dist/tools/wait.d.ts.map +1 -1
- package/dist/tools/wait.js +94 -40
- package/dist/tools/wait.js.map +1 -1
- package/extension/dist/assets/{content.ts-qe6IB5DK.js → content.ts-BAMOcF3R.js} +1 -1
- package/extension/dist/assets/{content.ts-loader-DUWbDHRS.js → content.ts-loader-4F9a1EWZ.js} +1 -1
- package/extension/dist/assets/index.ts-B79g2ikq.js +19820 -0
- package/extension/dist/assets/{page-scripts-D508WLkW.js → page-scripts-CSxn58h1.js} +257 -366
- package/extension/dist/assets/{popup.html-B-eVq48O.js → popup.html-DwwHo00N.js} +2 -2
- package/extension/dist/manifest.json +4 -4
- package/extension/dist/service-worker-loader.js +1 -1
- package/extension/dist/src/popup/popup.html +3 -3
- package/package.json +8 -6
- package/scripts/start-chrome.ps1 +9 -1
- package/extension/dist/assets/index.ts-D7_LCUoV.js +0 -9319
package/dist/core/session.js
CHANGED
|
@@ -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,
|
|
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;
|
|
@@ -97,6 +101,14 @@ class SessionManager {
|
|
|
97
101
|
requestMap = new Map();
|
|
98
102
|
// 监听器安装标志(防止重复安装)
|
|
99
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;
|
|
100
112
|
constructor() { }
|
|
101
113
|
/**
|
|
102
114
|
* 获取当前调试端口
|
|
@@ -117,35 +129,85 @@ class SessionManager {
|
|
|
117
129
|
* 只有连接失败时才启动新浏览器
|
|
118
130
|
*/
|
|
119
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();
|
|
120
140
|
return this.withLock(async () => {
|
|
141
|
+
remaining();
|
|
121
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
|
+
}
|
|
122
175
|
// 如果指定了端口,先尝试连接已运行的浏览器
|
|
123
|
-
if (port > 0) {
|
|
176
|
+
if (port > 0 && !processParameters) {
|
|
177
|
+
let reuseClient;
|
|
124
178
|
try {
|
|
125
|
-
const endpoint = await getBrowserWSEndpoint('127.0.0.1', port);
|
|
179
|
+
const endpoint = await getBrowserWSEndpoint('127.0.0.1', port, remaining(), signal);
|
|
126
180
|
// 连接成功,复用已有浏览器
|
|
181
|
+
remaining();
|
|
127
182
|
this.resetState();
|
|
128
183
|
this.stealthMode = options.stealth ?? 'safe';
|
|
129
|
-
|
|
130
|
-
|
|
184
|
+
reuseClient = new CDPClient(() => this.requestContext?.());
|
|
185
|
+
this.cdp = reuseClient;
|
|
186
|
+
await reuseClient.connect(endpoint, remaining());
|
|
187
|
+
remaining();
|
|
131
188
|
// 记录端口(connect 模式没有 launcher)
|
|
132
189
|
this.connectedPort = port;
|
|
133
190
|
// 获取现有页面
|
|
134
|
-
const targets = await getTargets('127.0.0.1', port);
|
|
191
|
+
const targets = await getTargets('127.0.0.1', port, remaining(), signal);
|
|
192
|
+
remaining();
|
|
135
193
|
let pageTarget = targets.find((t) => t.type === 'page');
|
|
136
194
|
// 如果没有页面或 attach 失败,创建新 tab
|
|
137
195
|
if (pageTarget) {
|
|
138
196
|
try {
|
|
139
|
-
await this.attachToTargetInternal(pageTarget.id);
|
|
197
|
+
await this.attachToTargetInternal(pageTarget.id, deadline);
|
|
198
|
+
remaining();
|
|
140
199
|
}
|
|
141
200
|
catch {
|
|
201
|
+
remaining();
|
|
142
202
|
// attach 失败,创建新 tab
|
|
143
203
|
pageTarget = undefined;
|
|
144
204
|
}
|
|
145
205
|
}
|
|
146
206
|
if (!pageTarget) {
|
|
147
207
|
// 创建新 tab(在已有窗口)
|
|
208
|
+
remaining();
|
|
148
209
|
const newTarget = await this.newPageInternal();
|
|
210
|
+
remaining();
|
|
149
211
|
return {
|
|
150
212
|
...newTarget,
|
|
151
213
|
reused: true,
|
|
@@ -161,35 +223,65 @@ class SessionManager {
|
|
|
161
223
|
targetCreated: false,
|
|
162
224
|
};
|
|
163
225
|
}
|
|
164
|
-
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();
|
|
165
235
|
// 连接失败,继续启动新浏览器
|
|
166
236
|
}
|
|
167
237
|
}
|
|
168
238
|
// 关闭现有会话
|
|
239
|
+
remaining();
|
|
169
240
|
this.resetState();
|
|
170
241
|
// 保存 stealth 模式
|
|
171
242
|
this.stealthMode = options.stealth ?? 'safe';
|
|
172
243
|
// 启动浏览器
|
|
173
|
-
|
|
174
|
-
const
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
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
|
+
};
|
|
183
272
|
}
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
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);
|
|
193
285
|
}
|
|
194
286
|
/**
|
|
195
287
|
* 连接到已运行的浏览器
|
|
@@ -204,7 +296,7 @@ class SessionManager {
|
|
|
204
296
|
// 获取 WebSocket 端点
|
|
205
297
|
const endpoint = await getBrowserWSEndpoint(host, port);
|
|
206
298
|
// 连接 CDP
|
|
207
|
-
this.cdp = new CDPClient();
|
|
299
|
+
this.cdp = new CDPClient(() => this.requestContext?.());
|
|
208
300
|
await this.cdp.connect(endpoint, timeout);
|
|
209
301
|
this.connectedPort = port;
|
|
210
302
|
// 获取第一个页面
|
|
@@ -262,12 +354,15 @@ class SessionManager {
|
|
|
262
354
|
this.ensureSession();
|
|
263
355
|
const { wait = 'load' } = options;
|
|
264
356
|
const abortController = new AbortController();
|
|
265
|
-
const
|
|
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);
|
|
266
360
|
navigationWait.promise.catch(() => { });
|
|
267
361
|
navigationWait.markActionStarted();
|
|
268
362
|
try {
|
|
269
363
|
const { frameId, loaderId, errorText } = (await this.send('Page.navigate', { url }, remainingNavigationTimeout(deadline)));
|
|
270
364
|
if (errorText) {
|
|
365
|
+
// noinspection ExceptionCaughtLocallyJS -- Report failure
|
|
271
366
|
throw new NavigationError(url, errorText);
|
|
272
367
|
}
|
|
273
368
|
if (loaderId) {
|
|
@@ -282,7 +377,7 @@ class SessionManager {
|
|
|
282
377
|
throw error;
|
|
283
378
|
}
|
|
284
379
|
await navigationWait.promise;
|
|
285
|
-
await this.updateState(remainingNavigationTimeout(deadline));
|
|
380
|
+
await withNavigationMetadata(() => this.updateState(remainingNavigationTimeout(deadline)));
|
|
286
381
|
}, deadline);
|
|
287
382
|
}
|
|
288
383
|
/**
|
|
@@ -292,7 +387,7 @@ class SessionManager {
|
|
|
292
387
|
*/
|
|
293
388
|
async waitForNetworkIdle(timeout, idleTime = 500) {
|
|
294
389
|
this.ensureSession();
|
|
295
|
-
return this.buildNetworkIdlePromise(this.cdp, timeout, idleTime);
|
|
390
|
+
return this.buildNetworkIdlePromise(this.cdp, timeout, idleTime, this.requestContext?.()?.signal);
|
|
296
391
|
}
|
|
297
392
|
/**
|
|
298
393
|
* 等待导航完成(跨文档导航或同文档导航)
|
|
@@ -312,14 +407,21 @@ class SessionManager {
|
|
|
312
407
|
if (currentIndex <= 0) {
|
|
313
408
|
return { navigated: false };
|
|
314
409
|
}
|
|
410
|
+
const abortController = new AbortController();
|
|
411
|
+
const requestSignal = this.requestContext?.()?.signal;
|
|
315
412
|
// 跨文档加载、主 frame BFCache 恢复和同文档导航分别提供完成事件
|
|
316
|
-
const waitPromise = this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument', 'Page.frameNavigated'], remainingNavigationTimeout(deadline));
|
|
317
|
-
// 预注册 rejection handler
|
|
318
|
-
// 其 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
|
|
319
415
|
waitPromise.catch(() => { });
|
|
320
|
-
|
|
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
|
+
}
|
|
321
423
|
await waitPromise;
|
|
322
|
-
await this.updateState(remainingNavigationTimeout(deadline));
|
|
424
|
+
await withNavigationMetadata(() => this.updateState(remainingNavigationTimeout(deadline)));
|
|
323
425
|
return { navigated: true };
|
|
324
426
|
}, deadline);
|
|
325
427
|
}
|
|
@@ -334,12 +436,20 @@ class SessionManager {
|
|
|
334
436
|
if (currentIndex >= entries.length - 1) {
|
|
335
437
|
return { navigated: false };
|
|
336
438
|
}
|
|
439
|
+
const abortController = new AbortController();
|
|
440
|
+
const requestSignal = this.requestContext?.()?.signal;
|
|
337
441
|
// 跨文档加载、主 frame BFCache 恢复和同文档导航分别提供完成事件
|
|
338
|
-
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);
|
|
339
443
|
waitPromise.catch(() => { });
|
|
340
|
-
|
|
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
|
+
}
|
|
341
451
|
await waitPromise;
|
|
342
|
-
await this.updateState(remainingNavigationTimeout(deadline));
|
|
452
|
+
await withNavigationMetadata(() => this.updateState(remainingNavigationTimeout(deadline)));
|
|
343
453
|
return { navigated: true };
|
|
344
454
|
}, deadline);
|
|
345
455
|
}
|
|
@@ -351,7 +461,9 @@ class SessionManager {
|
|
|
351
461
|
return this.withLock(async () => {
|
|
352
462
|
this.ensureSession();
|
|
353
463
|
const abortController = new AbortController();
|
|
354
|
-
const
|
|
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);
|
|
355
467
|
navigationWait.promise.catch(() => { });
|
|
356
468
|
navigationWait.markActionStarted();
|
|
357
469
|
try {
|
|
@@ -362,7 +474,7 @@ class SessionManager {
|
|
|
362
474
|
throw error;
|
|
363
475
|
}
|
|
364
476
|
await navigationWait.promise;
|
|
365
|
-
await this.updateState(remainingNavigationTimeout(deadline));
|
|
477
|
+
await withNavigationMetadata(() => this.updateState(remainingNavigationTimeout(deadline)));
|
|
366
478
|
}, deadline);
|
|
367
479
|
}
|
|
368
480
|
/**
|
|
@@ -370,7 +482,23 @@ class SessionManager {
|
|
|
370
482
|
*/
|
|
371
483
|
createLocator(target, options) {
|
|
372
484
|
this.ensureSession();
|
|
373
|
-
|
|
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),
|
|
374
502
|
...options,
|
|
375
503
|
nth: options?.nth ?? target.nth,
|
|
376
504
|
getUrl: () => this.state?.url,
|
|
@@ -381,7 +509,7 @@ class SessionManager {
|
|
|
381
509
|
*/
|
|
382
510
|
createAutoWait(options) {
|
|
383
511
|
this.ensureSession();
|
|
384
|
-
return new AutoWait(this.cdp, this.sessionId, options);
|
|
512
|
+
return new AutoWait(this.cdp, this.frameScopes.get(this.selectedFrame)?.sessionId ?? this.sessionId, options);
|
|
385
513
|
}
|
|
386
514
|
/**
|
|
387
515
|
* 获取行为模拟器
|
|
@@ -448,6 +576,9 @@ class SessionManager {
|
|
|
448
576
|
modifiers: this.modifiers,
|
|
449
577
|
});
|
|
450
578
|
}
|
|
579
|
+
getModifiers() {
|
|
580
|
+
return this.modifiers;
|
|
581
|
+
}
|
|
451
582
|
/**
|
|
452
583
|
* 键盘按下
|
|
453
584
|
*
|
|
@@ -455,7 +586,6 @@ class SessionManager {
|
|
|
455
586
|
* 上层 unified-session 维护 pressedKeys Set 决定是否启用
|
|
456
587
|
*/
|
|
457
588
|
async keyDown(key, commands, options, timeout) {
|
|
458
|
-
const deadline = timeout === undefined ? undefined : Date.now() + timeout;
|
|
459
589
|
this.ensureSession();
|
|
460
590
|
const nextModifiers = MODIFIER_KEYS[key] ? this.modifiers | MODIFIER_KEYS[key] : this.modifiers;
|
|
461
591
|
const keyDefinition = getKeyDefinition(key);
|
|
@@ -473,26 +603,33 @@ class SessionManager {
|
|
|
473
603
|
}
|
|
474
604
|
await this.send('Input.dispatchKeyEvent', params, timeout);
|
|
475
605
|
this.modifiers = nextModifiers;
|
|
476
|
-
if (deadline !== undefined) {
|
|
477
|
-
remainingNavigationTimeout(deadline);
|
|
478
|
-
}
|
|
479
606
|
}
|
|
480
607
|
/**
|
|
481
608
|
* 键盘释放
|
|
482
609
|
*/
|
|
483
|
-
async keyUp(key, timeout) {
|
|
484
|
-
const deadline = timeout === undefined ? undefined : Date.now() + timeout;
|
|
485
|
-
this.ensureSession();
|
|
610
|
+
async keyUp(key, timeout, inputContext) {
|
|
486
611
|
const keyDefinition = getKeyDefinition(key);
|
|
487
|
-
const nextModifiers = MODIFIER_KEYS[key] ? this.modifiers & ~MODIFIER_KEYS[key] : this.modifiers;
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
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;
|
|
496
633
|
}
|
|
497
634
|
}
|
|
498
635
|
/**
|
|
@@ -583,40 +720,25 @@ class SessionManager {
|
|
|
583
720
|
if (fullPage) {
|
|
584
721
|
// 获取页面完整高度
|
|
585
722
|
const sizeExpr = 'JSON.stringify({ width: document.documentElement.scrollWidth, ' +
|
|
586
|
-
'height: document.documentElement.scrollHeight })';
|
|
723
|
+
'height: document.documentElement.scrollHeight, devicePixelRatio: window.devicePixelRatio })';
|
|
587
724
|
const { result } = (await this.send('Runtime.evaluate', {
|
|
588
725
|
expression: sizeExpr,
|
|
589
726
|
returnByValue: true,
|
|
590
727
|
}));
|
|
591
|
-
let width, height;
|
|
728
|
+
let width, height, devicePixelRatio;
|
|
592
729
|
try {
|
|
593
730
|
;
|
|
594
|
-
({ width, height } = JSON.parse(result.value));
|
|
731
|
+
({ width, height, devicePixelRatio } = JSON.parse(result.value));
|
|
595
732
|
}
|
|
596
733
|
catch {
|
|
597
734
|
throw new Error(`screenshot: 无法解析页面尺寸: ${result.value}`);
|
|
598
735
|
}
|
|
599
|
-
assertScreenshotBudget(width, height, scale ?? 1);
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
mobile: false,
|
|
606
|
-
});
|
|
607
|
-
try {
|
|
608
|
-
const { data } = (await this.send('Page.captureScreenshot', captureParams));
|
|
609
|
-
assertScreenshotBase64Budget(data);
|
|
610
|
-
return { data, format: effectiveFormat };
|
|
611
|
-
}
|
|
612
|
-
finally {
|
|
613
|
-
try {
|
|
614
|
-
await this.send('Emulation.clearDeviceMetricsOverride');
|
|
615
|
-
}
|
|
616
|
-
catch {
|
|
617
|
-
// cleanup failure, ignore to preserve original error
|
|
618
|
-
}
|
|
619
|
-
}
|
|
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 };
|
|
620
742
|
}
|
|
621
743
|
if (clip) {
|
|
622
744
|
assertScreenshotBudget(clip.width, clip.height, scale ?? 1);
|
|
@@ -653,7 +775,7 @@ class SessionManager {
|
|
|
653
775
|
const state = JSON.parse(result.value);
|
|
654
776
|
// 获取可交互元素
|
|
655
777
|
await this.send('Accessibility.enable');
|
|
656
|
-
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));
|
|
657
779
|
const interactiveRoles = [
|
|
658
780
|
'button',
|
|
659
781
|
'link',
|
|
@@ -687,8 +809,9 @@ class SessionManager {
|
|
|
687
809
|
async getPageHtml(selector, outer = true) {
|
|
688
810
|
this.ensureSession();
|
|
689
811
|
if (selector) {
|
|
812
|
+
await this.evaluate(`(${installDomHelpers.toString()})();`);
|
|
690
813
|
const prop = outer ? 'outerHTML' : 'innerHTML';
|
|
691
|
-
return this.evaluate(`((s, p) => { const el =
|
|
814
|
+
return this.evaluate(`((s, p) => { const el = globalThis.__mcpDomHelpers.query({selector:s})[0]; return el ? el[p] : '' })`, [selector, prop]);
|
|
692
815
|
}
|
|
693
816
|
return this.evaluate('document.documentElement.outerHTML');
|
|
694
817
|
}
|
|
@@ -698,8 +821,9 @@ class SessionManager {
|
|
|
698
821
|
async getPageText(selector) {
|
|
699
822
|
this.ensureSession();
|
|
700
823
|
if (selector) {
|
|
824
|
+
await this.evaluate(`(${installDomHelpers.toString()})();`);
|
|
701
825
|
return this.evaluate(`(s => {
|
|
702
|
-
const element =
|
|
826
|
+
const element = globalThis.__mcpDomHelpers.query({selector:s})[0];
|
|
703
827
|
return element instanceof HTMLElement ? element.innerText : (element?.textContent ?? '');
|
|
704
828
|
})`, [selector]);
|
|
705
829
|
}
|
|
@@ -709,11 +833,17 @@ class SessionManager {
|
|
|
709
833
|
/** Extension readPage 等价物:CDP 通过页面 DOM 构造 pageContent 和 interactiveElements */
|
|
710
834
|
async readPage(options) {
|
|
711
835
|
const state = await this.getPageState();
|
|
712
|
-
const interactiveElements = await this.collectInteractiveElements(options?.depth);
|
|
836
|
+
const interactiveElements = await this.collectInteractiveElements(options?.depth, options?.target, options?.timeout);
|
|
713
837
|
const lines = interactiveElements.map((e) => {
|
|
714
838
|
let line = e.role;
|
|
715
839
|
if (e.name) {
|
|
716
|
-
line += `
|
|
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)}`;
|
|
717
847
|
}
|
|
718
848
|
return line;
|
|
719
849
|
});
|
|
@@ -723,9 +853,11 @@ class SessionManager {
|
|
|
723
853
|
interactiveElements,
|
|
724
854
|
};
|
|
725
855
|
}
|
|
726
|
-
async collectInteractiveElements(depth) {
|
|
856
|
+
async collectInteractiveElements(depth, target, timeout) {
|
|
727
857
|
const maxDepth = Number.isInteger(depth) && depth !== undefined && depth >= 0 ? depth : 15;
|
|
728
|
-
|
|
858
|
+
await this.evaluate(`(${installDomHelpers.toString()})();`, undefined, timeout);
|
|
859
|
+
const script = `function() {
|
|
860
|
+
var root = this;
|
|
729
861
|
var maxDepth = ${maxDepth};
|
|
730
862
|
function selectorFor(el) {
|
|
731
863
|
if (!(el instanceof Element)) return '';
|
|
@@ -755,56 +887,39 @@ class SessionManager {
|
|
|
755
887
|
function depthFor(el) {
|
|
756
888
|
var depth = 0;
|
|
757
889
|
var current = el;
|
|
758
|
-
while (current.parentElement) {
|
|
890
|
+
while (current !== root && (current.parentElement || current.getRootNode().host)) {
|
|
759
891
|
depth += 1;
|
|
760
|
-
current = current.parentElement;
|
|
892
|
+
current = current.parentElement || current.getRootNode().host;
|
|
761
893
|
}
|
|
762
894
|
return depth;
|
|
763
895
|
}
|
|
764
|
-
function roleFor(el) {
|
|
765
|
-
var explicit = el.getAttribute('role');
|
|
766
|
-
if (explicit) return explicit;
|
|
767
|
-
var tag = el.tagName.toLowerCase();
|
|
768
|
-
var type = (el.getAttribute('type') || '').toLowerCase();
|
|
769
|
-
if (tag === 'button' || type === 'button' || type === 'submit' || type === 'reset') return 'button';
|
|
770
|
-
if (tag === 'a' && el.hasAttribute('href')) return 'link';
|
|
771
|
-
if (tag === 'textarea' || (tag === 'input' && !['checkbox', 'radio', 'range'].includes(type))) {
|
|
772
|
-
return 'textbox';
|
|
773
|
-
}
|
|
774
|
-
if (type === 'checkbox') return 'checkbox';
|
|
775
|
-
if (type === 'radio') return 'radio';
|
|
776
|
-
if (tag === 'select') return 'combobox';
|
|
777
|
-
if (type === 'range') return 'slider';
|
|
778
|
-
if (el.isContentEditable) return 'textbox';
|
|
779
|
-
return tag;
|
|
780
|
-
}
|
|
781
|
-
function nameFor(el) {
|
|
782
|
-
return (
|
|
783
|
-
el.getAttribute('aria-label') ||
|
|
784
|
-
el.getAttribute('title') ||
|
|
785
|
-
el.getAttribute('placeholder') ||
|
|
786
|
-
el.textContent ||
|
|
787
|
-
''
|
|
788
|
-
).replace(/\\s+/g, ' ').trim().slice(0, 160);
|
|
789
|
-
}
|
|
790
896
|
var selector = [
|
|
791
897
|
'button,a[href],input,textarea,select,[role]',
|
|
792
898
|
'[contenteditable="true"],[tabindex]:not([tabindex="-1"])'
|
|
793
899
|
].join(',');
|
|
794
|
-
|
|
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) {
|
|
795
903
|
return depthFor(el) <= maxDepth;
|
|
796
904
|
}).slice(0, 100).map(function(el, index) {
|
|
797
905
|
var rect = el.getBoundingClientRect();
|
|
798
906
|
var cx = rect.left + rect.width / 2;
|
|
799
907
|
var cy = rect.top + rect.height / 2;
|
|
800
|
-
var top = rect.width > 0 && rect.height > 0
|
|
908
|
+
var top = rect.width > 0 && rect.height > 0
|
|
909
|
+
? globalThis.__mcpDomHelpers.deepElementFromPoint(cx, cy) : null;
|
|
801
910
|
var style = getComputedStyle(el);
|
|
802
911
|
var visible = rect.width > 0 && rect.height > 0 &&
|
|
803
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;
|
|
804
917
|
return {
|
|
805
918
|
refId: 'cdp-' + index,
|
|
806
|
-
role:
|
|
807
|
-
name:
|
|
919
|
+
role: globalThis.__mcpDomHelpers.role(el),
|
|
920
|
+
name: name,
|
|
921
|
+
...(type !== undefined ? {type: type} : {}),
|
|
922
|
+
...(value !== undefined ? {value: value} : {}),
|
|
808
923
|
selector: selectorFor(el),
|
|
809
924
|
visible: visible,
|
|
810
925
|
disabled: Boolean(el.disabled) || el.getAttribute('aria-disabled') === 'true',
|
|
@@ -813,7 +928,20 @@ class SessionManager {
|
|
|
813
928
|
frameId: 0
|
|
814
929
|
};
|
|
815
930
|
});
|
|
816
|
-
}
|
|
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);
|
|
817
945
|
}
|
|
818
946
|
async getFrames() {
|
|
819
947
|
this.ensureSession();
|
|
@@ -841,16 +969,18 @@ class SessionManager {
|
|
|
841
969
|
}
|
|
842
970
|
/** CDP 通过 evaluate 注入函数枚举 IMG */
|
|
843
971
|
async getHtmlWithImages(selector, outer = true) {
|
|
972
|
+
await this.evaluate(`(${installDomHelpers.toString()})();`);
|
|
844
973
|
const selectorArg = JSON.stringify(selector ?? null);
|
|
845
974
|
return this.evaluate(`(function() {
|
|
846
|
-
var root = ${selectorArg}
|
|
975
|
+
var root = ${selectorArg}
|
|
976
|
+
? globalThis.__mcpDomHelpers.query({selector:${selectorArg}})[0] : document.documentElement;
|
|
847
977
|
if (!root) return {html: '', images: []};
|
|
848
978
|
var html = ${selectorArg}
|
|
849
979
|
? (${outer} ? root.outerHTML : root.innerHTML)
|
|
850
980
|
: document.documentElement.outerHTML;
|
|
851
981
|
var imgList = [];
|
|
852
982
|
if (root.tagName === 'IMG') imgList.push(root);
|
|
853
|
-
|
|
983
|
+
globalThis.__mcpDomHelpers.query({selector:'img'},root).forEach(function(img) { imgList.push(img); });
|
|
854
984
|
var images = [];
|
|
855
985
|
for (var i = 0; i < imgList.length; i++) {
|
|
856
986
|
var img = imgList[i];
|
|
@@ -912,54 +1042,24 @@ class SessionManager {
|
|
|
912
1042
|
}
|
|
913
1043
|
// ==================== IBrowserDriver: 元素查找 ====================
|
|
914
1044
|
/** CDP 通过 evaluate 注入 TreeWalker 查找元素 */
|
|
915
|
-
async find(selector, text, xpath, timeout) {
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
NodeFilter.SHOW_ELEMENT,
|
|
934
|
-
{
|
|
935
|
-
acceptNode: function (n) {
|
|
936
|
-
var t = n.textContent || '';
|
|
937
|
-
if (!t.includes(lowerText)) return NodeFilter.FILTER_SKIP;
|
|
938
|
-
return NodeFilter.FILTER_ACCEPT;
|
|
939
|
-
}
|
|
940
|
-
});
|
|
941
|
-
while (walker.nextNode()) {
|
|
942
|
-
elements.push(walker.currentNode);
|
|
943
|
-
if (elements.length >= 200) break;
|
|
944
|
-
}
|
|
945
|
-
} else {
|
|
946
|
-
elements = Array.from(document.querySelectorAll('*'));
|
|
947
|
-
}
|
|
948
|
-
var results = [];
|
|
949
|
-
for (var j = 0; j < elements.length; j++) {
|
|
950
|
-
var el = elements[j];
|
|
951
|
-
if (text && !(el.textContent || '').includes(text)) continue;
|
|
952
|
-
var rect = el.getBoundingClientRect();
|
|
953
|
-
results.push({
|
|
954
|
-
refId: '',
|
|
955
|
-
tag: el.tagName.toLowerCase(),
|
|
956
|
-
text: (el.textContent || '').trim().substring(0, 100),
|
|
957
|
-
rect: {x: rect.x, y: rect.y, width: rect.width, height: rect.height}
|
|
958
|
-
});
|
|
959
|
-
if (results.length >= 50) break;
|
|
960
|
-
}
|
|
961
|
-
return results;
|
|
962
|
-
}`, [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);
|
|
963
1063
|
}
|
|
964
1064
|
// ==================== IBrowserDriver: 元素操作(refId 类,CDP 不支持) ====================
|
|
965
1065
|
click(_refId) {
|
|
@@ -994,7 +1094,11 @@ class SessionManager {
|
|
|
994
1094
|
if (!selector) {
|
|
995
1095
|
throw new DriverCapabilityError('getAttribute 需要 selector');
|
|
996
1096
|
}
|
|
997
|
-
|
|
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]);
|
|
998
1102
|
}
|
|
999
1103
|
// ==================== IBrowserDriver: 输入(precise) ====================
|
|
1000
1104
|
/** CDP 通用 inputKey 接口实现:直接转发 Input.dispatchKeyEvent,不维护 modifiers(由调用方提供) */
|
|
@@ -1167,10 +1271,10 @@ class SessionManager {
|
|
|
1167
1271
|
return this.currentTargetId;
|
|
1168
1272
|
}
|
|
1169
1273
|
async deselectPage(timeout) {
|
|
1170
|
-
const
|
|
1274
|
+
const sid = this.sessionId;
|
|
1171
1275
|
try {
|
|
1172
|
-
if (
|
|
1173
|
-
await this.cdp.send('Target.detachFromTarget', { sessionId:
|
|
1276
|
+
if (sid && this.cdp?.isConnected && !this.eventControllers.has(sid)) {
|
|
1277
|
+
await this.cdp.send('Target.detachFromTarget', { sessionId: sid }, undefined, timeout);
|
|
1174
1278
|
}
|
|
1175
1279
|
}
|
|
1176
1280
|
finally {
|
|
@@ -1218,21 +1322,288 @@ class SessionManager {
|
|
|
1218
1322
|
throw new DriverCapabilityError('CDP 模式不支持同步切换 target,请用 selectPage(targetId) 或 attachToTarget(targetId)');
|
|
1219
1323
|
}
|
|
1220
1324
|
}
|
|
1221
|
-
// ==================== IBrowserDriver:
|
|
1222
|
-
resolveFrame(
|
|
1223
|
-
|
|
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
|
+
}
|
|
1224
1545
|
}
|
|
1225
1546
|
getCurrentFrameId() {
|
|
1226
|
-
|
|
1227
|
-
return 0;
|
|
1547
|
+
return this.selectedFrame;
|
|
1228
1548
|
}
|
|
1229
1549
|
setCurrentFrameId(frameId) {
|
|
1230
|
-
if (frameId !==
|
|
1231
|
-
throw new DriverCapabilityError('
|
|
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');
|
|
1559
|
+
}
|
|
1560
|
+
return this.cdp.send('Runtime.evaluate', { expression, contextId: frame.contextId, returnByValue: true, awaitPromise: true, timeout }, frame.sessionId, timeout);
|
|
1561
|
+
}
|
|
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);
|
|
1232
1594
|
}
|
|
1233
1595
|
}
|
|
1234
|
-
|
|
1235
|
-
|
|
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');
|
|
1236
1607
|
}
|
|
1237
1608
|
// ==================== IBrowserDriver: CDP 直通 ====================
|
|
1238
1609
|
/**
|
|
@@ -1241,6 +1612,10 @@ class SessionManager {
|
|
|
1241
1612
|
* browser-level 域(Target/Browser/SystemInfo/DeviceAccess/IO)走 sendBrowserCommand
|
|
1242
1613
|
*/
|
|
1243
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
|
+
}
|
|
1244
1619
|
const domain = method.split('.')[0];
|
|
1245
1620
|
const browserLevelDomains = ['Target', 'Browser', 'SystemInfo', 'DeviceAccess', 'IO'];
|
|
1246
1621
|
if (browserLevelDomains.includes(domain)) {
|
|
@@ -1270,13 +1645,38 @@ class SessionManager {
|
|
|
1270
1645
|
* 获取 Cookies
|
|
1271
1646
|
*/
|
|
1272
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
|
+
}
|
|
1273
1651
|
this.ensureSession();
|
|
1274
1652
|
const urls = filter?.url ? [filter.url] : undefined;
|
|
1275
|
-
const
|
|
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 } : {});
|
|
1276
1658
|
if (!filter) {
|
|
1277
1659
|
return cookies;
|
|
1278
1660
|
}
|
|
1279
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
|
+
}
|
|
1280
1680
|
if (filter.name && c.name !== filter.name) {
|
|
1281
1681
|
return false;
|
|
1282
1682
|
}
|
|
@@ -1309,7 +1709,8 @@ class SessionManager {
|
|
|
1309
1709
|
this.ensureSession();
|
|
1310
1710
|
const url = params.url ?? this.state?.url ?? 'http://localhost';
|
|
1311
1711
|
const { name, value, domain, path, httpOnly, secure, sameSite, expirationDate } = params;
|
|
1312
|
-
await this.
|
|
1712
|
+
const contextId = await this.cookieContext(params);
|
|
1713
|
+
const cookie = {
|
|
1313
1714
|
name,
|
|
1314
1715
|
value,
|
|
1315
1716
|
url,
|
|
@@ -1319,40 +1720,194 @@ class SessionManager {
|
|
|
1319
1720
|
...(secure !== undefined && { secure }),
|
|
1320
1721
|
...(sameSite !== undefined && { sameSite }),
|
|
1321
1722
|
...(expirationDate !== undefined && { expires: expirationDate }),
|
|
1322
|
-
|
|
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
|
+
}
|
|
1323
1737
|
}
|
|
1324
|
-
async deleteCookie(url, name) {
|
|
1738
|
+
async deleteCookie(url, name, scope, exact) {
|
|
1325
1739
|
this.ensureSession();
|
|
1326
|
-
const
|
|
1327
|
-
|
|
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
|
+
}
|
|
1328
1786
|
}
|
|
1329
1787
|
async clearCookies(filter) {
|
|
1330
|
-
this.ensureSession();
|
|
1331
|
-
// Driver 级护栏:必须按 URL 或域名限定范围,name 只能进一步缩小范围
|
|
1332
1788
|
if (!filter || (!filter.url && !filter.domain)) {
|
|
1333
|
-
throw new Error('clearCookies
|
|
1789
|
+
throw new Error('clearCookies requires url or domain');
|
|
1334
1790
|
}
|
|
1335
|
-
|
|
1336
|
-
const
|
|
1337
|
-
|
|
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
|
+
};
|
|
1338
1808
|
for (const cookie of cookies) {
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
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;
|
|
1343
1835
|
continue;
|
|
1344
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
|
+
}
|
|
1345
1868
|
}
|
|
1346
|
-
|
|
1347
|
-
|
|
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
|
+
});
|
|
1348
1908
|
}
|
|
1349
|
-
const protocol = cookie.secure ? 'https:' : 'http:';
|
|
1350
|
-
const domain = cookie.domain.startsWith('.') ? cookie.domain.slice(1) : cookie.domain;
|
|
1351
|
-
const deleteUrl = `${protocol}//${domain}${cookie.path}`;
|
|
1352
|
-
await this.send('Network.deleteCookies', { name: cookie.name, url: deleteUrl });
|
|
1353
|
-
count++;
|
|
1354
1909
|
}
|
|
1355
|
-
return
|
|
1910
|
+
return progress;
|
|
1356
1911
|
}
|
|
1357
1912
|
async getConsoleLogs(options = {}) {
|
|
1358
1913
|
let logs = this.consoleLogs;
|
|
@@ -1381,7 +1936,6 @@ class SessionManager {
|
|
|
1381
1936
|
const result = requests;
|
|
1382
1937
|
if (clear) {
|
|
1383
1938
|
this.networkRequests = [];
|
|
1384
|
-
this.requestMap.clear();
|
|
1385
1939
|
}
|
|
1386
1940
|
return result;
|
|
1387
1941
|
}
|
|
@@ -1394,12 +1948,11 @@ class SessionManager {
|
|
|
1394
1948
|
clearLogs() {
|
|
1395
1949
|
this.consoleLogs = [];
|
|
1396
1950
|
this.networkRequests = [];
|
|
1397
|
-
this.requestMap.clear();
|
|
1398
1951
|
}
|
|
1399
1952
|
/**
|
|
1400
1953
|
* 执行 JavaScript
|
|
1401
1954
|
*/
|
|
1402
|
-
async evaluate(script, args, timeout) {
|
|
1955
|
+
async evaluate(script, args, timeout, userAction) {
|
|
1403
1956
|
this.ensureSession();
|
|
1404
1957
|
// CDP 命令超时需大于脚本执行超时,给 WebSocket 通信留余量
|
|
1405
1958
|
const CDP_MARGIN = 5000;
|
|
@@ -1421,9 +1974,9 @@ class SessionManager {
|
|
|
1421
1974
|
if (timeout !== undefined) {
|
|
1422
1975
|
callParams.timeout = timeout;
|
|
1423
1976
|
}
|
|
1424
|
-
const { result, exceptionDetails } = (await this.send('Runtime.callFunctionOn', callParams, sendTimeout));
|
|
1977
|
+
const { result, exceptionDetails } = (await this.send('Runtime.callFunctionOn', callParams, sendTimeout, userAction));
|
|
1425
1978
|
if (exceptionDetails) {
|
|
1426
|
-
throw new Error(formatCdpException(exceptionDetails));
|
|
1979
|
+
throw setErrorSource(new Error(formatCdpException(exceptionDetails)), 'page');
|
|
1427
1980
|
}
|
|
1428
1981
|
return extractCdpValue(result);
|
|
1429
1982
|
}
|
|
@@ -1439,9 +1992,9 @@ class SessionManager {
|
|
|
1439
1992
|
if (timeout !== undefined) {
|
|
1440
1993
|
evalParams.timeout = timeout;
|
|
1441
1994
|
}
|
|
1442
|
-
const { result, exceptionDetails } = (await this.send('Runtime.evaluate', evalParams, sendTimeout));
|
|
1995
|
+
const { result, exceptionDetails } = (await this.send('Runtime.evaluate', evalParams, sendTimeout, userAction));
|
|
1443
1996
|
if (exceptionDetails) {
|
|
1444
|
-
throw new Error(formatCdpException(exceptionDetails));
|
|
1997
|
+
throw setErrorSource(new Error(formatCdpException(exceptionDetails)), 'page');
|
|
1445
1998
|
}
|
|
1446
1999
|
return extractCdpValue(result);
|
|
1447
2000
|
}
|
|
@@ -1471,16 +2024,25 @@ class SessionManager {
|
|
|
1471
2024
|
*/
|
|
1472
2025
|
async clearCache(type = 'all') {
|
|
1473
2026
|
this.ensureSession();
|
|
2027
|
+
if (type !== 'cache') {
|
|
2028
|
+
this.ensureEventController(this.currentTargetId, this.sessionId).assertNativeReady();
|
|
2029
|
+
}
|
|
1474
2030
|
if (type === 'all' || type === 'cache') {
|
|
1475
2031
|
await this.send('Network.clearBrowserCache');
|
|
1476
2032
|
}
|
|
1477
2033
|
if (type === 'all' || type === 'storage') {
|
|
1478
|
-
await this.send('Runtime.evaluate', {
|
|
1479
|
-
expression: `
|
|
1480
|
-
localStorage.clear();
|
|
1481
|
-
sessionStorage.clear();
|
|
1482
|
-
`,
|
|
2034
|
+
const result = await this.send('Runtime.evaluate', {
|
|
2035
|
+
expression: `localStorage.clear(); sessionStorage.clear();`,
|
|
1483
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
|
+
}
|
|
1484
2046
|
}
|
|
1485
2047
|
}
|
|
1486
2048
|
/**
|
|
@@ -1489,7 +2051,7 @@ class SessionManager {
|
|
|
1489
2051
|
* IBrowserDriver 接口:可选 url 参数,url 提供时新建后立即导航
|
|
1490
2052
|
*/
|
|
1491
2053
|
async newPage(url, timeout, options = {}) {
|
|
1492
|
-
if (Object.
|
|
2054
|
+
if (Object.entries(options).some(([key, value]) => value !== undefined && key !== 'taskHint' && key !== 'note')) {
|
|
1493
2055
|
throw new DriverCapabilityError('CDP 模式不支持 Chrome UI 的 newPage 配置参数,未创建页面;请使用 Extension 模式');
|
|
1494
2056
|
}
|
|
1495
2057
|
const target = await this.withLock(async () => this.newPageInternal());
|
|
@@ -1540,7 +2102,8 @@ class SessionManager {
|
|
|
1540
2102
|
return this.withLock(async () => {
|
|
1541
2103
|
this.ensureConnected();
|
|
1542
2104
|
const targets = await this.listTargets();
|
|
1543
|
-
|
|
2105
|
+
const before = targets.find((target) => target.targetId === targetId);
|
|
2106
|
+
if (!before) {
|
|
1544
2107
|
throw new TargetNotFoundError(targetId);
|
|
1545
2108
|
}
|
|
1546
2109
|
const id = targetId;
|
|
@@ -1549,16 +2112,25 @@ class SessionManager {
|
|
|
1549
2112
|
await this.assertPageCondition(id, condition.expectedUrl, condition.expectedRevision);
|
|
1550
2113
|
this.pendingPageCondition = null;
|
|
1551
2114
|
}
|
|
2115
|
+
const sid = this.targetSessions.get(id);
|
|
2116
|
+
if (sid) {
|
|
2117
|
+
await this.eventControllers.get(sid)?.dispose('page closed');
|
|
2118
|
+
}
|
|
1552
2119
|
const result = (await this.cdp.send('Target.closeTarget', { targetId: id }));
|
|
1553
2120
|
if (!result.success) {
|
|
1554
2121
|
throw new TargetNotFoundError(targetId);
|
|
1555
2122
|
}
|
|
1556
2123
|
this.revisions.delete(id);
|
|
2124
|
+
if (sid) {
|
|
2125
|
+
this.eventControllers.delete(sid);
|
|
2126
|
+
this.targetSessions.delete(id);
|
|
2127
|
+
}
|
|
1557
2128
|
// 如果关闭的是当前页面,清除会话状态
|
|
1558
2129
|
if (id === this.currentTargetId) {
|
|
1559
2130
|
this.clearAttachedTargetState();
|
|
1560
2131
|
}
|
|
1561
2132
|
this.targetLogs.delete(id);
|
|
2133
|
+
return { targetId: id, before, after: null };
|
|
1562
2134
|
});
|
|
1563
2135
|
}
|
|
1564
2136
|
/**
|
|
@@ -1570,6 +2142,7 @@ class SessionManager {
|
|
|
1570
2142
|
* 2. 通过 withLock 串行化状态清理:等 withLock 中的操作处理完错误后再置空引用
|
|
1571
2143
|
*/
|
|
1572
2144
|
async close() {
|
|
2145
|
+
await Promise.all([...this.eventControllers.values()].map((controller) => controller.suspend('connection closing')));
|
|
1573
2146
|
// Phase 1: 立即关闭 CDP 连接(reject pending callbacks,清除 event listeners)
|
|
1574
2147
|
if (this.cdp) {
|
|
1575
2148
|
this.cdp.close();
|
|
@@ -1611,7 +2184,7 @@ class SessionManager {
|
|
|
1611
2184
|
* 多步操作(type 循环、fullPage 截图等)的 await 间隙可能被 close() 打断,
|
|
1612
2185
|
* ensureSession() 确保在当前 tick 内 this.cdp 非空
|
|
1613
2186
|
*/
|
|
1614
|
-
async send(method, params, timeout) {
|
|
2187
|
+
async send(method, params, timeout, dispatchedAction) {
|
|
1615
2188
|
const deadline = timeout === undefined ? undefined : Date.now() + timeout;
|
|
1616
2189
|
this.ensureSession();
|
|
1617
2190
|
const mutation = method === 'Page.navigate' ||
|
|
@@ -1633,10 +2206,30 @@ class SessionManager {
|
|
|
1633
2206
|
this.pendingPageCondition = null;
|
|
1634
2207
|
}
|
|
1635
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
|
+
}
|
|
1636
2215
|
if (mutation && this.currentTargetId) {
|
|
1637
2216
|
this.revisions.set(this.currentTargetId, (this.revisions.get(this.currentTargetId) ?? 0) + 1);
|
|
1638
2217
|
}
|
|
1639
|
-
|
|
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;
|
|
1640
2233
|
}
|
|
1641
2234
|
/**
|
|
1642
2235
|
* 发送 browser-level CDP 命令(不携带 sessionId)
|
|
@@ -1649,6 +2242,63 @@ class SessionManager {
|
|
|
1649
2242
|
/**
|
|
1650
2243
|
* 派发 CDP Input.dispatchTouchEvent,临时启用 touch 模拟避免命令挂起
|
|
1651
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
|
+
}
|
|
1652
2302
|
async dispatchTouch(params) {
|
|
1653
2303
|
await this.send('Emulation.setTouchEmulationEnabled', { enabled: true });
|
|
1654
2304
|
try {
|
|
@@ -1663,11 +2313,20 @@ class SessionManager {
|
|
|
1663
2313
|
}
|
|
1664
2314
|
}
|
|
1665
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
|
+
}
|
|
1666
2324
|
/** 在触发导航前注册相应等待器,并按主 frame loader 过滤生命周期事件 */
|
|
1667
2325
|
startNavigationWait(wait, timeout, signal, bindFromFrameNavigation) {
|
|
1668
2326
|
this.ensureSession();
|
|
1669
2327
|
const cdp = this.cdp;
|
|
1670
2328
|
const sessionId = this.sessionId;
|
|
2329
|
+
const deadline = Date.now() + timeout;
|
|
1671
2330
|
const baselineLoaderId = this.mainFrameLoaderId;
|
|
1672
2331
|
const lifecycleName = wait === 'domcontentloaded' ? 'DOMContentLoaded' : wait === 'load' ? 'load' : 'networkIdle';
|
|
1673
2332
|
const seenLifecycle = new Set();
|
|
@@ -1803,8 +2462,8 @@ class SessionManager {
|
|
|
1803
2462
|
if (!actionStarted || eventSessionId !== sessionId) {
|
|
1804
2463
|
return;
|
|
1805
2464
|
}
|
|
1806
|
-
const requestId = params
|
|
1807
|
-
if (requestId) {
|
|
2465
|
+
const { requestId, loaderId } = params;
|
|
2466
|
+
if (requestId && loaderId !== '') {
|
|
1808
2467
|
sameDocumentPendingRequests.add(requestId);
|
|
1809
2468
|
checkSameDocumentIdle();
|
|
1810
2469
|
}
|
|
@@ -1823,7 +2482,11 @@ class SessionManager {
|
|
|
1823
2482
|
fail(signal?.reason instanceof Error ? signal.reason : new Error('导航等待已取消'));
|
|
1824
2483
|
};
|
|
1825
2484
|
const onDisconnected = () => fail(new Error('CDP 连接已关闭'));
|
|
1826
|
-
const timeoutId = setTimeout(() =>
|
|
2485
|
+
const timeoutId = setTimeout(() => {
|
|
2486
|
+
if (!settled) {
|
|
2487
|
+
fail(this.navigationTimeout(wait, timeout, deadline));
|
|
2488
|
+
}
|
|
2489
|
+
}, timeout);
|
|
1827
2490
|
cdp.onEvent('Page.frameNavigated', onFrameNavigated);
|
|
1828
2491
|
cdp.onEvent('Page.lifecycleEvent', onLifecycleEvent);
|
|
1829
2492
|
cdp.onEvent('Page.navigatedWithinDocument', onNavigatedWithinDocument);
|
|
@@ -1854,8 +2517,10 @@ class SessionManager {
|
|
|
1854
2517
|
* close() 时通过 'disconnected' 信号立即 reject
|
|
1855
2518
|
*/
|
|
1856
2519
|
buildNetworkIdlePromise(cdp, timeout, idleTime, signal) {
|
|
1857
|
-
|
|
2520
|
+
// CDP 用空 loaderId 标识 Worker 请求,页面 session 可能只收到其开始事件
|
|
2521
|
+
const localPendingRequests = new Set([...this.requestMap].filter(([, request]) => request.loaderId !== '').map(([requestId]) => requestId));
|
|
1858
2522
|
const sessionId = this.sessionId;
|
|
2523
|
+
const deadline = Date.now() + timeout;
|
|
1859
2524
|
return new Promise((resolve, reject) => {
|
|
1860
2525
|
let idleTimer = null;
|
|
1861
2526
|
let timeoutTimer = null;
|
|
@@ -1879,7 +2544,10 @@ class SessionManager {
|
|
|
1879
2544
|
if (eventSessionId !== sessionId) {
|
|
1880
2545
|
return;
|
|
1881
2546
|
}
|
|
1882
|
-
const { requestId } = params;
|
|
2547
|
+
const { requestId, loaderId } = params;
|
|
2548
|
+
if (loaderId === '') {
|
|
2549
|
+
return;
|
|
2550
|
+
}
|
|
1883
2551
|
localPendingRequests.add(requestId);
|
|
1884
2552
|
checkIdle();
|
|
1885
2553
|
};
|
|
@@ -1910,7 +2578,7 @@ class SessionManager {
|
|
|
1910
2578
|
};
|
|
1911
2579
|
timeoutTimer = setTimeout(() => {
|
|
1912
2580
|
cleanup();
|
|
1913
|
-
reject(
|
|
2581
|
+
reject(this.navigationTimeout('networkidle', timeout, deadline));
|
|
1914
2582
|
}, timeout);
|
|
1915
2583
|
const onDisconnected = () => {
|
|
1916
2584
|
cleanup();
|
|
@@ -1937,23 +2605,16 @@ class SessionManager {
|
|
|
1937
2605
|
if (this.currentTargetId === targetId && this.sessionId) {
|
|
1938
2606
|
return;
|
|
1939
2607
|
}
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
try {
|
|
1943
|
-
await this.sendBrowserCommand('Target.detachFromTarget', {
|
|
1944
|
-
sessionId: this.sessionId,
|
|
1945
|
-
}, deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
|
|
1946
|
-
}
|
|
1947
|
-
catch {
|
|
1948
|
-
// 忽略分离错误
|
|
1949
|
-
}
|
|
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');
|
|
1950
2610
|
}
|
|
1951
2611
|
this.clearAttachedTargetState();
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
targetId,
|
|
1955
|
-
|
|
1956
|
-
|
|
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
|
+
}
|
|
1957
2618
|
this.sessionId = sessionId;
|
|
1958
2619
|
this.currentTargetId = targetId;
|
|
1959
2620
|
const logs = this.targetLogs.get(targetId);
|
|
@@ -2013,6 +2674,7 @@ class SessionManager {
|
|
|
2013
2674
|
this.mainFrameLoaderId = null;
|
|
2014
2675
|
this.modifiers = 0;
|
|
2015
2676
|
this.sessionId = null;
|
|
2677
|
+
this.selectedFrame = 0;
|
|
2016
2678
|
this.currentTargetId = null;
|
|
2017
2679
|
this.state = null;
|
|
2018
2680
|
}
|
|
@@ -2035,6 +2697,16 @@ class SessionManager {
|
|
|
2035
2697
|
this.launcher = null;
|
|
2036
2698
|
}
|
|
2037
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;
|
|
2038
2710
|
this.targetLogs.clear();
|
|
2039
2711
|
this.revisionEpoch = randomUUID();
|
|
2040
2712
|
this.revisions.clear();
|
|
@@ -2047,6 +2719,8 @@ class SessionManager {
|
|
|
2047
2719
|
* 串行执行操作(防止并发竞态)
|
|
2048
2720
|
*/
|
|
2049
2721
|
async withLock(fn, deadline) {
|
|
2722
|
+
const signal = this.requestContext?.()?.signal;
|
|
2723
|
+
signal?.throwIfAborted();
|
|
2050
2724
|
const previousLock = this.operationLock;
|
|
2051
2725
|
let releaseLock;
|
|
2052
2726
|
this.operationLock = new Promise((resolve) => {
|
|
@@ -2054,8 +2728,9 @@ class SessionManager {
|
|
|
2054
2728
|
});
|
|
2055
2729
|
let acquired = false;
|
|
2056
2730
|
try {
|
|
2057
|
-
await waitForNavigationQueue(previousLock, deadline);
|
|
2731
|
+
await waitForNavigationQueue(previousLock, deadline, signal);
|
|
2058
2732
|
acquired = true;
|
|
2733
|
+
signal?.throwIfAborted();
|
|
2059
2734
|
return await fn();
|
|
2060
2735
|
}
|
|
2061
2736
|
catch (error) {
|
|
@@ -2086,7 +2761,9 @@ class SessionManager {
|
|
|
2086
2761
|
* 接受完成事件后清理所有监听器和超时定时器
|
|
2087
2762
|
* close() 时通过 'disconnected' 信号立即 reject,不必等 timer 超时
|
|
2088
2763
|
*/
|
|
2089
|
-
waitForAnyEvent(events, timeout) {
|
|
2764
|
+
waitForAnyEvent(events, timeout, signal = this.requestContext?.()?.signal) {
|
|
2765
|
+
const deadline = Date.now() + timeout;
|
|
2766
|
+
signal?.throwIfAborted();
|
|
2090
2767
|
// 捕获当前 cdp 引用,防止 close() 并发置 null 导致回调崩溃
|
|
2091
2768
|
const cdp = this.cdp;
|
|
2092
2769
|
const sessionId = this.sessionId;
|
|
@@ -2097,20 +2774,30 @@ class SessionManager {
|
|
|
2097
2774
|
const listeners = [];
|
|
2098
2775
|
const cleanup = () => {
|
|
2099
2776
|
clearTimeout(timer);
|
|
2777
|
+
signal?.removeEventListener('abort', onAbort);
|
|
2100
2778
|
for (const { event, listener } of listeners) {
|
|
2101
2779
|
cdp.offEvent(event, listener);
|
|
2102
2780
|
}
|
|
2103
2781
|
cdp.removeListener('disconnected', onDisconnected);
|
|
2104
2782
|
};
|
|
2783
|
+
const onAbort = () => {
|
|
2784
|
+
cleanup();
|
|
2785
|
+
reject(signal?.reason ?? new Error('Request cancelled'));
|
|
2786
|
+
};
|
|
2105
2787
|
const timer = setTimeout(() => {
|
|
2106
2788
|
cleanup();
|
|
2107
|
-
reject(
|
|
2789
|
+
reject(this.navigationTimeout('navigation', timeout, deadline));
|
|
2108
2790
|
}, timeout);
|
|
2109
2791
|
const onDisconnected = () => {
|
|
2110
2792
|
cleanup();
|
|
2111
2793
|
reject(new Error('CDP 连接已关闭'));
|
|
2112
2794
|
};
|
|
2113
2795
|
cdp.once('disconnected', onDisconnected);
|
|
2796
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
2797
|
+
if (signal?.aborted) {
|
|
2798
|
+
onAbort();
|
|
2799
|
+
return;
|
|
2800
|
+
}
|
|
2114
2801
|
for (const event of events) {
|
|
2115
2802
|
const listener = (params, eventSessionId) => {
|
|
2116
2803
|
if (eventSessionId !== sessionId) {
|
|
@@ -2141,6 +2828,8 @@ class SessionManager {
|
|
|
2141
2828
|
*/
|
|
2142
2829
|
async initSession(deadline) {
|
|
2143
2830
|
const remaining = () => (deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
|
|
2831
|
+
this.setupEventListeners();
|
|
2832
|
+
this.ensureEventController(this.currentTargetId, this.sessionId);
|
|
2144
2833
|
// 启用必要的域
|
|
2145
2834
|
await Promise.all([
|
|
2146
2835
|
this.send('Page.enable', undefined, remaining()),
|
|
@@ -2172,22 +2861,94 @@ class SessionManager {
|
|
|
2172
2861
|
return;
|
|
2173
2862
|
}
|
|
2174
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
|
+
});
|
|
2175
2934
|
this.cdp.onEvent('Page.frameNavigated', (params, eventSessionId) => {
|
|
2176
|
-
|
|
2935
|
+
const targetId = [...this.targetSessions].find(([, sid]) => sid === eventSessionId)?.[0];
|
|
2936
|
+
if (!targetId) {
|
|
2177
2937
|
return;
|
|
2178
2938
|
}
|
|
2179
2939
|
const frame = params.frame;
|
|
2180
2940
|
if (frame?.id && !frame.parentId) {
|
|
2181
|
-
this.
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
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;
|
|
2185
2944
|
}
|
|
2945
|
+
this.revisions.set(targetId, (this.revisions.get(targetId) ?? 0) + 1);
|
|
2186
2946
|
}
|
|
2187
2947
|
});
|
|
2188
2948
|
this.cdp.onEvent('Page.navigatedWithinDocument', (_params, eventSessionId) => {
|
|
2189
|
-
|
|
2190
|
-
|
|
2949
|
+
const targetId = [...this.targetSessions].find(([, sid]) => sid === eventSessionId)?.[0];
|
|
2950
|
+
if (targetId) {
|
|
2951
|
+
this.revisions.set(targetId, (this.revisions.get(targetId) ?? 0) + 1);
|
|
2191
2952
|
}
|
|
2192
2953
|
});
|
|
2193
2954
|
// 控制台日志
|
|
@@ -2209,6 +2970,24 @@ class SessionManager {
|
|
|
2209
2970
|
this.consoleLogs.splice(0, this.consoleLogs.length - 800);
|
|
2210
2971
|
}
|
|
2211
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
|
+
});
|
|
2212
2991
|
// 网络请求
|
|
2213
2992
|
this.cdp.onEvent('Network.requestWillBeSent', (params, eventSessionId) => {
|
|
2214
2993
|
if (!this.isCurrentSessionEvent(eventSessionId)) {
|
|
@@ -2221,6 +3000,7 @@ class SessionManager {
|
|
|
2221
3000
|
type: p.type,
|
|
2222
3001
|
timestamp: Math.round(p.wallTime * 1000), // wallTime 是 epoch 秒 → epoch 毫秒
|
|
2223
3002
|
frameId: p.frameId,
|
|
3003
|
+
loaderId: p.loaderId,
|
|
2224
3004
|
_monotonic: p.timestamp, // MonotonicTime 用于 duration 计算
|
|
2225
3005
|
});
|
|
2226
3006
|
});
|
|
@@ -2250,6 +3030,7 @@ class SessionManager {
|
|
|
2250
3030
|
if (request) {
|
|
2251
3031
|
const { _monotonic, ...requestData } = request;
|
|
2252
3032
|
delete requestData.frameId;
|
|
3033
|
+
delete requestData.loaderId;
|
|
2253
3034
|
this.networkRequests.push({
|
|
2254
3035
|
sequence: ++this.nextNetworkRequestSequence,
|
|
2255
3036
|
...requestData,
|