@pyrokine/mcp-chrome 3.0.1 → 3.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1060 -432
- package/README_zh.md +936 -349
- package/dist/cdp/client.d.ts +8 -3
- package/dist/cdp/client.d.ts.map +1 -1
- package/dist/cdp/client.js +260 -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 +73 -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 +105 -0
- package/dist/core/browser-events.d.ts.map +1 -0
- package/dist/core/browser-events.js +1482 -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 +231 -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/error-sanitizer.d.ts.map +1 -1
- package/dist/core/error-sanitizer.js +2 -1
- package/dist/core/error-sanitizer.js.map +1 -1
- package/dist/core/errors.d.ts +4 -0
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/errors.js +57 -9
- 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 +11 -2
- package/dist/core/locator.d.ts.map +1 -1
- package/dist/core/locator.js +135 -206
- 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 +104 -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 +62 -12
- package/dist/core/session.d.ts.map +1 -1
- package/dist/core/session.js +1174 -304
- 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 +48 -37
- package/dist/core/unified-session.d.ts.map +1 -1
- package/dist/core/unified-session.js +982 -294
- package/dist/core/unified-session.js.map +1 -1
- package/dist/core/utils.d.ts +8 -4
- package/dist/core/utils.d.ts.map +1 -1
- package/dist/core/utils.js +76 -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 +288 -46
- package/dist/extension/bridge.js.map +1 -1
- package/dist/extension/http-server.d.ts +8 -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 +15 -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 +18 -5
- package/dist/tools/challenge.d.ts.map +1 -1
- package/dist/tools/challenge.js +217 -200
- package/dist/tools/challenge.js.map +1 -1
- package/dist/tools/cookies.d.ts.map +1 -1
- package/dist/tools/cookies.js +34 -8
- package/dist/tools/cookies.js.map +1 -1
- package/dist/tools/diagnostics.d.ts.map +1 -1
- package/dist/tools/diagnostics.js +15 -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 +94 -52
- package/dist/tools/evaluate.js.map +1 -1
- package/dist/tools/extract.d.ts.map +1 -1
- package/dist/tools/extract.js +293 -153
- package/dist/tools/extract.js.map +1 -1
- package/dist/tools/input.d.ts.map +1 -1
- package/dist/tools/input.js +747 -282
- 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 +123 -18
- package/dist/tools/manage.js.map +1 -1
- package/dist/tools/network-sanitizer.d.ts +2 -0
- package/dist/tools/network-sanitizer.d.ts.map +1 -1
- package/dist/tools/network-sanitizer.js +53 -10
- 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 +57 -14
- package/dist/tools/page-context.js.map +1 -1
- package/dist/tools/png.d.ts.map +1 -1
- package/dist/tools/png.js +12 -3
- package/dist/tools/png.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 +163 -47
- 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 +64 -34
- 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-C9QgtUYe.js} +1 -1
- package/extension/dist/assets/{content.ts-loader-DUWbDHRS.js → content.ts-loader-yqB_P8vu.js} +1 -1
- package/extension/dist/assets/index.ts-DBFNh8mZ.js +20275 -0
- package/extension/dist/assets/{page-scripts-D508WLkW.js → page-scripts-BjqQ0zXt.js} +258 -367
- 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 +9 -7
- package/scripts/start-chrome.ps1 +9 -1
- package/extension/dist/assets/index.ts-D7_LCUoV.js +0 -9319
package/dist/core/session.js
CHANGED
|
@@ -9,14 +9,17 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { randomUUID } from 'node:crypto';
|
|
11
11
|
import { BehaviorSimulator, getAntiDetectionScript } from '../anti-detection/index.js';
|
|
12
|
-
import { assertScreenshotBase64Budget, assertScreenshotBudget } from '../tools/png.js';
|
|
13
12
|
import { BrowserLauncher, CDPClient, getBrowserWSEndpoint, getTargets } from '../cdp/index.js';
|
|
13
|
+
import { assertScreenshotBase64Budget, assertScreenshotBudget } from '../tools/png.js';
|
|
14
14
|
import { AutoWait } from './auto-wait.js';
|
|
15
15
|
import { DriverCapabilityError, } from './browser-driver.js';
|
|
16
|
-
import {
|
|
16
|
+
import { browserEventCommandSchema } from './browser-event-schema.js';
|
|
17
|
+
import { BROWSER_EVENT_METHODS, BrowserEventController, eventRefTarget, } from './browser-events.js';
|
|
18
|
+
import { installDomHelpers } from './dom-helpers.js';
|
|
19
|
+
import { CDPError, creationError, ElementNotFoundError, formatErrorResponse, NavigationError, NavigationTimeoutError, PagePreconditionError, SessionNotFoundError, setErrorSource, StructuredToolError, TargetNotFoundError, TimeoutError, } from './errors.js';
|
|
17
20
|
import { Locator } from './locator.js';
|
|
18
21
|
import { DEFAULT_TIMEOUT, extractCdpValue, formatCdpException, MODIFIER_KEYS, } from './types.js';
|
|
19
|
-
import { remainingNavigationTimeout, waitForNavigationQueue, withNavigationBudget } from './utils.js';
|
|
22
|
+
import { remainingNavigationTimeout, waitForNavigationQueue, withNavigationBudget, withNavigationMetadata, } from './utils.js';
|
|
20
23
|
function wildcardSegmentMatches(value, segment, index) {
|
|
21
24
|
if (index + segment.length > value.length) {
|
|
22
25
|
return false;
|
|
@@ -70,6 +73,7 @@ class SessionManager {
|
|
|
70
73
|
static instance;
|
|
71
74
|
// 日志收集(环形缓冲区,限制最大条数避免内存泄漏)
|
|
72
75
|
static MAX_LOG_ENTRIES = 1000;
|
|
76
|
+
requestContext;
|
|
73
77
|
launcher = null;
|
|
74
78
|
cdp = null;
|
|
75
79
|
connectedPort = 0;
|
|
@@ -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,67 +223,113 @@ 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
|
+
// noinspection ExceptionCaughtLocallyJS -- 外层关闭本次创建的 client 与 launcher
|
|
262
|
+
throw new Error('未找到页面');
|
|
263
|
+
}
|
|
264
|
+
// 附加到页面
|
|
265
|
+
await this.attachToTargetInternal(pageTarget.id, deadline);
|
|
266
|
+
remaining();
|
|
267
|
+
return {
|
|
268
|
+
targetId: pageTarget.id,
|
|
269
|
+
type: pageTarget.type,
|
|
270
|
+
url: pageTarget.url,
|
|
271
|
+
title: pageTarget.title,
|
|
272
|
+
};
|
|
183
273
|
}
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
274
|
+
catch (error) {
|
|
275
|
+
client?.close();
|
|
276
|
+
if (this.cdp === client) {
|
|
277
|
+
this.cdp = null;
|
|
278
|
+
}
|
|
279
|
+
launcher.close();
|
|
280
|
+
if (this.launcher === launcher) {
|
|
281
|
+
this.launcher = null;
|
|
282
|
+
}
|
|
283
|
+
throw error;
|
|
284
|
+
}
|
|
285
|
+
}, deadline);
|
|
193
286
|
}
|
|
194
287
|
/**
|
|
195
288
|
* 连接到已运行的浏览器
|
|
196
289
|
*/
|
|
197
290
|
async connect(options) {
|
|
291
|
+
const { host = '127.0.0.1', port, timeout = DEFAULT_TIMEOUT, stealth = 'safe' } = options;
|
|
292
|
+
const scope = this.requestContext?.();
|
|
293
|
+
const signal = scope?.signal;
|
|
294
|
+
const deadline = Math.min(Date.now() + timeout, scope?.deadline ?? Infinity);
|
|
295
|
+
const remaining = () => {
|
|
296
|
+
signal?.throwIfAborted();
|
|
297
|
+
return remainingNavigationTimeout(deadline);
|
|
298
|
+
};
|
|
299
|
+
remaining();
|
|
198
300
|
return this.withLock(async () => {
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
// 连接 CDP
|
|
207
|
-
this.cdp = new CDPClient();
|
|
208
|
-
await this.cdp.connect(endpoint, timeout);
|
|
209
|
-
this.connectedPort = port;
|
|
210
|
-
// 获取第一个页面
|
|
211
|
-
const targets = await getTargets(host, port);
|
|
212
|
-
const pageTarget = targets.find((t) => t.type === 'page');
|
|
301
|
+
const endpoint = await getBrowserWSEndpoint(host, port, remaining(), signal);
|
|
302
|
+
const targets = await getTargets(host, port, remaining(), signal);
|
|
303
|
+
remaining();
|
|
304
|
+
const reused = this.cdp?.isConnected === true && this.cdp.endpoint === endpoint;
|
|
305
|
+
const pageTarget = (reused
|
|
306
|
+
? targets.find((target) => target.id === this.currentTargetId && target.type === 'page')
|
|
307
|
+
: undefined) ?? targets.find((target) => target.type === 'page');
|
|
213
308
|
if (!pageTarget) {
|
|
214
309
|
throw new Error('未找到页面');
|
|
215
310
|
}
|
|
216
|
-
|
|
217
|
-
|
|
311
|
+
const stealthChanged = this.stealthMode !== stealth;
|
|
312
|
+
if (!reused) {
|
|
313
|
+
this.resetState();
|
|
314
|
+
this.cdp = new CDPClient(() => this.requestContext?.());
|
|
315
|
+
await this.cdp.connect(endpoint, remaining());
|
|
316
|
+
this.connectedPort = port;
|
|
317
|
+
}
|
|
318
|
+
this.stealthMode = stealth;
|
|
319
|
+
if (reused && this.currentTargetId === pageTarget.id && this.sessionId && stealthChanged) {
|
|
320
|
+
await this.initSession(deadline);
|
|
321
|
+
}
|
|
322
|
+
else {
|
|
323
|
+
await this.attachToTargetInternal(pageTarget.id, deadline);
|
|
324
|
+
}
|
|
325
|
+
remaining();
|
|
218
326
|
return {
|
|
219
327
|
targetId: pageTarget.id,
|
|
220
328
|
type: pageTarget.type,
|
|
221
329
|
url: pageTarget.url,
|
|
222
330
|
title: pageTarget.title,
|
|
223
331
|
};
|
|
224
|
-
});
|
|
332
|
+
}, deadline);
|
|
225
333
|
}
|
|
226
334
|
/**
|
|
227
335
|
* 列出所有可用页面
|
|
@@ -262,12 +370,15 @@ class SessionManager {
|
|
|
262
370
|
this.ensureSession();
|
|
263
371
|
const { wait = 'load' } = options;
|
|
264
372
|
const abortController = new AbortController();
|
|
265
|
-
const
|
|
373
|
+
const requestSignal = this.requestContext?.()?.signal;
|
|
374
|
+
requestSignal?.throwIfAborted();
|
|
375
|
+
const navigationWait = this.startNavigationWait(wait, remainingNavigationTimeout(deadline), requestSignal ? AbortSignal.any([abortController.signal, requestSignal]) : abortController.signal, false);
|
|
266
376
|
navigationWait.promise.catch(() => { });
|
|
267
377
|
navigationWait.markActionStarted();
|
|
268
378
|
try {
|
|
269
379
|
const { frameId, loaderId, errorText } = (await this.send('Page.navigate', { url }, remainingNavigationTimeout(deadline)));
|
|
270
380
|
if (errorText) {
|
|
381
|
+
// noinspection ExceptionCaughtLocallyJS -- Report failure
|
|
271
382
|
throw new NavigationError(url, errorText);
|
|
272
383
|
}
|
|
273
384
|
if (loaderId) {
|
|
@@ -282,7 +393,7 @@ class SessionManager {
|
|
|
282
393
|
throw error;
|
|
283
394
|
}
|
|
284
395
|
await navigationWait.promise;
|
|
285
|
-
await this.updateState(remainingNavigationTimeout(deadline));
|
|
396
|
+
await withNavigationMetadata(() => this.updateState(remainingNavigationTimeout(deadline)));
|
|
286
397
|
}, deadline);
|
|
287
398
|
}
|
|
288
399
|
/**
|
|
@@ -292,7 +403,7 @@ class SessionManager {
|
|
|
292
403
|
*/
|
|
293
404
|
async waitForNetworkIdle(timeout, idleTime = 500) {
|
|
294
405
|
this.ensureSession();
|
|
295
|
-
return this.buildNetworkIdlePromise(this.cdp, timeout, idleTime);
|
|
406
|
+
return this.buildNetworkIdlePromise(this.cdp, timeout, idleTime, this.requestContext?.()?.signal);
|
|
296
407
|
}
|
|
297
408
|
/**
|
|
298
409
|
* 等待导航完成(跨文档导航或同文档导航)
|
|
@@ -312,14 +423,21 @@ class SessionManager {
|
|
|
312
423
|
if (currentIndex <= 0) {
|
|
313
424
|
return { navigated: false };
|
|
314
425
|
}
|
|
426
|
+
const abortController = new AbortController();
|
|
427
|
+
const requestSignal = this.requestContext?.()?.signal;
|
|
315
428
|
// 跨文档加载、主 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 默认会退出进程)
|
|
429
|
+
const waitPromise = this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument', 'Page.frameNavigated'], remainingNavigationTimeout(deadline), requestSignal ? AbortSignal.any([abortController.signal, requestSignal]) : abortController.signal);
|
|
430
|
+
// 预注册 rejection handler,发送失败时局部取消也会使等待 Promise reject
|
|
319
431
|
waitPromise.catch(() => { });
|
|
320
|
-
|
|
432
|
+
try {
|
|
433
|
+
await this.send('Page.navigateToHistoryEntry', { entryId: entries[currentIndex - 1].id }, remainingNavigationTimeout(deadline));
|
|
434
|
+
}
|
|
435
|
+
catch (error) {
|
|
436
|
+
abortController.abort(error);
|
|
437
|
+
throw error;
|
|
438
|
+
}
|
|
321
439
|
await waitPromise;
|
|
322
|
-
await this.updateState(remainingNavigationTimeout(deadline));
|
|
440
|
+
await withNavigationMetadata(() => this.updateState(remainingNavigationTimeout(deadline)));
|
|
323
441
|
return { navigated: true };
|
|
324
442
|
}, deadline);
|
|
325
443
|
}
|
|
@@ -334,12 +452,20 @@ class SessionManager {
|
|
|
334
452
|
if (currentIndex >= entries.length - 1) {
|
|
335
453
|
return { navigated: false };
|
|
336
454
|
}
|
|
455
|
+
const abortController = new AbortController();
|
|
456
|
+
const requestSignal = this.requestContext?.()?.signal;
|
|
337
457
|
// 跨文档加载、主 frame BFCache 恢复和同文档导航分别提供完成事件
|
|
338
|
-
const waitPromise = this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument', 'Page.frameNavigated'], remainingNavigationTimeout(deadline));
|
|
458
|
+
const waitPromise = this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument', 'Page.frameNavigated'], remainingNavigationTimeout(deadline), requestSignal ? AbortSignal.any([abortController.signal, requestSignal]) : abortController.signal);
|
|
339
459
|
waitPromise.catch(() => { });
|
|
340
|
-
|
|
460
|
+
try {
|
|
461
|
+
await this.send('Page.navigateToHistoryEntry', { entryId: entries[currentIndex + 1].id }, remainingNavigationTimeout(deadline));
|
|
462
|
+
}
|
|
463
|
+
catch (error) {
|
|
464
|
+
abortController.abort(error);
|
|
465
|
+
throw error;
|
|
466
|
+
}
|
|
341
467
|
await waitPromise;
|
|
342
|
-
await this.updateState(remainingNavigationTimeout(deadline));
|
|
468
|
+
await withNavigationMetadata(() => this.updateState(remainingNavigationTimeout(deadline)));
|
|
343
469
|
return { navigated: true };
|
|
344
470
|
}, deadline);
|
|
345
471
|
}
|
|
@@ -351,7 +477,9 @@ class SessionManager {
|
|
|
351
477
|
return this.withLock(async () => {
|
|
352
478
|
this.ensureSession();
|
|
353
479
|
const abortController = new AbortController();
|
|
354
|
-
const
|
|
480
|
+
const requestSignal = this.requestContext?.()?.signal;
|
|
481
|
+
requestSignal?.throwIfAborted();
|
|
482
|
+
const navigationWait = this.startNavigationWait(waitUntil, remainingNavigationTimeout(deadline), requestSignal ? AbortSignal.any([abortController.signal, requestSignal]) : abortController.signal, true);
|
|
355
483
|
navigationWait.promise.catch(() => { });
|
|
356
484
|
navigationWait.markActionStarted();
|
|
357
485
|
try {
|
|
@@ -362,7 +490,7 @@ class SessionManager {
|
|
|
362
490
|
throw error;
|
|
363
491
|
}
|
|
364
492
|
await navigationWait.promise;
|
|
365
|
-
await this.updateState(remainingNavigationTimeout(deadline));
|
|
493
|
+
await withNavigationMetadata(() => this.updateState(remainingNavigationTimeout(deadline)));
|
|
366
494
|
}, deadline);
|
|
367
495
|
}
|
|
368
496
|
/**
|
|
@@ -370,7 +498,24 @@ class SessionManager {
|
|
|
370
498
|
*/
|
|
371
499
|
createLocator(target, options) {
|
|
372
500
|
this.ensureSession();
|
|
373
|
-
|
|
501
|
+
const frame = this.frameScopes.get(this.selectedFrame);
|
|
502
|
+
return new Locator(this.cdp, target, frame?.sessionId ?? this.sessionId, {
|
|
503
|
+
contextId: frame?.contextId,
|
|
504
|
+
frameId: frame?.frameId,
|
|
505
|
+
localPoint: frame
|
|
506
|
+
? async (timeout) => {
|
|
507
|
+
const deadline = Date.now() + timeout;
|
|
508
|
+
for (const owner of frame.owners) {
|
|
509
|
+
if (owner.parentSessionId === frame.sessionId &&
|
|
510
|
+
(await this.getFrameOwnerZoom(owner, remainingNavigationTimeout(deadline))) !== 1) {
|
|
511
|
+
return true;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
return false;
|
|
515
|
+
}
|
|
516
|
+
: undefined,
|
|
517
|
+
mapPoint: (point, timeout) => this.mapFramePoint(point, timeout, false, frame),
|
|
518
|
+
mapViewportPoint: (point, timeout) => this.mapFramePoint(point, timeout, true, frame),
|
|
374
519
|
...options,
|
|
375
520
|
nth: options?.nth ?? target.nth,
|
|
376
521
|
getUrl: () => this.state?.url,
|
|
@@ -381,7 +526,7 @@ class SessionManager {
|
|
|
381
526
|
*/
|
|
382
527
|
createAutoWait(options) {
|
|
383
528
|
this.ensureSession();
|
|
384
|
-
return new AutoWait(this.cdp, this.sessionId, options);
|
|
529
|
+
return new AutoWait(this.cdp, this.frameScopes.get(this.selectedFrame)?.sessionId ?? this.sessionId, options);
|
|
385
530
|
}
|
|
386
531
|
/**
|
|
387
532
|
* 获取行为模拟器
|
|
@@ -448,6 +593,9 @@ class SessionManager {
|
|
|
448
593
|
modifiers: this.modifiers,
|
|
449
594
|
});
|
|
450
595
|
}
|
|
596
|
+
getModifiers() {
|
|
597
|
+
return this.modifiers;
|
|
598
|
+
}
|
|
451
599
|
/**
|
|
452
600
|
* 键盘按下
|
|
453
601
|
*
|
|
@@ -455,7 +603,6 @@ class SessionManager {
|
|
|
455
603
|
* 上层 unified-session 维护 pressedKeys Set 决定是否启用
|
|
456
604
|
*/
|
|
457
605
|
async keyDown(key, commands, options, timeout) {
|
|
458
|
-
const deadline = timeout === undefined ? undefined : Date.now() + timeout;
|
|
459
606
|
this.ensureSession();
|
|
460
607
|
const nextModifiers = MODIFIER_KEYS[key] ? this.modifiers | MODIFIER_KEYS[key] : this.modifiers;
|
|
461
608
|
const keyDefinition = getKeyDefinition(key);
|
|
@@ -473,26 +620,33 @@ class SessionManager {
|
|
|
473
620
|
}
|
|
474
621
|
await this.send('Input.dispatchKeyEvent', params, timeout);
|
|
475
622
|
this.modifiers = nextModifiers;
|
|
476
|
-
if (deadline !== undefined) {
|
|
477
|
-
remainingNavigationTimeout(deadline);
|
|
478
|
-
}
|
|
479
623
|
}
|
|
480
624
|
/**
|
|
481
625
|
* 键盘释放
|
|
482
626
|
*/
|
|
483
|
-
async keyUp(key, timeout) {
|
|
484
|
-
const deadline = timeout === undefined ? undefined : Date.now() + timeout;
|
|
485
|
-
this.ensureSession();
|
|
627
|
+
async keyUp(key, timeout, inputContext) {
|
|
486
628
|
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
|
-
|
|
629
|
+
const nextModifiers = inputContext?.modifiers ?? (MODIFIER_KEYS[key] ? this.modifiers & ~MODIFIER_KEYS[key] : this.modifiers);
|
|
630
|
+
const params = { type: 'keyUp', modifiers: nextModifiers, ...keyDefinition };
|
|
631
|
+
if (inputContext) {
|
|
632
|
+
this.ensureConnected();
|
|
633
|
+
const frame = inputContext.frameId ? this.frameScopes.get(inputContext.frameId) : undefined;
|
|
634
|
+
const sessionId = inputContext.frameId
|
|
635
|
+
? frame?.targetId === inputContext.targetId
|
|
636
|
+
? frame.sessionId
|
|
637
|
+
: undefined
|
|
638
|
+
: this.targetSessions.get(inputContext.targetId);
|
|
639
|
+
if (!sessionId) {
|
|
640
|
+
throw new DriverCapabilityError('Original input session is no longer available for key release');
|
|
641
|
+
}
|
|
642
|
+
this.revisions.set(inputContext.targetId, (this.revisions.get(inputContext.targetId) ?? 0) + 1);
|
|
643
|
+
await this.cdp.send('Input.dispatchKeyEvent', params, sessionId, timeout);
|
|
644
|
+
}
|
|
645
|
+
else {
|
|
646
|
+
await this.send('Input.dispatchKeyEvent', params, timeout);
|
|
647
|
+
}
|
|
648
|
+
if (!inputContext || inputContext.targetId === this.currentTargetId) {
|
|
649
|
+
this.modifiers = nextModifiers;
|
|
496
650
|
}
|
|
497
651
|
}
|
|
498
652
|
/**
|
|
@@ -511,33 +665,46 @@ class SessionManager {
|
|
|
511
665
|
// 归一化换行:\r\n 和 \r 都视作单个 \n
|
|
512
666
|
const normalized = text.replace(/\r\n?/g, '\n');
|
|
513
667
|
for (const char of normalized) {
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
const enterParams = {
|
|
668
|
+
const keyParams = char === '\n'
|
|
669
|
+
? {
|
|
517
670
|
key: 'Enter',
|
|
518
671
|
code: 'Enter',
|
|
519
672
|
windowsVirtualKeyCode: 13,
|
|
520
673
|
nativeVirtualKeyCode: 13,
|
|
521
674
|
modifiers: this.modifiers,
|
|
522
|
-
};
|
|
523
|
-
const keyDownTimeout = remainingTimeout();
|
|
524
|
-
try {
|
|
525
|
-
await this.send('Input.dispatchKeyEvent', { type: 'keyDown', ...enterParams }, keyDownTimeout);
|
|
526
|
-
await this.send('Input.dispatchKeyEvent', { type: 'char', text: '\r', ...enterParams }, remainingTimeout());
|
|
527
675
|
}
|
|
528
|
-
|
|
529
|
-
|
|
676
|
+
: { modifiers: this.modifiers, text: char };
|
|
677
|
+
const keyDownTimeout = remainingTimeout();
|
|
678
|
+
let failed = false;
|
|
679
|
+
let failure;
|
|
680
|
+
try {
|
|
681
|
+
await this.send('Input.dispatchKeyEvent', { type: 'keyDown', ...keyParams }, keyDownTimeout);
|
|
682
|
+
if (char === '\n') {
|
|
683
|
+
// Enter 键:char 通道不接受 \n,必须分发 keyDown + char('\r') + keyUp
|
|
684
|
+
await this.send('Input.dispatchKeyEvent', { type: 'char', text: '\r', ...keyParams }, remainingTimeout());
|
|
530
685
|
}
|
|
531
686
|
}
|
|
532
|
-
|
|
533
|
-
|
|
687
|
+
catch (error) {
|
|
688
|
+
failed = true;
|
|
689
|
+
failure = error;
|
|
690
|
+
}
|
|
691
|
+
finally {
|
|
534
692
|
try {
|
|
535
|
-
await this.send('Input.dispatchKeyEvent', { type: '
|
|
693
|
+
await this.send('Input.dispatchKeyEvent', { type: 'keyUp', ...keyParams }, Math.max(1, deadline - Date.now()), undefined, true);
|
|
536
694
|
}
|
|
537
|
-
|
|
538
|
-
|
|
695
|
+
catch (error) {
|
|
696
|
+
if (failed) {
|
|
697
|
+
console.warn('[MCP] Typing key release failed after input error:', error);
|
|
698
|
+
}
|
|
699
|
+
else {
|
|
700
|
+
failed = true;
|
|
701
|
+
failure = error;
|
|
702
|
+
}
|
|
539
703
|
}
|
|
540
704
|
}
|
|
705
|
+
if (failed) {
|
|
706
|
+
throw failure;
|
|
707
|
+
}
|
|
541
708
|
if (delay > 0) {
|
|
542
709
|
await new Promise((r) => setTimeout(r, Math.min(delay, remainingTimeout())));
|
|
543
710
|
}
|
|
@@ -583,40 +750,25 @@ class SessionManager {
|
|
|
583
750
|
if (fullPage) {
|
|
584
751
|
// 获取页面完整高度
|
|
585
752
|
const sizeExpr = 'JSON.stringify({ width: document.documentElement.scrollWidth, ' +
|
|
586
|
-
'height: document.documentElement.scrollHeight })';
|
|
753
|
+
'height: document.documentElement.scrollHeight, devicePixelRatio: window.devicePixelRatio })';
|
|
587
754
|
const { result } = (await this.send('Runtime.evaluate', {
|
|
588
755
|
expression: sizeExpr,
|
|
589
756
|
returnByValue: true,
|
|
590
757
|
}));
|
|
591
|
-
let width, height;
|
|
758
|
+
let width, height, devicePixelRatio;
|
|
592
759
|
try {
|
|
593
760
|
;
|
|
594
|
-
({ width, height } = JSON.parse(result.value));
|
|
761
|
+
({ width, height, devicePixelRatio } = JSON.parse(result.value));
|
|
595
762
|
}
|
|
596
763
|
catch {
|
|
597
764
|
throw new Error(`screenshot: 无法解析页面尺寸: ${result.value}`);
|
|
598
765
|
}
|
|
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
|
-
}
|
|
766
|
+
assertScreenshotBudget(width, height, (scale ?? 1) * devicePixelRatio);
|
|
767
|
+
captureParams.clip = { x: 0, y: 0, width, height, scale: scale ?? 1 };
|
|
768
|
+
captureParams.captureBeyondViewport = true;
|
|
769
|
+
const { data } = (await this.send('Page.captureScreenshot', captureParams));
|
|
770
|
+
assertScreenshotBase64Budget(data);
|
|
771
|
+
return { data, format: effectiveFormat };
|
|
620
772
|
}
|
|
621
773
|
if (clip) {
|
|
622
774
|
assertScreenshotBudget(clip.width, clip.height, scale ?? 1);
|
|
@@ -653,7 +805,7 @@ class SessionManager {
|
|
|
653
805
|
const state = JSON.parse(result.value);
|
|
654
806
|
// 获取可交互元素
|
|
655
807
|
await this.send('Accessibility.enable');
|
|
656
|
-
const { nodes } = (await this.send('Accessibility.getFullAXTree'));
|
|
808
|
+
const { nodes } = (await this.send('Accessibility.getFullAXTree', this.selectedFrame ? { frameId: this.frameScopes.get(this.selectedFrame)?.frameId } : undefined));
|
|
657
809
|
const interactiveRoles = [
|
|
658
810
|
'button',
|
|
659
811
|
'link',
|
|
@@ -687,8 +839,9 @@ class SessionManager {
|
|
|
687
839
|
async getPageHtml(selector, outer = true) {
|
|
688
840
|
this.ensureSession();
|
|
689
841
|
if (selector) {
|
|
842
|
+
await this.evaluate(`(${installDomHelpers.toString()})();`);
|
|
690
843
|
const prop = outer ? 'outerHTML' : 'innerHTML';
|
|
691
|
-
return this.evaluate(`((s, p) => { const el =
|
|
844
|
+
return this.evaluate(`((s, p) => { const el = globalThis.__mcpDomHelpers.query({selector:s})[0]; return el ? el[p] : '' })`, [selector, prop]);
|
|
692
845
|
}
|
|
693
846
|
return this.evaluate('document.documentElement.outerHTML');
|
|
694
847
|
}
|
|
@@ -698,8 +851,9 @@ class SessionManager {
|
|
|
698
851
|
async getPageText(selector) {
|
|
699
852
|
this.ensureSession();
|
|
700
853
|
if (selector) {
|
|
854
|
+
await this.evaluate(`(${installDomHelpers.toString()})();`);
|
|
701
855
|
return this.evaluate(`(s => {
|
|
702
|
-
const element =
|
|
856
|
+
const element = globalThis.__mcpDomHelpers.query({selector:s})[0];
|
|
703
857
|
return element instanceof HTMLElement ? element.innerText : (element?.textContent ?? '');
|
|
704
858
|
})`, [selector]);
|
|
705
859
|
}
|
|
@@ -709,11 +863,17 @@ class SessionManager {
|
|
|
709
863
|
/** Extension readPage 等价物:CDP 通过页面 DOM 构造 pageContent 和 interactiveElements */
|
|
710
864
|
async readPage(options) {
|
|
711
865
|
const state = await this.getPageState();
|
|
712
|
-
const interactiveElements = await this.collectInteractiveElements(options?.depth);
|
|
866
|
+
const interactiveElements = await this.collectInteractiveElements(options?.depth, options?.target, options?.timeout);
|
|
713
867
|
const lines = interactiveElements.map((e) => {
|
|
714
868
|
let line = e.role;
|
|
715
869
|
if (e.name) {
|
|
716
|
-
line += `
|
|
870
|
+
line += ` ${JSON.stringify(e.name)}`;
|
|
871
|
+
}
|
|
872
|
+
if (e.type) {
|
|
873
|
+
line += ` type=${JSON.stringify(e.type)}`;
|
|
874
|
+
}
|
|
875
|
+
if (e.value !== undefined) {
|
|
876
|
+
line += ` value=${JSON.stringify(e.value)}`;
|
|
717
877
|
}
|
|
718
878
|
return line;
|
|
719
879
|
});
|
|
@@ -723,9 +883,11 @@ class SessionManager {
|
|
|
723
883
|
interactiveElements,
|
|
724
884
|
};
|
|
725
885
|
}
|
|
726
|
-
async collectInteractiveElements(depth) {
|
|
886
|
+
async collectInteractiveElements(depth, target, timeout) {
|
|
727
887
|
const maxDepth = Number.isInteger(depth) && depth !== undefined && depth >= 0 ? depth : 15;
|
|
728
|
-
|
|
888
|
+
await this.evaluate(`(${installDomHelpers.toString()})();`, undefined, timeout);
|
|
889
|
+
const script = `function() {
|
|
890
|
+
var root = this;
|
|
729
891
|
var maxDepth = ${maxDepth};
|
|
730
892
|
function selectorFor(el) {
|
|
731
893
|
if (!(el instanceof Element)) return '';
|
|
@@ -755,65 +917,67 @@ class SessionManager {
|
|
|
755
917
|
function depthFor(el) {
|
|
756
918
|
var depth = 0;
|
|
757
919
|
var current = el;
|
|
758
|
-
while (current.parentElement) {
|
|
920
|
+
while (current !== root && (current.parentElement || current.getRootNode().host)) {
|
|
759
921
|
depth += 1;
|
|
760
|
-
current = current.parentElement;
|
|
922
|
+
current = current.parentElement || current.getRootNode().host;
|
|
761
923
|
}
|
|
762
924
|
return depth;
|
|
763
925
|
}
|
|
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
926
|
var selector = [
|
|
791
927
|
'button,a[href],input,textarea,select,[role]',
|
|
792
928
|
'[contenteditable="true"],[tabindex]:not([tabindex="-1"])'
|
|
793
929
|
].join(',');
|
|
794
|
-
|
|
930
|
+
var elements = globalThis.__mcpDomHelpers.query({selector:selector}, root);
|
|
931
|
+
if (root.nodeType === 1 && root.matches(selector)) elements.unshift(root);
|
|
932
|
+
return elements.filter(function(el) {
|
|
795
933
|
return depthFor(el) <= maxDepth;
|
|
796
934
|
}).slice(0, 100).map(function(el, index) {
|
|
797
935
|
var rect = el.getBoundingClientRect();
|
|
798
936
|
var cx = rect.left + rect.width / 2;
|
|
799
937
|
var cy = rect.top + rect.height / 2;
|
|
800
|
-
var top = rect.width > 0 && rect.height > 0
|
|
938
|
+
var top = rect.width > 0 && rect.height > 0
|
|
939
|
+
? globalThis.__mcpDomHelpers.deepElementFromPoint(cx, cy) : null;
|
|
801
940
|
var style = getComputedStyle(el);
|
|
802
941
|
var visible = rect.width > 0 && rect.height > 0 &&
|
|
803
942
|
style.visibility !== 'hidden' && style.display !== 'none';
|
|
943
|
+
var name = globalThis.__mcpDomHelpers.accessibleName(el, true);
|
|
944
|
+
var type = el.tagName.toLowerCase() === 'input' ? el.type : undefined;
|
|
945
|
+
var value = type !== undefined && !['hidden','password','file'].includes(type) &&
|
|
946
|
+
(!name || !['button','submit','reset'].includes(type)) ? el.value : undefined;
|
|
804
947
|
return {
|
|
805
948
|
refId: 'cdp-' + index,
|
|
806
|
-
role:
|
|
807
|
-
name:
|
|
949
|
+
role: globalThis.__mcpDomHelpers.role(el),
|
|
950
|
+
name: name,
|
|
951
|
+
...(type !== undefined ? {type: type} : {}),
|
|
952
|
+
...(value !== undefined ? {value: value} : {}),
|
|
808
953
|
selector: selectorFor(el),
|
|
809
954
|
visible: visible,
|
|
810
|
-
disabled:
|
|
955
|
+
disabled: el.matches(':disabled') || Boolean(el.disabled) ||
|
|
956
|
+
el.getAttribute('aria-disabled') === 'true',
|
|
811
957
|
bounds: {x: rect.x, y: rect.y, width: rect.width, height: rect.height},
|
|
812
958
|
covered: Boolean(visible && top && top !== el && !el.contains(top)),
|
|
813
959
|
frameId: 0
|
|
814
960
|
};
|
|
815
961
|
});
|
|
816
|
-
}
|
|
962
|
+
}`;
|
|
963
|
+
if (target && 'x' in target && 'y' in target) {
|
|
964
|
+
const elements = await this.evaluate('(() => {\n const root = ' +
|
|
965
|
+
'globalThis.__mcpDomHelpers.deepElementFromPoin' +
|
|
966
|
+
't(' +
|
|
967
|
+
`${JSON.stringify(target.x)}` +
|
|
968
|
+
', ' +
|
|
969
|
+
`${JSON.stringify(target.y)}` +
|
|
970
|
+
');\n return root ? (' +
|
|
971
|
+
`${script}` +
|
|
972
|
+
').call(root) : null;\n })()', undefined, timeout);
|
|
973
|
+
if (!elements) {
|
|
974
|
+
throw new ElementNotFoundError(target, timeout ?? DEFAULT_TIMEOUT);
|
|
975
|
+
}
|
|
976
|
+
return elements;
|
|
977
|
+
}
|
|
978
|
+
return target
|
|
979
|
+
? this.createLocator(target, timeout !== undefined ? { timeout } : undefined).evaluateOn(script)
|
|
980
|
+
: this.evaluate(`(${script}).call(document)`, undefined, timeout);
|
|
817
981
|
}
|
|
818
982
|
async getFrames() {
|
|
819
983
|
this.ensureSession();
|
|
@@ -841,16 +1005,18 @@ class SessionManager {
|
|
|
841
1005
|
}
|
|
842
1006
|
/** CDP 通过 evaluate 注入函数枚举 IMG */
|
|
843
1007
|
async getHtmlWithImages(selector, outer = true) {
|
|
1008
|
+
await this.evaluate(`(${installDomHelpers.toString()})();`);
|
|
844
1009
|
const selectorArg = JSON.stringify(selector ?? null);
|
|
845
1010
|
return this.evaluate(`(function() {
|
|
846
|
-
var root = ${selectorArg}
|
|
1011
|
+
var root = ${selectorArg}
|
|
1012
|
+
? globalThis.__mcpDomHelpers.query({selector:${selectorArg}})[0] : document.documentElement;
|
|
847
1013
|
if (!root) return {html: '', images: []};
|
|
848
1014
|
var html = ${selectorArg}
|
|
849
1015
|
? (${outer} ? root.outerHTML : root.innerHTML)
|
|
850
1016
|
: document.documentElement.outerHTML;
|
|
851
1017
|
var imgList = [];
|
|
852
1018
|
if (root.tagName === 'IMG') imgList.push(root);
|
|
853
|
-
|
|
1019
|
+
globalThis.__mcpDomHelpers.query({selector:'img'},root).forEach(function(img) { imgList.push(img); });
|
|
854
1020
|
var images = [];
|
|
855
1021
|
for (var i = 0; i < imgList.length; i++) {
|
|
856
1022
|
var img = imgList[i];
|
|
@@ -912,54 +1078,24 @@ class SessionManager {
|
|
|
912
1078
|
}
|
|
913
1079
|
// ==================== IBrowserDriver: 元素查找 ====================
|
|
914
1080
|
/** 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);
|
|
1081
|
+
async find(selector, text, xpath, timeout, semanticOrMatchIndex, matchIndex) {
|
|
1082
|
+
const semantic = typeof semanticOrMatchIndex === 'object' ? semanticOrMatchIndex : undefined;
|
|
1083
|
+
const nth = typeof semanticOrMatchIndex === 'number' ? semanticOrMatchIndex : matchIndex;
|
|
1084
|
+
await this.evaluate(`(${installDomHelpers.toString()})();`, undefined, timeout);
|
|
1085
|
+
return this.evaluate(`function(selector, text, xpath, semantic, nth) {
|
|
1086
|
+
const elements = globalThis.__mcpDomHelpers.query({
|
|
1087
|
+
selector: selector ?? undefined, text: text ?? undefined,
|
|
1088
|
+
xpath: xpath ?? undefined, semantic: semantic ?? undefined
|
|
1089
|
+
});
|
|
1090
|
+
return (nth == null ? elements.slice(0,50) : elements.slice(nth,nth+1)).map(el => {
|
|
1091
|
+
const r = el.getBoundingClientRect();
|
|
1092
|
+
return {
|
|
1093
|
+
refId: '', tag: el.tagName.toLowerCase(),
|
|
1094
|
+
text: (el.textContent || '').trim().slice(0,100),
|
|
1095
|
+
rect: {x:r.x,y:r.y,width:r.width,height:r.height}
|
|
1096
|
+
};
|
|
1097
|
+
});
|
|
1098
|
+
}`, [selector ?? null, text ?? null, xpath ?? null, semantic ?? null, nth ?? null], timeout);
|
|
963
1099
|
}
|
|
964
1100
|
// ==================== IBrowserDriver: 元素操作(refId 类,CDP 不支持) ====================
|
|
965
1101
|
click(_refId) {
|
|
@@ -994,7 +1130,11 @@ class SessionManager {
|
|
|
994
1130
|
if (!selector) {
|
|
995
1131
|
throw new DriverCapabilityError('getAttribute 需要 selector');
|
|
996
1132
|
}
|
|
997
|
-
|
|
1133
|
+
await this.evaluate(`(${installDomHelpers.toString()})();`);
|
|
1134
|
+
return this.evaluate(`(s, a) => {
|
|
1135
|
+
const el = globalThis.__mcpDomHelpers.query({selector:s})[0];
|
|
1136
|
+
return el ? el.getAttribute(a) : null;
|
|
1137
|
+
}`, [selector, attribute]);
|
|
998
1138
|
}
|
|
999
1139
|
// ==================== IBrowserDriver: 输入(precise) ====================
|
|
1000
1140
|
/** CDP 通用 inputKey 接口实现:直接转发 Input.dispatchKeyEvent,不维护 modifiers(由调用方提供) */
|
|
@@ -1167,10 +1307,10 @@ class SessionManager {
|
|
|
1167
1307
|
return this.currentTargetId;
|
|
1168
1308
|
}
|
|
1169
1309
|
async deselectPage(timeout) {
|
|
1170
|
-
const
|
|
1310
|
+
const sid = this.sessionId;
|
|
1171
1311
|
try {
|
|
1172
|
-
if (
|
|
1173
|
-
await this.cdp.send('Target.detachFromTarget', { sessionId:
|
|
1312
|
+
if (sid && this.cdp?.isConnected && !this.eventControllers.has(sid)) {
|
|
1313
|
+
await this.cdp.send('Target.detachFromTarget', { sessionId: sid }, undefined, timeout);
|
|
1174
1314
|
}
|
|
1175
1315
|
}
|
|
1176
1316
|
finally {
|
|
@@ -1218,21 +1358,308 @@ class SessionManager {
|
|
|
1218
1358
|
throw new DriverCapabilityError('CDP 模式不支持同步切换 target,请用 selectPage(targetId) 或 attachToTarget(targetId)');
|
|
1219
1359
|
}
|
|
1220
1360
|
}
|
|
1221
|
-
// ==================== IBrowserDriver:
|
|
1222
|
-
resolveFrame(
|
|
1223
|
-
|
|
1361
|
+
// ==================== IBrowserDriver: 原生 frame scope ====================
|
|
1362
|
+
async resolveFrame(frame, timeout) {
|
|
1363
|
+
this.ensureSession();
|
|
1364
|
+
const deadline = Date.now() + (timeout ?? DEFAULT_TIMEOUT);
|
|
1365
|
+
const rootSid = this.sessionId;
|
|
1366
|
+
await this.cdp.send('Target.setAutoAttach', {
|
|
1367
|
+
autoAttach: true,
|
|
1368
|
+
waitForDebuggerOnStart: false,
|
|
1369
|
+
flatten: true,
|
|
1370
|
+
filter: [{ type: 'iframe', exclude: false }],
|
|
1371
|
+
}, rootSid, remainingNavigationTimeout(deadline));
|
|
1372
|
+
await this.cdp.send('Runtime.enable', {}, rootSid, remainingNavigationTimeout(deadline));
|
|
1373
|
+
const tree = await this.cdp.send('Page.getFrameTree', {}, rootSid, remainingNavigationTimeout(deadline));
|
|
1374
|
+
let nativeFrame = tree.frameTree.frame.id;
|
|
1375
|
+
let sid = rootSid;
|
|
1376
|
+
const owners = [];
|
|
1377
|
+
const path = Array.isArray(frame) ? frame : [frame];
|
|
1378
|
+
if (!path.length) {
|
|
1379
|
+
throw new DriverCapabilityError('Frame path must contain at least one selection');
|
|
1380
|
+
}
|
|
1381
|
+
for (const selection of path) {
|
|
1382
|
+
const context = (this.contexts.get(sid) ?? []).find((c) => c.frameId === nativeFrame && c.isDefault);
|
|
1383
|
+
if (!context) {
|
|
1384
|
+
throw new DriverCapabilityError(`Default execution context unavailable for frame ${nativeFrame}`);
|
|
1385
|
+
}
|
|
1386
|
+
const query = typeof selection === 'number'
|
|
1387
|
+
? `globalThis.__mcpDomHelpers.query({selector:'iframe,frame'})[${selection}]`
|
|
1388
|
+
: `globalThis.__mcpDomHelpers.query({selector:${JSON.stringify(selection)}})[0]`;
|
|
1389
|
+
const expression = `(${installDomHelpers.toString()})();${query}`;
|
|
1390
|
+
const resolutionContext = {
|
|
1391
|
+
tabId: this.currentTargetId,
|
|
1392
|
+
phase: 'frame_resolution',
|
|
1393
|
+
selection,
|
|
1394
|
+
path,
|
|
1395
|
+
actionExecuted: false,
|
|
1396
|
+
actionStatus: 'not_started',
|
|
1397
|
+
retryable: false,
|
|
1398
|
+
};
|
|
1399
|
+
const result = await this.cdp.send('Runtime.evaluate', { expression, contextId: context.id, returnByValue: false }, sid, remainingNavigationTimeout(deadline));
|
|
1400
|
+
if (result.exceptionDetails || !result.result.objectId) {
|
|
1401
|
+
const exception = result.exceptionDetails?.exception;
|
|
1402
|
+
const invalidSelector = exception?.className === 'SyntaxError' ||
|
|
1403
|
+
(exception?.className === 'DOMException' && /^SyntaxError:/.test(exception.description ?? ''));
|
|
1404
|
+
if (result.exceptionDetails && !invalidSelector) {
|
|
1405
|
+
throw new DriverCapabilityError('Frame selection failed: ' + result.exceptionDetails.text);
|
|
1406
|
+
}
|
|
1407
|
+
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' });
|
|
1408
|
+
}
|
|
1409
|
+
const objectSessionId = sid;
|
|
1410
|
+
try {
|
|
1411
|
+
const descriptor = await this.cdp.send('DOM.describeNode', { objectId: result.result.objectId }, sid, remainingNavigationTimeout(deadline));
|
|
1412
|
+
if (!['IFRAME', 'FRAME'].includes(descriptor.node.nodeName) || !descriptor.node.frameId) {
|
|
1413
|
+
const notFrame = !['IFRAME', 'FRAME'].includes(descriptor.node.nodeName);
|
|
1414
|
+
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' });
|
|
1415
|
+
}
|
|
1416
|
+
nativeFrame = descriptor.node.frameId;
|
|
1417
|
+
sid = this.frameSessions.get(nativeFrame) ?? sid;
|
|
1418
|
+
await this.cdp.send('Runtime.enable', {}, sid, remainingNavigationTimeout(deadline));
|
|
1419
|
+
if (!(this.contexts.get(sid) ?? []).some((c) => c.frameId === nativeFrame && c.isDefault)) {
|
|
1420
|
+
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);
|
|
1421
|
+
void oopif;
|
|
1422
|
+
sid = this.frameSessions.get(nativeFrame) ?? sid;
|
|
1423
|
+
}
|
|
1424
|
+
const childContext = (this.contexts.get(sid) ?? []).find((c) => c.frameId === nativeFrame && c.isDefault);
|
|
1425
|
+
if (!childContext) {
|
|
1426
|
+
throw new DriverCapabilityError('Frame execution context changed during selection');
|
|
1427
|
+
}
|
|
1428
|
+
owners.push({
|
|
1429
|
+
parentSessionId: objectSessionId,
|
|
1430
|
+
backendNodeId: descriptor.node.backendNodeId,
|
|
1431
|
+
frameId: nativeFrame,
|
|
1432
|
+
sessionId: sid,
|
|
1433
|
+
contextId: childContext.id,
|
|
1434
|
+
});
|
|
1435
|
+
}
|
|
1436
|
+
finally {
|
|
1437
|
+
void this.cdp.send('Runtime.releaseObject', { objectId: result.result.objectId }, objectSessionId).catch(() => { });
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
const context = (this.contexts.get(sid) ?? []).find((c) => c.frameId === nativeFrame && c.isDefault);
|
|
1441
|
+
if (!context) {
|
|
1442
|
+
throw new DriverCapabilityError('Frame execution context changed during selection');
|
|
1443
|
+
}
|
|
1444
|
+
const handle = ++this.nextFrameHandle;
|
|
1445
|
+
if (this.frameScopes.size > 64) {
|
|
1446
|
+
this.frameScopes.delete(this.frameScopes.keys().next().value);
|
|
1447
|
+
}
|
|
1448
|
+
this.frameScopes.set(handle, {
|
|
1449
|
+
targetId: this.currentTargetId,
|
|
1450
|
+
frameId: nativeFrame,
|
|
1451
|
+
contextId: context.id,
|
|
1452
|
+
sessionId: sid,
|
|
1453
|
+
owners,
|
|
1454
|
+
});
|
|
1455
|
+
return {
|
|
1456
|
+
frameId: handle,
|
|
1457
|
+
offset: null,
|
|
1458
|
+
frameContext: {
|
|
1459
|
+
backend: 'cdp',
|
|
1460
|
+
frameId: nativeFrame,
|
|
1461
|
+
contextId: context.id,
|
|
1462
|
+
sessionId: sid,
|
|
1463
|
+
selection: frame,
|
|
1464
|
+
},
|
|
1465
|
+
};
|
|
1466
|
+
}
|
|
1467
|
+
async mapFramePoint(point, timeout = DEFAULT_TIMEOUT, viewportPoint = false, frame = this.frameScopes.get(this.selectedFrame)) {
|
|
1468
|
+
if (!frame) {
|
|
1469
|
+
return point;
|
|
1470
|
+
}
|
|
1471
|
+
const deadline = Date.now() + timeout;
|
|
1472
|
+
const remaining = () => remainingNavigationTimeout(deadline);
|
|
1473
|
+
let currentSession = frame.sessionId;
|
|
1474
|
+
let local = !viewportPoint;
|
|
1475
|
+
let mapped = point;
|
|
1476
|
+
try {
|
|
1477
|
+
for (const owner of [...frame.owners].reverse()) {
|
|
1478
|
+
// Same-session quads already include every ancestor in that viewport.
|
|
1479
|
+
const sameViewport = !local && owner.parentSessionId === currentSession;
|
|
1480
|
+
if (sameViewport && (await this.getFrameOwnerZoom(owner, remaining())) === 1) {
|
|
1481
|
+
continue;
|
|
1482
|
+
}
|
|
1483
|
+
if (sameViewport) {
|
|
1484
|
+
// Descendant quads omit an ancestor iframe's CSS zoom. Undo their query viewport first.
|
|
1485
|
+
const anchor = await this.cdp.send('Runtime.evaluate', {
|
|
1486
|
+
contextId: owner.contextId,
|
|
1487
|
+
returnByValue: false,
|
|
1488
|
+
expression: '(() => {\n const ' +
|
|
1489
|
+
'walk=document.createTreeWalker(document,' +
|
|
1490
|
+
'NodeFilter.SHOW_ELEMENT);\n ' +
|
|
1491
|
+
' for(let el=walk.nextNode();el;' +
|
|
1492
|
+
'el=walk.nextNode()) {\n ' +
|
|
1493
|
+
' const r=el.getBoundingClientRect();\n ' +
|
|
1494
|
+
' if (!(r.width>0 ' +
|
|
1495
|
+
'&& r.height>0) || el.getClientRects().length!=' +
|
|
1496
|
+
'=1) continue;\n ' +
|
|
1497
|
+
'let aligned=true;\n ' +
|
|
1498
|
+
' for(let p=el;p;p=p.parentElement) {\n ' +
|
|
1499
|
+
' const ' +
|
|
1500
|
+
's=getComputedStyle(p),m=new ' +
|
|
1501
|
+
"DOMMatrix(s.transform==='none'?undefined:s.tra" +
|
|
1502
|
+
'nsform);\n ' +
|
|
1503
|
+
'if(!m.is2D || Math.abs(m.b)>1e-12 || ' +
|
|
1504
|
+
'Math.abs(m.c)>1e-12 || m.a<=0 || m.d<=0 ||\n ' +
|
|
1505
|
+
' ' +
|
|
1506
|
+
"(s.rotate&&s.rotate!=='none'&&!/^(?:[xyz] " +
|
|
1507
|
+
')?0deg$/.test(s.rotate)) ||\n ' +
|
|
1508
|
+
" (s.scale&&s.scale!=='non" +
|
|
1509
|
+
"e'&&s.scale.split(/\\s+/).some(value=>" +
|
|
1510
|
+
'Number(value)<=0))) {aligned=false;break}\n ' +
|
|
1511
|
+
' }\n ' +
|
|
1512
|
+
' if(aligned)return el;\n ' +
|
|
1513
|
+
' }\n ' +
|
|
1514
|
+
' return null;\n })()',
|
|
1515
|
+
}, owner.sessionId, remaining());
|
|
1516
|
+
const objectId = anchor.result.objectId;
|
|
1517
|
+
if (!objectId) {
|
|
1518
|
+
// noinspection ExceptionCaughtLocallyJS -- 外层统一返回 frame 几何错误
|
|
1519
|
+
throw new Error('Frame zoom viewport anchor is unavailable');
|
|
1520
|
+
}
|
|
1521
|
+
try {
|
|
1522
|
+
const { result: { value: r }, } = await this.cdp.send('Runtime.callFunctionOn', {
|
|
1523
|
+
objectId,
|
|
1524
|
+
functionDeclaration: 'function(){const r=this.getBoundingClientRect();' +
|
|
1525
|
+
'return {x:r.x,y:r.y,width:r.width,' +
|
|
1526
|
+
'height:r.height}}',
|
|
1527
|
+
returnByValue: true,
|
|
1528
|
+
}, owner.sessionId, remaining());
|
|
1529
|
+
const { model: { border: q }, } = await this.cdp.send('DOM.getBoxModel', { objectId }, owner.sessionId, remaining());
|
|
1530
|
+
if (!(r.width > 0 && r.height > 0) || q.length !== 8 || !q.every(Number.isFinite)) {
|
|
1531
|
+
// noinspection ExceptionCaughtLocallyJS -- 统一返回几何错误并释放临时对象
|
|
1532
|
+
throw new Error('Frame zoom viewport anchor is invalid');
|
|
1533
|
+
}
|
|
1534
|
+
const [a, b, c, d] = [
|
|
1535
|
+
(q[2] - q[0]) / r.width,
|
|
1536
|
+
(q[3] - q[1]) / r.width,
|
|
1537
|
+
(q[6] - q[0]) / r.height,
|
|
1538
|
+
(q[7] - q[1]) / r.height,
|
|
1539
|
+
];
|
|
1540
|
+
const determinant = a * d - b * c;
|
|
1541
|
+
if (Math.abs(determinant) < 1e-12 ||
|
|
1542
|
+
Math.abs(q[4] - q[2] - q[6] + q[0]) > 0.001 ||
|
|
1543
|
+
Math.abs(q[5] - q[3] - q[7] + q[1]) > 0.001) {
|
|
1544
|
+
// noinspection ExceptionCaughtLocallyJS -- 统一返回几何错误并释放临时对象
|
|
1545
|
+
throw new Error('Frame zoom viewport anchor is singular or non-affine');
|
|
1546
|
+
}
|
|
1547
|
+
const dx = mapped.x - q[0], dy = mapped.y - q[1];
|
|
1548
|
+
mapped = { x: (d * dx - c * dy) / determinant + r.x, y: (a * dy - b * dx) / determinant + r.y };
|
|
1549
|
+
}
|
|
1550
|
+
finally {
|
|
1551
|
+
await this.cdp.send('Runtime.releaseObject', { objectId }, owner.sessionId, 1000).catch((error) => console.warn('[MCP] Frame zoom anchor cleanup failed:', error));
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
if (!(this.contexts.get(owner.sessionId) ?? []).some((c) => c.id === owner.contextId && c.frameId === owner.frameId)) {
|
|
1555
|
+
// noinspection ExceptionCaughtLocallyJS -- 外层统一返回 frame 身份变化的几何错误
|
|
1556
|
+
throw new Error('Frame document identity changed before input');
|
|
1557
|
+
}
|
|
1558
|
+
const { node } = await this.cdp.send('DOM.describeNode', { backendNodeId: owner.backendNodeId }, owner.parentSessionId, remaining());
|
|
1559
|
+
if (node.frameId !== owner.frameId) {
|
|
1560
|
+
// noinspection ExceptionCaughtLocallyJS -- 外层统一返回 frame 身份变化的几何错误
|
|
1561
|
+
throw new Error('Frame owner identity changed before input');
|
|
1562
|
+
}
|
|
1563
|
+
const { model } = await this.cdp.send('DOM.getBoxModel', { backendNodeId: owner.backendNodeId }, owner.parentSessionId, remaining());
|
|
1564
|
+
const viewport = await this.cdp.send('Runtime.evaluate', {
|
|
1565
|
+
expression: '({width:innerWidth,height:innerHeight})',
|
|
1566
|
+
contextId: owner.contextId,
|
|
1567
|
+
returnByValue: true,
|
|
1568
|
+
}, owner.sessionId, remaining());
|
|
1569
|
+
const { width, height } = viewport.result.value ?? {};
|
|
1570
|
+
const q = model.content;
|
|
1571
|
+
if (viewport.exceptionDetails ||
|
|
1572
|
+
!(width > 0 && height > 0) ||
|
|
1573
|
+
q.length !== 8 ||
|
|
1574
|
+
!q.every(Number.isFinite)) {
|
|
1575
|
+
// noinspection ExceptionCaughtLocallyJS -- 外层统一返回 frame 几何错误
|
|
1576
|
+
throw new Error('Frame content quad or viewport is unavailable');
|
|
1577
|
+
}
|
|
1578
|
+
const [a, b, c, d, e, f] = [
|
|
1579
|
+
(q[2] - q[0]) / width,
|
|
1580
|
+
(q[3] - q[1]) / width,
|
|
1581
|
+
(q[6] - q[0]) / height,
|
|
1582
|
+
(q[7] - q[1]) / height,
|
|
1583
|
+
q[0],
|
|
1584
|
+
q[1],
|
|
1585
|
+
];
|
|
1586
|
+
if (Math.abs(a * d - b * c) < 1e-12 ||
|
|
1587
|
+
Math.abs(q[4] - q[2] - q[6] + q[0]) > 0.001 ||
|
|
1588
|
+
Math.abs(q[5] - q[3] - q[7] + q[1]) > 0.001) {
|
|
1589
|
+
// noinspection ExceptionCaughtLocallyJS -- 外层统一返回 frame 几何错误
|
|
1590
|
+
throw new Error('Frame content quad is singular or non-affine');
|
|
1591
|
+
}
|
|
1592
|
+
mapped = { x: a * mapped.x + c * mapped.y + e, y: b * mapped.x + d * mapped.y + f };
|
|
1593
|
+
currentSession = owner.parentSessionId;
|
|
1594
|
+
local = false;
|
|
1595
|
+
}
|
|
1596
|
+
return mapped;
|
|
1597
|
+
}
|
|
1598
|
+
catch (error) {
|
|
1599
|
+
throw new StructuredToolError('FRAME_GEOMETRY_UNAVAILABLE', error instanceof Error ? error.message : String(error), '重新读取 frame 的文档和布局后再执行输入', { actionExecuted: false, actionStatus: 'not_started', retryable: false });
|
|
1600
|
+
}
|
|
1224
1601
|
}
|
|
1225
1602
|
getCurrentFrameId() {
|
|
1226
|
-
|
|
1227
|
-
return 0;
|
|
1603
|
+
return this.selectedFrame;
|
|
1228
1604
|
}
|
|
1229
1605
|
setCurrentFrameId(frameId) {
|
|
1230
|
-
if (frameId !==
|
|
1231
|
-
throw new DriverCapabilityError('
|
|
1606
|
+
if (frameId && this.frameScopes.get(frameId)?.targetId !== this.currentTargetId) {
|
|
1607
|
+
throw new DriverCapabilityError('CDP frame scope is no longer available');
|
|
1608
|
+
}
|
|
1609
|
+
this.selectedFrame = frameId;
|
|
1610
|
+
}
|
|
1611
|
+
async evaluateInFrame(frameId, expression, timeout, _staleContextRetry) {
|
|
1612
|
+
const frame = this.frameScopes.get(frameId);
|
|
1613
|
+
if (!frame) {
|
|
1614
|
+
throw new DriverCapabilityError('CDP frame scope is no longer available');
|
|
1232
1615
|
}
|
|
1616
|
+
return this.cdp.send('Runtime.evaluate', { expression, contextId: frame.contextId, returnByValue: true, awaitPromise: true, timeout }, frame.sessionId, timeout);
|
|
1233
1617
|
}
|
|
1234
|
-
|
|
1235
|
-
|
|
1618
|
+
async browserEvents(action, command, targetId, timeout) {
|
|
1619
|
+
this.ensureConnected();
|
|
1620
|
+
browserEventCommandSchema.parse({ action, command });
|
|
1621
|
+
const target = command.ref ? eventRefTarget(command.ref) : undefined;
|
|
1622
|
+
if (target && (target.backend !== 'cdp' || (targetId && target.targetId !== targetId))) {
|
|
1623
|
+
throw new DriverCapabilityError('Browser event ref target mismatch');
|
|
1624
|
+
}
|
|
1625
|
+
const id = target?.targetId ?? targetId ?? this.currentTargetId;
|
|
1626
|
+
const sid = id && this.targetSessions.get(id);
|
|
1627
|
+
if (!id || !sid) {
|
|
1628
|
+
throw new DriverCapabilityError('No observed CDP session for this target');
|
|
1629
|
+
}
|
|
1630
|
+
const controller = this.ensureEventController(id, sid);
|
|
1631
|
+
const scope = this.requestContext?.();
|
|
1632
|
+
scope?.signal?.throwIfAborted();
|
|
1633
|
+
if (scope?.deadline !== undefined && Date.now() >= scope.deadline) {
|
|
1634
|
+
throw new TimeoutError('Browser event deadline exceeded');
|
|
1635
|
+
}
|
|
1636
|
+
const abort = () => {
|
|
1637
|
+
void controller.abortPending('request cancelled');
|
|
1638
|
+
};
|
|
1639
|
+
scope?.signal?.addEventListener('abort', abort, { once: true });
|
|
1640
|
+
try {
|
|
1641
|
+
return await controller.command(action, {
|
|
1642
|
+
...command,
|
|
1643
|
+
...(action === 'download' && command.op === 'wait' && timeout
|
|
1644
|
+
? { timeout: Math.min(Number(command.timeout ?? timeout), timeout) }
|
|
1645
|
+
: {}),
|
|
1646
|
+
}, scope?.signal);
|
|
1647
|
+
}
|
|
1648
|
+
finally {
|
|
1649
|
+
scope?.signal?.removeEventListener('abort', abort);
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
async browserFetchCommand(method, params, targetId) {
|
|
1653
|
+
const id = targetId ?? this.currentTargetId;
|
|
1654
|
+
const sid = id && this.targetSessions.get(id);
|
|
1655
|
+
if (!id || !sid) {
|
|
1656
|
+
throw new DriverCapabilityError('No observed CDP session for this target');
|
|
1657
|
+
}
|
|
1658
|
+
return this.ensureEventController(id, sid).rawFetch(method, params);
|
|
1659
|
+
}
|
|
1660
|
+
async suspendBrowserEventsForChallenge() {
|
|
1661
|
+
this.ensureSession();
|
|
1662
|
+
return this.ensureEventController(this.currentTargetId, this.sessionId).suspend('Cloudflare challenge');
|
|
1236
1663
|
}
|
|
1237
1664
|
// ==================== IBrowserDriver: CDP 直通 ====================
|
|
1238
1665
|
/**
|
|
@@ -1241,6 +1668,10 @@ class SessionManager {
|
|
|
1241
1668
|
* browser-level 域(Target/Browser/SystemInfo/DeviceAccess/IO)走 sendBrowserCommand
|
|
1242
1669
|
*/
|
|
1243
1670
|
async debuggerSend(method, params, _tabId, timeout) {
|
|
1671
|
+
if (method.startsWith('Fetch.')) {
|
|
1672
|
+
this.ensureSession();
|
|
1673
|
+
return this.ensureEventController(this.currentTargetId, this.sessionId).rawFetch(method, params);
|
|
1674
|
+
}
|
|
1244
1675
|
const domain = method.split('.')[0];
|
|
1245
1676
|
const browserLevelDomains = ['Target', 'Browser', 'SystemInfo', 'DeviceAccess', 'IO'];
|
|
1246
1677
|
if (browserLevelDomains.includes(domain)) {
|
|
@@ -1270,13 +1701,38 @@ class SessionManager {
|
|
|
1270
1701
|
* 获取 Cookies
|
|
1271
1702
|
*/
|
|
1272
1703
|
async getCookies(filter) {
|
|
1704
|
+
if (![filter?.name, filter?.domain, filter?.url].some((value) => value !== undefined && value.trim().length > 0)) {
|
|
1705
|
+
throw new StructuredToolError('INVALID_ARGUMENT', 'cookies action=get 必须带非空 name、domain 或 url 过滤参数', '指定读取范围后再获取 Cookie', { actionExecuted: false, actionStatus: 'not_started', retryable: false });
|
|
1706
|
+
}
|
|
1273
1707
|
this.ensureSession();
|
|
1274
1708
|
const urls = filter?.url ? [filter.url] : undefined;
|
|
1275
|
-
const
|
|
1709
|
+
const contextId = await this.cookieContext(filter);
|
|
1710
|
+
const scoped = filter?.targetId !== undefined || filter?.browserContextId !== undefined;
|
|
1711
|
+
const { cookies } = scoped
|
|
1712
|
+
? await this.sendBrowserCommand('Storage.getCookies', contextId ? { browserContextId: contextId } : {})
|
|
1713
|
+
: await this.send('Network.getCookies', urls ? { urls } : {});
|
|
1276
1714
|
if (!filter) {
|
|
1277
1715
|
return cookies;
|
|
1278
1716
|
}
|
|
1279
1717
|
return cookies.filter((c) => {
|
|
1718
|
+
if (filter.url && scoped) {
|
|
1719
|
+
const url = new URL(filter.url);
|
|
1720
|
+
const domain = c.domain.replace(/^\./, '');
|
|
1721
|
+
if (url.hostname !== domain && !(c.domain.startsWith('.') && url.hostname.endsWith('.' + domain))) {
|
|
1722
|
+
return false;
|
|
1723
|
+
}
|
|
1724
|
+
const pathMatches = url.pathname === c.path ||
|
|
1725
|
+
(url.pathname.startsWith(c.path) && (c.path.endsWith('/') || url.pathname[c.path.length] === '/'));
|
|
1726
|
+
if (!pathMatches || (c.secure && url.protocol !== 'https:')) {
|
|
1727
|
+
return false;
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
const partition = c.partitionKey;
|
|
1731
|
+
if (filter.partitionKey &&
|
|
1732
|
+
(!partition ||
|
|
1733
|
+
Object.entries(filter.partitionKey).some(([key, value]) => partition[key] !== value))) {
|
|
1734
|
+
return false;
|
|
1735
|
+
}
|
|
1280
1736
|
if (filter.name && c.name !== filter.name) {
|
|
1281
1737
|
return false;
|
|
1282
1738
|
}
|
|
@@ -1309,7 +1765,8 @@ class SessionManager {
|
|
|
1309
1765
|
this.ensureSession();
|
|
1310
1766
|
const url = params.url ?? this.state?.url ?? 'http://localhost';
|
|
1311
1767
|
const { name, value, domain, path, httpOnly, secure, sameSite, expirationDate } = params;
|
|
1312
|
-
await this.
|
|
1768
|
+
const contextId = await this.cookieContext(params);
|
|
1769
|
+
const cookie = {
|
|
1313
1770
|
name,
|
|
1314
1771
|
value,
|
|
1315
1772
|
url,
|
|
@@ -1319,40 +1776,207 @@ class SessionManager {
|
|
|
1319
1776
|
...(secure !== undefined && { secure }),
|
|
1320
1777
|
...(sameSite !== undefined && { sameSite }),
|
|
1321
1778
|
...(expirationDate !== undefined && { expires: expirationDate }),
|
|
1322
|
-
|
|
1779
|
+
...(params.partitionKey ? { partitionKey: params.partitionKey } : {}),
|
|
1780
|
+
};
|
|
1781
|
+
if (params.targetId !== undefined || params.browserContextId !== undefined) {
|
|
1782
|
+
await this.sendBrowserCommand('Storage.setCookies', {
|
|
1783
|
+
cookies: [cookie],
|
|
1784
|
+
...(contextId ? { browserContextId: contextId } : {}),
|
|
1785
|
+
});
|
|
1786
|
+
}
|
|
1787
|
+
else {
|
|
1788
|
+
const result = await this.send('Network.setCookie', cookie);
|
|
1789
|
+
if (!result.success) {
|
|
1790
|
+
throw new CDPError('Browser rejected the cookie');
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1323
1793
|
}
|
|
1324
|
-
async deleteCookie(url, name) {
|
|
1794
|
+
async deleteCookie(url, name, scope, exact) {
|
|
1325
1795
|
this.ensureSession();
|
|
1326
|
-
const
|
|
1327
|
-
|
|
1796
|
+
const contextId = await this.cookieContext(scope);
|
|
1797
|
+
let target = scope?.targetId ?? this.currentTargetId;
|
|
1798
|
+
const { targetInfo } = await this.sendBrowserCommand('Target.getTargetInfo', { targetId: target });
|
|
1799
|
+
if (scope?.browserContextId !== undefined && contextId !== targetInfo.browserContextId) {
|
|
1800
|
+
const { targetInfos } = await this.sendBrowserCommand('Target.getTargets');
|
|
1801
|
+
const selected = targetInfos.find((candidate) => candidate.type === 'page' && candidate.browserContextId === contextId);
|
|
1802
|
+
if (!selected) {
|
|
1803
|
+
throw new DriverCapabilityError('Cookie deletion requires a target in the selected browser context');
|
|
1804
|
+
}
|
|
1805
|
+
target = selected.targetId;
|
|
1806
|
+
}
|
|
1807
|
+
const cdp = this.cdp;
|
|
1808
|
+
let sid = this.targetSessions.get(target);
|
|
1809
|
+
let temporary = false;
|
|
1810
|
+
if (!sid) {
|
|
1811
|
+
sid = (await cdp.send('Target.attachToTarget', { targetId: target, flatten: true }))
|
|
1812
|
+
.sessionId;
|
|
1813
|
+
temporary = true;
|
|
1814
|
+
}
|
|
1815
|
+
let failure;
|
|
1816
|
+
let failed = false;
|
|
1817
|
+
try {
|
|
1818
|
+
exact?.onDeleteAttempt?.();
|
|
1819
|
+
await this.cdp.send('Network.deleteCookies', {
|
|
1820
|
+
name,
|
|
1821
|
+
...(exact
|
|
1822
|
+
? { domain: exact.domain, path: exact.path }
|
|
1823
|
+
: { url: url || this.state?.url || 'http://localhost' }),
|
|
1824
|
+
...(scope?.partitionKey ? { partitionKey: scope.partitionKey } : {}),
|
|
1825
|
+
}, sid);
|
|
1826
|
+
exact?.onAcknowledged?.();
|
|
1827
|
+
}
|
|
1828
|
+
catch (error) {
|
|
1829
|
+
failed = true;
|
|
1830
|
+
failure = error;
|
|
1831
|
+
}
|
|
1832
|
+
if (temporary) {
|
|
1833
|
+
try {
|
|
1834
|
+
await cdp.send('Target.detachFromTarget', { sessionId: sid }, undefined, 1000, true);
|
|
1835
|
+
}
|
|
1836
|
+
catch (error) {
|
|
1837
|
+
if (!failed) {
|
|
1838
|
+
throw error;
|
|
1839
|
+
}
|
|
1840
|
+
const original = JSON.parse(formatErrorResponse(failure).content[0].text).error;
|
|
1841
|
+
throw new StructuredToolError(original.code, original.message, original.suggestion ?? '核对 Cookie 状态与目标连接,勿自动重放清除', { ...original.context, cleanupError: JSON.parse(formatErrorResponse(error).content[0].text).error });
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
if (failed) {
|
|
1845
|
+
throw failure;
|
|
1846
|
+
}
|
|
1328
1847
|
}
|
|
1329
1848
|
async clearCookies(filter) {
|
|
1330
|
-
this.ensureSession();
|
|
1331
|
-
// Driver 级护栏:必须按 URL 或域名限定范围,name 只能进一步缩小范围
|
|
1332
1849
|
if (!filter || (!filter.url && !filter.domain)) {
|
|
1333
|
-
throw new Error('clearCookies
|
|
1850
|
+
throw new Error('clearCookies requires url or domain');
|
|
1334
1851
|
}
|
|
1335
|
-
|
|
1336
|
-
const
|
|
1337
|
-
|
|
1852
|
+
this.ensureSession();
|
|
1853
|
+
const scope = {
|
|
1854
|
+
...filter,
|
|
1855
|
+
...(filter.targetId === undefined && filter.browserContextId === undefined
|
|
1856
|
+
? { targetId: this.currentTargetId }
|
|
1857
|
+
: {}),
|
|
1858
|
+
};
|
|
1859
|
+
const cookies = await this.getCookies(scope);
|
|
1860
|
+
if (cookies.some((cookie) => 'partitionKeyOpaque' in cookie && !cookie.partitionKey)) {
|
|
1861
|
+
throw new DriverCapabilityError('Cookie 分区身份不可序列化,未执行清除');
|
|
1862
|
+
}
|
|
1863
|
+
const progress = {
|
|
1864
|
+
count: 0,
|
|
1865
|
+
matched: cookies.length,
|
|
1866
|
+
attempted: 0,
|
|
1867
|
+
acknowledged: 0,
|
|
1868
|
+
alreadyAbsent: 0,
|
|
1869
|
+
failed: 0,
|
|
1870
|
+
unknown: 0,
|
|
1871
|
+
unprocessed: cookies.length,
|
|
1872
|
+
countSemantics: 'observed_present_then_absent',
|
|
1873
|
+
};
|
|
1338
1874
|
for (const cookie of cookies) {
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1875
|
+
const partitionKey = cookie.partitionKey;
|
|
1876
|
+
const identityFilter = {
|
|
1877
|
+
...scope,
|
|
1878
|
+
name: cookie.name,
|
|
1879
|
+
domain: cookie.domain,
|
|
1880
|
+
path: cookie.path,
|
|
1881
|
+
partitionKey,
|
|
1882
|
+
};
|
|
1883
|
+
const matches = (candidate) => {
|
|
1884
|
+
const candidatePartition = candidate.partitionKey;
|
|
1885
|
+
return (candidate.name === cookie.name &&
|
|
1886
|
+
candidate.domain === cookie.domain &&
|
|
1887
|
+
candidate.path === cookie.path &&
|
|
1888
|
+
Boolean(candidatePartition) === Boolean(partitionKey) &&
|
|
1889
|
+
candidatePartition?.topLevelSite === partitionKey?.topLevelSite &&
|
|
1890
|
+
candidatePartition?.hasCrossSiteAncestor === partitionKey?.hasCrossSiteAncestor);
|
|
1891
|
+
};
|
|
1892
|
+
let phase = 'precheck';
|
|
1893
|
+
let deleteAttempted = false;
|
|
1894
|
+
let acknowledged = false;
|
|
1895
|
+
let cleanupFailure;
|
|
1896
|
+
try {
|
|
1897
|
+
this.requestContext?.()?.signal?.throwIfAborted();
|
|
1898
|
+
if (!(await this.getCookies(identityFilter)).some(matches)) {
|
|
1899
|
+
++progress.alreadyAbsent;
|
|
1900
|
+
--progress.unprocessed;
|
|
1343
1901
|
continue;
|
|
1344
1902
|
}
|
|
1903
|
+
phase = 'delete';
|
|
1904
|
+
++progress.attempted;
|
|
1905
|
+
--progress.unprocessed;
|
|
1906
|
+
try {
|
|
1907
|
+
await this.deleteCookie('', cookie.name, { ...scope, partitionKey }, {
|
|
1908
|
+
domain: cookie.domain,
|
|
1909
|
+
path: cookie.path,
|
|
1910
|
+
onDeleteAttempt: () => {
|
|
1911
|
+
deleteAttempted = true;
|
|
1912
|
+
},
|
|
1913
|
+
onAcknowledged: () => {
|
|
1914
|
+
acknowledged = true;
|
|
1915
|
+
++progress.acknowledged;
|
|
1916
|
+
},
|
|
1917
|
+
});
|
|
1918
|
+
}
|
|
1919
|
+
catch (error) {
|
|
1920
|
+
if (!acknowledged) {
|
|
1921
|
+
// noinspection ExceptionCaughtLocallyJS -- 外层按 delete 阶段保留实际清除进度
|
|
1922
|
+
throw error;
|
|
1923
|
+
}
|
|
1924
|
+
cleanupFailure = { error };
|
|
1925
|
+
}
|
|
1926
|
+
phase = 'verification';
|
|
1927
|
+
if ((await this.getCookies(identityFilter)).some(matches)) {
|
|
1928
|
+
// noinspection ExceptionCaughtLocallyJS -- 外层按 verification 阶段记录仍存在的 Cookie
|
|
1929
|
+
throw new StructuredToolError('COOKIE_STILL_PRESENT', '浏览器确认请求后仍存在相同身份的 Cookie', '读取该 Cookie 核对实际状态,勿自动重放清除', {});
|
|
1930
|
+
}
|
|
1931
|
+
++progress.count;
|
|
1932
|
+
if (cleanupFailure) {
|
|
1933
|
+
phase = 'cleanup';
|
|
1934
|
+
// noinspection ExceptionCaughtLocallyJS -- 外层同时保留已完成清除与清理失败
|
|
1935
|
+
throw cleanupFailure.error;
|
|
1936
|
+
}
|
|
1345
1937
|
}
|
|
1346
|
-
|
|
1347
|
-
|
|
1938
|
+
catch (error) {
|
|
1939
|
+
const cause = JSON.parse(formatErrorResponse(error).content[0].text).error;
|
|
1940
|
+
if (phase === 'delete') {
|
|
1941
|
+
if (!deleteAttempted ||
|
|
1942
|
+
cause.context?.actionExecuted === false ||
|
|
1943
|
+
cause.context?.protocolError === true) {
|
|
1944
|
+
++progress.failed;
|
|
1945
|
+
}
|
|
1946
|
+
else {
|
|
1947
|
+
++progress.unknown;
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
else if (phase === 'verification') {
|
|
1951
|
+
if (cause.code === 'COOKIE_STILL_PRESENT') {
|
|
1952
|
+
++progress.failed;
|
|
1953
|
+
}
|
|
1954
|
+
else {
|
|
1955
|
+
++progress.unknown;
|
|
1956
|
+
}
|
|
1957
|
+
}
|
|
1958
|
+
const actionExecuted = progress.acknowledged > 0 ? true : progress.unknown > 0 ? 'unknown' : false;
|
|
1959
|
+
throw new StructuredToolError('COOKIE_CLEAR_PARTIAL', 'Cookie 清除未全部完成', '按清除进度读取实际 Cookie 状态,勿自动重放整个清除请求', {
|
|
1960
|
+
...progress,
|
|
1961
|
+
phase,
|
|
1962
|
+
cause,
|
|
1963
|
+
...(cleanupFailure && phase !== 'cleanup'
|
|
1964
|
+
? {
|
|
1965
|
+
cleanupError: JSON.parse(formatErrorResponse(cleanupFailure.error).content[0].text)
|
|
1966
|
+
.error,
|
|
1967
|
+
}
|
|
1968
|
+
: {}),
|
|
1969
|
+
actionExecuted,
|
|
1970
|
+
actionStatus: actionExecuted === false
|
|
1971
|
+
? 'not_started'
|
|
1972
|
+
: actionExecuted === 'unknown'
|
|
1973
|
+
? 'unknown'
|
|
1974
|
+
: 'partial',
|
|
1975
|
+
retryable: false,
|
|
1976
|
+
});
|
|
1348
1977
|
}
|
|
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
1978
|
}
|
|
1355
|
-
return
|
|
1979
|
+
return progress;
|
|
1356
1980
|
}
|
|
1357
1981
|
async getConsoleLogs(options = {}) {
|
|
1358
1982
|
let logs = this.consoleLogs;
|
|
@@ -1381,7 +2005,6 @@ class SessionManager {
|
|
|
1381
2005
|
const result = requests;
|
|
1382
2006
|
if (clear) {
|
|
1383
2007
|
this.networkRequests = [];
|
|
1384
|
-
this.requestMap.clear();
|
|
1385
2008
|
}
|
|
1386
2009
|
return result;
|
|
1387
2010
|
}
|
|
@@ -1394,12 +2017,11 @@ class SessionManager {
|
|
|
1394
2017
|
clearLogs() {
|
|
1395
2018
|
this.consoleLogs = [];
|
|
1396
2019
|
this.networkRequests = [];
|
|
1397
|
-
this.requestMap.clear();
|
|
1398
2020
|
}
|
|
1399
2021
|
/**
|
|
1400
2022
|
* 执行 JavaScript
|
|
1401
2023
|
*/
|
|
1402
|
-
async evaluate(script, args, timeout) {
|
|
2024
|
+
async evaluate(script, args, timeout, userAction) {
|
|
1403
2025
|
this.ensureSession();
|
|
1404
2026
|
// CDP 命令超时需大于脚本执行超时,给 WebSocket 通信留余量
|
|
1405
2027
|
const CDP_MARGIN = 5000;
|
|
@@ -1421,9 +2043,9 @@ class SessionManager {
|
|
|
1421
2043
|
if (timeout !== undefined) {
|
|
1422
2044
|
callParams.timeout = timeout;
|
|
1423
2045
|
}
|
|
1424
|
-
const { result, exceptionDetails } = (await this.send('Runtime.callFunctionOn', callParams, sendTimeout));
|
|
2046
|
+
const { result, exceptionDetails } = (await this.send('Runtime.callFunctionOn', callParams, sendTimeout, userAction));
|
|
1425
2047
|
if (exceptionDetails) {
|
|
1426
|
-
throw new Error(formatCdpException(exceptionDetails));
|
|
2048
|
+
throw setErrorSource(new Error(formatCdpException(exceptionDetails)), 'page');
|
|
1427
2049
|
}
|
|
1428
2050
|
return extractCdpValue(result);
|
|
1429
2051
|
}
|
|
@@ -1439,9 +2061,9 @@ class SessionManager {
|
|
|
1439
2061
|
if (timeout !== undefined) {
|
|
1440
2062
|
evalParams.timeout = timeout;
|
|
1441
2063
|
}
|
|
1442
|
-
const { result, exceptionDetails } = (await this.send('Runtime.evaluate', evalParams, sendTimeout));
|
|
2064
|
+
const { result, exceptionDetails } = (await this.send('Runtime.evaluate', evalParams, sendTimeout, userAction));
|
|
1443
2065
|
if (exceptionDetails) {
|
|
1444
|
-
throw new Error(formatCdpException(exceptionDetails));
|
|
2066
|
+
throw setErrorSource(new Error(formatCdpException(exceptionDetails)), 'page');
|
|
1445
2067
|
}
|
|
1446
2068
|
return extractCdpValue(result);
|
|
1447
2069
|
}
|
|
@@ -1471,16 +2093,25 @@ class SessionManager {
|
|
|
1471
2093
|
*/
|
|
1472
2094
|
async clearCache(type = 'all') {
|
|
1473
2095
|
this.ensureSession();
|
|
2096
|
+
if (type !== 'cache') {
|
|
2097
|
+
this.ensureEventController(this.currentTargetId, this.sessionId).assertNativeReady();
|
|
2098
|
+
}
|
|
1474
2099
|
if (type === 'all' || type === 'cache') {
|
|
1475
2100
|
await this.send('Network.clearBrowserCache');
|
|
1476
2101
|
}
|
|
1477
2102
|
if (type === 'all' || type === 'storage') {
|
|
1478
|
-
await this.send('Runtime.evaluate', {
|
|
1479
|
-
expression: `
|
|
1480
|
-
localStorage.clear();
|
|
1481
|
-
sessionStorage.clear();
|
|
1482
|
-
`,
|
|
2103
|
+
const result = await this.send('Runtime.evaluate', {
|
|
2104
|
+
expression: `localStorage.clear(); sessionStorage.clear();`,
|
|
1483
2105
|
});
|
|
2106
|
+
if (result.exceptionDetails) {
|
|
2107
|
+
throw new CDPError(`Storage cleanup failed: ${formatCdpException(result.exceptionDetails)}`, {
|
|
2108
|
+
cacheCleared: type === 'all',
|
|
2109
|
+
storageStatus: 'failed_or_partial',
|
|
2110
|
+
actionExecuted: type === 'all' ? true : 'unknown',
|
|
2111
|
+
actionStatus: type === 'all' ? 'partial' : 'unknown',
|
|
2112
|
+
retryable: false,
|
|
2113
|
+
});
|
|
2114
|
+
}
|
|
1484
2115
|
}
|
|
1485
2116
|
}
|
|
1486
2117
|
/**
|
|
@@ -1489,7 +2120,7 @@ class SessionManager {
|
|
|
1489
2120
|
* IBrowserDriver 接口:可选 url 参数,url 提供时新建后立即导航
|
|
1490
2121
|
*/
|
|
1491
2122
|
async newPage(url, timeout, options = {}) {
|
|
1492
|
-
if (Object.
|
|
2123
|
+
if (Object.entries(options).some(([key, value]) => value !== undefined && key !== 'taskHint' && key !== 'note')) {
|
|
1493
2124
|
throw new DriverCapabilityError('CDP 模式不支持 Chrome UI 的 newPage 配置参数,未创建页面;请使用 Extension 模式');
|
|
1494
2125
|
}
|
|
1495
2126
|
const target = await this.withLock(async () => this.newPageInternal());
|
|
@@ -1540,7 +2171,8 @@ class SessionManager {
|
|
|
1540
2171
|
return this.withLock(async () => {
|
|
1541
2172
|
this.ensureConnected();
|
|
1542
2173
|
const targets = await this.listTargets();
|
|
1543
|
-
|
|
2174
|
+
const before = targets.find((target) => target.targetId === targetId);
|
|
2175
|
+
if (!before) {
|
|
1544
2176
|
throw new TargetNotFoundError(targetId);
|
|
1545
2177
|
}
|
|
1546
2178
|
const id = targetId;
|
|
@@ -1549,16 +2181,25 @@ class SessionManager {
|
|
|
1549
2181
|
await this.assertPageCondition(id, condition.expectedUrl, condition.expectedRevision);
|
|
1550
2182
|
this.pendingPageCondition = null;
|
|
1551
2183
|
}
|
|
2184
|
+
const sid = this.targetSessions.get(id);
|
|
2185
|
+
if (sid) {
|
|
2186
|
+
await this.eventControllers.get(sid)?.dispose('page closed');
|
|
2187
|
+
}
|
|
1552
2188
|
const result = (await this.cdp.send('Target.closeTarget', { targetId: id }));
|
|
1553
2189
|
if (!result.success) {
|
|
1554
2190
|
throw new TargetNotFoundError(targetId);
|
|
1555
2191
|
}
|
|
1556
2192
|
this.revisions.delete(id);
|
|
2193
|
+
if (sid) {
|
|
2194
|
+
this.eventControllers.delete(sid);
|
|
2195
|
+
this.targetSessions.delete(id);
|
|
2196
|
+
}
|
|
1557
2197
|
// 如果关闭的是当前页面,清除会话状态
|
|
1558
2198
|
if (id === this.currentTargetId) {
|
|
1559
2199
|
this.clearAttachedTargetState();
|
|
1560
2200
|
}
|
|
1561
2201
|
this.targetLogs.delete(id);
|
|
2202
|
+
return { targetId: id, before, after: null };
|
|
1562
2203
|
});
|
|
1563
2204
|
}
|
|
1564
2205
|
/**
|
|
@@ -1570,6 +2211,7 @@ class SessionManager {
|
|
|
1570
2211
|
* 2. 通过 withLock 串行化状态清理:等 withLock 中的操作处理完错误后再置空引用
|
|
1571
2212
|
*/
|
|
1572
2213
|
async close() {
|
|
2214
|
+
await Promise.all([...this.eventControllers.values()].map((controller) => controller.suspend('connection closing')));
|
|
1573
2215
|
// Phase 1: 立即关闭 CDP 连接(reject pending callbacks,清除 event listeners)
|
|
1574
2216
|
if (this.cdp) {
|
|
1575
2217
|
this.cdp.close();
|
|
@@ -1611,7 +2253,7 @@ class SessionManager {
|
|
|
1611
2253
|
* 多步操作(type 循环、fullPage 截图等)的 await 间隙可能被 close() 打断,
|
|
1612
2254
|
* ensureSession() 确保在当前 tick 内 this.cdp 非空
|
|
1613
2255
|
*/
|
|
1614
|
-
async send(method, params, timeout) {
|
|
2256
|
+
async send(method, params, timeout, dispatchedAction, cleanup = false) {
|
|
1615
2257
|
const deadline = timeout === undefined ? undefined : Date.now() + timeout;
|
|
1616
2258
|
this.ensureSession();
|
|
1617
2259
|
const mutation = method === 'Page.navigate' ||
|
|
@@ -1633,10 +2275,30 @@ class SessionManager {
|
|
|
1633
2275
|
this.pendingPageCondition = null;
|
|
1634
2276
|
}
|
|
1635
2277
|
const remaining = deadline === undefined ? undefined : remainingNavigationTimeout(deadline);
|
|
2278
|
+
const cleanupType = params?.type;
|
|
2279
|
+
const blocking = /^(?:Runtime\.(?:evaluate|callFunctionOn)|Input\.)/.test(method) &&
|
|
2280
|
+
!['mouseReleased', 'keyUp', 'touchEnd', 'touchCancel'].includes(cleanupType ?? '');
|
|
2281
|
+
if (blocking) {
|
|
2282
|
+
this.ensureEventController(this.currentTargetId, this.sessionId).assertNativeReady();
|
|
2283
|
+
}
|
|
1636
2284
|
if (mutation && this.currentTargetId) {
|
|
1637
2285
|
this.revisions.set(this.currentTargetId, (this.revisions.get(this.currentTargetId) ?? 0) + 1);
|
|
1638
2286
|
}
|
|
1639
|
-
|
|
2287
|
+
const frame = this.frameScopes.get(this.selectedFrame);
|
|
2288
|
+
const scoped = frame && (/^(?:Runtime|DOM|Accessibility)\./.test(method) || method === 'Input.dispatchKeyEvent');
|
|
2289
|
+
const sessionId = scoped ? frame.sessionId : this.sessionId;
|
|
2290
|
+
const nativeParams = scoped && method === 'Runtime.evaluate' ? { ...params, contextId: frame.contextId } : params;
|
|
2291
|
+
const operation = this.cdp.send(method, nativeParams, sessionId, remaining, cleanup, dispatchedAction);
|
|
2292
|
+
return blocking
|
|
2293
|
+
? this.ensureEventController(this.currentTargetId, this.sessionId)
|
|
2294
|
+
.race(operation)
|
|
2295
|
+
.catch((error) => {
|
|
2296
|
+
if (error.code === 'DIALOG_OPEN') {
|
|
2297
|
+
throw new StructuredToolError('DIALOG_OPEN', error.message, 'Read logs type=dialog and handle the observed ref; do not replay the original action', error.context);
|
|
2298
|
+
}
|
|
2299
|
+
throw error;
|
|
2300
|
+
})
|
|
2301
|
+
: operation;
|
|
1640
2302
|
}
|
|
1641
2303
|
/**
|
|
1642
2304
|
* 发送 browser-level CDP 命令(不携带 sessionId)
|
|
@@ -1649,6 +2311,65 @@ class SessionManager {
|
|
|
1649
2311
|
/**
|
|
1650
2312
|
* 派发 CDP Input.dispatchTouchEvent,临时启用 touch 模拟避免命令挂起
|
|
1651
2313
|
*/
|
|
2314
|
+
async getFrameOwnerZoom(owner, timeout) {
|
|
2315
|
+
const deadline = Date.now() + timeout;
|
|
2316
|
+
let objectId;
|
|
2317
|
+
try {
|
|
2318
|
+
const { object } = await this.cdp.send('DOM.resolveNode', { backendNodeId: owner.backendNodeId }, owner.parentSessionId, remainingNavigationTimeout(deadline));
|
|
2319
|
+
objectId = object.objectId;
|
|
2320
|
+
if (!objectId) {
|
|
2321
|
+
// noinspection ExceptionCaughtLocallyJS -- 外层统一返回 frame 几何错误
|
|
2322
|
+
throw new Error('Frame owner object is unavailable');
|
|
2323
|
+
}
|
|
2324
|
+
const { result, exceptionDetails } = await this.cdp.send('Runtime.callFunctionOn', { objectId, functionDeclaration: 'function(){return this.currentCSSZoom ?? 1}', returnByValue: true }, owner.parentSessionId, remainingNavigationTimeout(deadline));
|
|
2325
|
+
if (exceptionDetails ||
|
|
2326
|
+
typeof result.value !== 'number' ||
|
|
2327
|
+
!Number.isFinite(result.value) ||
|
|
2328
|
+
result.value <= 0) {
|
|
2329
|
+
// noinspection ExceptionCaughtLocallyJS -- 统一返回几何错误,finally 释放临时对象
|
|
2330
|
+
throw new Error('Frame owner CSS zoom is unavailable');
|
|
2331
|
+
}
|
|
2332
|
+
return result.value;
|
|
2333
|
+
}
|
|
2334
|
+
catch (error) {
|
|
2335
|
+
throw new StructuredToolError('FRAME_GEOMETRY_UNAVAILABLE', error instanceof Error ? error.message : String(error), '重新读取 frame 的文档和布局后再执行输入', { actionExecuted: false, actionStatus: 'not_started', retryable: false });
|
|
2336
|
+
}
|
|
2337
|
+
finally {
|
|
2338
|
+
if (objectId) {
|
|
2339
|
+
await this.cdp.send('Runtime.releaseObject', { objectId }, owner.parentSessionId, 1000).catch((error) => console.warn('[MCP] Frame zoom object cleanup failed:', error));
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
}
|
|
2343
|
+
ensureEventController(targetId, sessionId) {
|
|
2344
|
+
let controller = this.eventControllers.get(sessionId);
|
|
2345
|
+
if (!controller) {
|
|
2346
|
+
controller = new BrowserEventController({
|
|
2347
|
+
backend: 'cdp',
|
|
2348
|
+
targetId,
|
|
2349
|
+
owner: this.revisionEpoch,
|
|
2350
|
+
nativeSessionId: sessionId,
|
|
2351
|
+
generation: randomUUID(),
|
|
2352
|
+
}, (method, params, childSessionId) => this.cdp.send(method, params, childSessionId ?? sessionId));
|
|
2353
|
+
this.eventControllers.set(sessionId, controller);
|
|
2354
|
+
}
|
|
2355
|
+
return controller;
|
|
2356
|
+
}
|
|
2357
|
+
async cookieContext(scope) {
|
|
2358
|
+
if (scope?.storeId !== undefined) {
|
|
2359
|
+
throw new DriverCapabilityError('CookieStore IDs belong to Extension; CDP uses browserContextId');
|
|
2360
|
+
}
|
|
2361
|
+
if (scope?.partitionKey && !scope.partitionKey.topLevelSite) {
|
|
2362
|
+
throw new DriverCapabilityError('CDP partitionKey requires topLevelSite');
|
|
2363
|
+
}
|
|
2364
|
+
if (!scope?.targetId) {
|
|
2365
|
+
return scope?.browserContextId;
|
|
2366
|
+
}
|
|
2367
|
+
const { targetInfo } = await this.sendBrowserCommand('Target.getTargetInfo', { targetId: scope.targetId });
|
|
2368
|
+
if (scope.browserContextId !== undefined && scope.browserContextId !== targetInfo.browserContextId) {
|
|
2369
|
+
throw new DriverCapabilityError('Cookie target browser context does not match browserContextId');
|
|
2370
|
+
}
|
|
2371
|
+
return targetInfo.browserContextId;
|
|
2372
|
+
}
|
|
1652
2373
|
async dispatchTouch(params) {
|
|
1653
2374
|
await this.send('Emulation.setTouchEmulationEnabled', { enabled: true });
|
|
1654
2375
|
try {
|
|
@@ -1663,11 +2384,20 @@ class SessionManager {
|
|
|
1663
2384
|
}
|
|
1664
2385
|
}
|
|
1665
2386
|
}
|
|
2387
|
+
navigationTimeout(wait, timeout, deadline) {
|
|
2388
|
+
const error = new NavigationTimeoutError(wait, timeout);
|
|
2389
|
+
const scope = this.requestContext?.();
|
|
2390
|
+
if (scope?.deadline !== undefined && deadline >= scope.deadline) {
|
|
2391
|
+
scope.budgetError ??= setErrorSource(error, 'budget');
|
|
2392
|
+
}
|
|
2393
|
+
return error;
|
|
2394
|
+
}
|
|
1666
2395
|
/** 在触发导航前注册相应等待器,并按主 frame loader 过滤生命周期事件 */
|
|
1667
2396
|
startNavigationWait(wait, timeout, signal, bindFromFrameNavigation) {
|
|
1668
2397
|
this.ensureSession();
|
|
1669
2398
|
const cdp = this.cdp;
|
|
1670
2399
|
const sessionId = this.sessionId;
|
|
2400
|
+
const deadline = Date.now() + timeout;
|
|
1671
2401
|
const baselineLoaderId = this.mainFrameLoaderId;
|
|
1672
2402
|
const lifecycleName = wait === 'domcontentloaded' ? 'DOMContentLoaded' : wait === 'load' ? 'load' : 'networkIdle';
|
|
1673
2403
|
const seenLifecycle = new Set();
|
|
@@ -1803,8 +2533,8 @@ class SessionManager {
|
|
|
1803
2533
|
if (!actionStarted || eventSessionId !== sessionId) {
|
|
1804
2534
|
return;
|
|
1805
2535
|
}
|
|
1806
|
-
const requestId = params
|
|
1807
|
-
if (requestId) {
|
|
2536
|
+
const { requestId, loaderId } = params;
|
|
2537
|
+
if (requestId && loaderId !== '') {
|
|
1808
2538
|
sameDocumentPendingRequests.add(requestId);
|
|
1809
2539
|
checkSameDocumentIdle();
|
|
1810
2540
|
}
|
|
@@ -1823,7 +2553,11 @@ class SessionManager {
|
|
|
1823
2553
|
fail(signal?.reason instanceof Error ? signal.reason : new Error('导航等待已取消'));
|
|
1824
2554
|
};
|
|
1825
2555
|
const onDisconnected = () => fail(new Error('CDP 连接已关闭'));
|
|
1826
|
-
const timeoutId = setTimeout(() =>
|
|
2556
|
+
const timeoutId = setTimeout(() => {
|
|
2557
|
+
if (!settled) {
|
|
2558
|
+
fail(this.navigationTimeout(wait, timeout, deadline));
|
|
2559
|
+
}
|
|
2560
|
+
}, timeout);
|
|
1827
2561
|
cdp.onEvent('Page.frameNavigated', onFrameNavigated);
|
|
1828
2562
|
cdp.onEvent('Page.lifecycleEvent', onLifecycleEvent);
|
|
1829
2563
|
cdp.onEvent('Page.navigatedWithinDocument', onNavigatedWithinDocument);
|
|
@@ -1854,8 +2588,10 @@ class SessionManager {
|
|
|
1854
2588
|
* close() 时通过 'disconnected' 信号立即 reject
|
|
1855
2589
|
*/
|
|
1856
2590
|
buildNetworkIdlePromise(cdp, timeout, idleTime, signal) {
|
|
1857
|
-
|
|
2591
|
+
// CDP 用空 loaderId 标识 Worker 请求,页面 session 可能只收到其开始事件
|
|
2592
|
+
const localPendingRequests = new Set([...this.requestMap].filter(([, request]) => request.loaderId !== '').map(([requestId]) => requestId));
|
|
1858
2593
|
const sessionId = this.sessionId;
|
|
2594
|
+
const deadline = Date.now() + timeout;
|
|
1859
2595
|
return new Promise((resolve, reject) => {
|
|
1860
2596
|
let idleTimer = null;
|
|
1861
2597
|
let timeoutTimer = null;
|
|
@@ -1879,7 +2615,10 @@ class SessionManager {
|
|
|
1879
2615
|
if (eventSessionId !== sessionId) {
|
|
1880
2616
|
return;
|
|
1881
2617
|
}
|
|
1882
|
-
const { requestId } = params;
|
|
2618
|
+
const { requestId, loaderId } = params;
|
|
2619
|
+
if (loaderId === '') {
|
|
2620
|
+
return;
|
|
2621
|
+
}
|
|
1883
2622
|
localPendingRequests.add(requestId);
|
|
1884
2623
|
checkIdle();
|
|
1885
2624
|
};
|
|
@@ -1910,7 +2649,7 @@ class SessionManager {
|
|
|
1910
2649
|
};
|
|
1911
2650
|
timeoutTimer = setTimeout(() => {
|
|
1912
2651
|
cleanup();
|
|
1913
|
-
reject(
|
|
2652
|
+
reject(this.navigationTimeout('networkidle', timeout, deadline));
|
|
1914
2653
|
}, timeout);
|
|
1915
2654
|
const onDisconnected = () => {
|
|
1916
2655
|
cleanup();
|
|
@@ -1937,28 +2676,22 @@ class SessionManager {
|
|
|
1937
2676
|
if (this.currentTargetId === targetId && this.sessionId) {
|
|
1938
2677
|
return;
|
|
1939
2678
|
}
|
|
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
|
-
}
|
|
2679
|
+
if (!this.targetSessions.has(targetId) && this.targetSessions.size >= 32) {
|
|
2680
|
+
throw new DriverCapabilityError('CDP observed page capacity reached (32); close unused pages before attaching');
|
|
1950
2681
|
}
|
|
1951
2682
|
this.clearAttachedTargetState();
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
targetId,
|
|
1955
|
-
|
|
1956
|
-
|
|
2683
|
+
let sessionId = this.targetSessions.get(targetId);
|
|
2684
|
+
if (!sessionId) {
|
|
2685
|
+
const attached = await this.sendBrowserCommand('Target.attachToTarget', { targetId, flatten: true }, deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
|
|
2686
|
+
sessionId = attached.sessionId;
|
|
2687
|
+
this.targetSessions.set(targetId, sessionId);
|
|
2688
|
+
}
|
|
1957
2689
|
this.sessionId = sessionId;
|
|
1958
2690
|
this.currentTargetId = targetId;
|
|
1959
2691
|
const logs = this.targetLogs.get(targetId);
|
|
1960
2692
|
this.consoleLogs = logs?.console ?? [];
|
|
1961
2693
|
this.networkRequests = logs?.network ?? [];
|
|
2694
|
+
this.requestMap = logs?.requests ?? new Map();
|
|
1962
2695
|
// 初始化会话
|
|
1963
2696
|
await this.initSession(deadline);
|
|
1964
2697
|
}
|
|
@@ -2002,20 +2735,32 @@ class SessionManager {
|
|
|
2002
2735
|
}
|
|
2003
2736
|
clearAttachedTargetState() {
|
|
2004
2737
|
if (this.currentTargetId) {
|
|
2005
|
-
this.targetLogs.set(this.currentTargetId, {
|
|
2738
|
+
this.targetLogs.set(this.currentTargetId, {
|
|
2739
|
+
console: this.consoleLogs,
|
|
2740
|
+
network: this.networkRequests,
|
|
2741
|
+
requests: this.requestMap,
|
|
2742
|
+
});
|
|
2006
2743
|
}
|
|
2007
2744
|
this.consoleLogs = [];
|
|
2008
2745
|
this.networkRequests = [];
|
|
2009
|
-
this.requestMap
|
|
2746
|
+
this.requestMap = new Map();
|
|
2010
2747
|
this.challengeRequired = false;
|
|
2011
2748
|
this.runtimeEnabled = false;
|
|
2012
2749
|
this.mainFrameId = null;
|
|
2013
2750
|
this.mainFrameLoaderId = null;
|
|
2014
2751
|
this.modifiers = 0;
|
|
2015
2752
|
this.sessionId = null;
|
|
2753
|
+
this.selectedFrame = 0;
|
|
2016
2754
|
this.currentTargetId = null;
|
|
2017
2755
|
this.state = null;
|
|
2018
2756
|
}
|
|
2757
|
+
networkState(eventSessionId) {
|
|
2758
|
+
if (this.isCurrentSessionEvent(eventSessionId)) {
|
|
2759
|
+
return { network: this.networkRequests, requests: this.requestMap };
|
|
2760
|
+
}
|
|
2761
|
+
const targetId = [...this.targetSessions].find(([, sid]) => sid === eventSessionId)?.[0];
|
|
2762
|
+
return targetId ? this.targetLogs.get(targetId) : undefined;
|
|
2763
|
+
}
|
|
2019
2764
|
isCurrentSessionEvent(eventSessionId) {
|
|
2020
2765
|
return this.sessionId !== null && eventSessionId === this.sessionId;
|
|
2021
2766
|
}
|
|
@@ -2035,6 +2780,16 @@ class SessionManager {
|
|
|
2035
2780
|
this.launcher = null;
|
|
2036
2781
|
}
|
|
2037
2782
|
this.clearAttachedTargetState();
|
|
2783
|
+
for (const controller of this.eventControllers.values()) {
|
|
2784
|
+
void controller.dispose('connection closed').catch(() => { });
|
|
2785
|
+
}
|
|
2786
|
+
this.eventControllers.clear();
|
|
2787
|
+
this.targetSessions.clear();
|
|
2788
|
+
this.childSessions.clear();
|
|
2789
|
+
this.frameSessions.clear();
|
|
2790
|
+
this.contexts.clear();
|
|
2791
|
+
this.frameScopes.clear();
|
|
2792
|
+
this.selectedFrame = 0;
|
|
2038
2793
|
this.targetLogs.clear();
|
|
2039
2794
|
this.revisionEpoch = randomUUID();
|
|
2040
2795
|
this.revisions.clear();
|
|
@@ -2047,6 +2802,8 @@ class SessionManager {
|
|
|
2047
2802
|
* 串行执行操作(防止并发竞态)
|
|
2048
2803
|
*/
|
|
2049
2804
|
async withLock(fn, deadline) {
|
|
2805
|
+
const signal = this.requestContext?.()?.signal;
|
|
2806
|
+
signal?.throwIfAborted();
|
|
2050
2807
|
const previousLock = this.operationLock;
|
|
2051
2808
|
let releaseLock;
|
|
2052
2809
|
this.operationLock = new Promise((resolve) => {
|
|
@@ -2054,8 +2811,9 @@ class SessionManager {
|
|
|
2054
2811
|
});
|
|
2055
2812
|
let acquired = false;
|
|
2056
2813
|
try {
|
|
2057
|
-
await waitForNavigationQueue(previousLock, deadline);
|
|
2814
|
+
await waitForNavigationQueue(previousLock, deadline, signal);
|
|
2058
2815
|
acquired = true;
|
|
2816
|
+
signal?.throwIfAborted();
|
|
2059
2817
|
return await fn();
|
|
2060
2818
|
}
|
|
2061
2819
|
catch (error) {
|
|
@@ -2086,7 +2844,9 @@ class SessionManager {
|
|
|
2086
2844
|
* 接受完成事件后清理所有监听器和超时定时器
|
|
2087
2845
|
* close() 时通过 'disconnected' 信号立即 reject,不必等 timer 超时
|
|
2088
2846
|
*/
|
|
2089
|
-
waitForAnyEvent(events, timeout) {
|
|
2847
|
+
waitForAnyEvent(events, timeout, signal = this.requestContext?.()?.signal) {
|
|
2848
|
+
const deadline = Date.now() + timeout;
|
|
2849
|
+
signal?.throwIfAborted();
|
|
2090
2850
|
// 捕获当前 cdp 引用,防止 close() 并发置 null 导致回调崩溃
|
|
2091
2851
|
const cdp = this.cdp;
|
|
2092
2852
|
const sessionId = this.sessionId;
|
|
@@ -2097,20 +2857,30 @@ class SessionManager {
|
|
|
2097
2857
|
const listeners = [];
|
|
2098
2858
|
const cleanup = () => {
|
|
2099
2859
|
clearTimeout(timer);
|
|
2860
|
+
signal?.removeEventListener('abort', onAbort);
|
|
2100
2861
|
for (const { event, listener } of listeners) {
|
|
2101
2862
|
cdp.offEvent(event, listener);
|
|
2102
2863
|
}
|
|
2103
2864
|
cdp.removeListener('disconnected', onDisconnected);
|
|
2104
2865
|
};
|
|
2866
|
+
const onAbort = () => {
|
|
2867
|
+
cleanup();
|
|
2868
|
+
reject(signal?.reason ?? new Error('Request cancelled'));
|
|
2869
|
+
};
|
|
2105
2870
|
const timer = setTimeout(() => {
|
|
2106
2871
|
cleanup();
|
|
2107
|
-
reject(
|
|
2872
|
+
reject(this.navigationTimeout('navigation', timeout, deadline));
|
|
2108
2873
|
}, timeout);
|
|
2109
2874
|
const onDisconnected = () => {
|
|
2110
2875
|
cleanup();
|
|
2111
2876
|
reject(new Error('CDP 连接已关闭'));
|
|
2112
2877
|
};
|
|
2113
2878
|
cdp.once('disconnected', onDisconnected);
|
|
2879
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
2880
|
+
if (signal?.aborted) {
|
|
2881
|
+
onAbort();
|
|
2882
|
+
return;
|
|
2883
|
+
}
|
|
2114
2884
|
for (const event of events) {
|
|
2115
2885
|
const listener = (params, eventSessionId) => {
|
|
2116
2886
|
if (eventSessionId !== sessionId) {
|
|
@@ -2141,6 +2911,8 @@ class SessionManager {
|
|
|
2141
2911
|
*/
|
|
2142
2912
|
async initSession(deadline) {
|
|
2143
2913
|
const remaining = () => (deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
|
|
2914
|
+
this.setupEventListeners();
|
|
2915
|
+
this.ensureEventController(this.currentTargetId, this.sessionId);
|
|
2144
2916
|
// 启用必要的域
|
|
2145
2917
|
await Promise.all([
|
|
2146
2918
|
this.send('Page.enable', undefined, remaining()),
|
|
@@ -2172,22 +2944,95 @@ class SessionManager {
|
|
|
2172
2944
|
return;
|
|
2173
2945
|
}
|
|
2174
2946
|
this.listenersInstalled = true;
|
|
2947
|
+
for (const method of BROWSER_EVENT_METHODS) {
|
|
2948
|
+
this.cdp.onEvent(method, (params, sid) => {
|
|
2949
|
+
const root = sid && (this.childSessions.get(sid) ?? sid);
|
|
2950
|
+
if (root) {
|
|
2951
|
+
this.eventControllers.get(root)?.handle(method, params, sid);
|
|
2952
|
+
}
|
|
2953
|
+
});
|
|
2954
|
+
}
|
|
2955
|
+
this.cdp.onEvent('Runtime.executionContextCreated', (raw, sid) => {
|
|
2956
|
+
const c = raw.context;
|
|
2957
|
+
if (sid && c.auxData?.frameId) {
|
|
2958
|
+
const contexts = this.contexts.get(sid) ?? [];
|
|
2959
|
+
contexts.push({ id: c.id, frameId: c.auxData.frameId, isDefault: c.auxData.isDefault === true });
|
|
2960
|
+
this.contexts.set(sid, contexts);
|
|
2961
|
+
}
|
|
2962
|
+
});
|
|
2963
|
+
this.cdp.onEvent('Runtime.executionContextDestroyed', (raw, sid) => {
|
|
2964
|
+
if (sid) {
|
|
2965
|
+
this.contexts.set(sid, (this.contexts.get(sid) ?? []).filter((c) => c.id !== raw.executionContextId));
|
|
2966
|
+
}
|
|
2967
|
+
});
|
|
2968
|
+
this.cdp.onEvent('Runtime.executionContextsCleared', (_, sid) => {
|
|
2969
|
+
if (sid) {
|
|
2970
|
+
this.contexts.delete(sid);
|
|
2971
|
+
}
|
|
2972
|
+
});
|
|
2973
|
+
this.cdp.onEvent('Target.attachedToTarget', (raw, parent) => {
|
|
2974
|
+
const p = raw;
|
|
2975
|
+
if (!parent || p.targetInfo.type !== 'iframe') {
|
|
2976
|
+
return;
|
|
2977
|
+
}
|
|
2978
|
+
const root = this.childSessions.get(parent) ?? parent;
|
|
2979
|
+
this.childSessions.set(p.sessionId, root);
|
|
2980
|
+
this.frameSessions.set(p.targetInfo.targetId, p.sessionId);
|
|
2981
|
+
void (async () => {
|
|
2982
|
+
await this.cdp.send('Runtime.enable', {}, p.sessionId);
|
|
2983
|
+
await this.cdp.send('Target.setAutoAttach', {
|
|
2984
|
+
autoAttach: true,
|
|
2985
|
+
waitForDebuggerOnStart: false,
|
|
2986
|
+
flatten: true,
|
|
2987
|
+
filter: [{ type: 'iframe', exclude: false }],
|
|
2988
|
+
}, p.sessionId);
|
|
2989
|
+
})().catch((error) => console.warn('[MCP] OOPIF context setup failed:', error));
|
|
2990
|
+
});
|
|
2991
|
+
this.cdp.onEvent('Target.detachedFromTarget', (raw) => {
|
|
2992
|
+
const sid = raw.sessionId;
|
|
2993
|
+
for (const [targetId, session] of this.targetSessions) {
|
|
2994
|
+
if (session !== sid) {
|
|
2995
|
+
continue;
|
|
2996
|
+
}
|
|
2997
|
+
const controller = this.eventControllers.get(sid);
|
|
2998
|
+
this.targetSessions.delete(targetId);
|
|
2999
|
+
this.eventControllers.delete(sid);
|
|
3000
|
+
if (this.currentTargetId === targetId) {
|
|
3001
|
+
this.clearAttachedTargetState();
|
|
3002
|
+
}
|
|
3003
|
+
this.targetLogs.delete(targetId);
|
|
3004
|
+
if (controller) {
|
|
3005
|
+
void controller
|
|
3006
|
+
.dispose('native target detached')
|
|
3007
|
+
.catch((error) => console.warn('[MCP] Native target event cleanup outcome:', error));
|
|
3008
|
+
}
|
|
3009
|
+
}
|
|
3010
|
+
this.contexts.delete(sid);
|
|
3011
|
+
this.childSessions.delete(sid);
|
|
3012
|
+
for (const [id, session] of this.frameSessions) {
|
|
3013
|
+
if (session === sid) {
|
|
3014
|
+
this.frameSessions.delete(id);
|
|
3015
|
+
}
|
|
3016
|
+
}
|
|
3017
|
+
});
|
|
2175
3018
|
this.cdp.onEvent('Page.frameNavigated', (params, eventSessionId) => {
|
|
2176
|
-
|
|
3019
|
+
const targetId = [...this.targetSessions].find(([, sid]) => sid === eventSessionId)?.[0];
|
|
3020
|
+
if (!targetId) {
|
|
2177
3021
|
return;
|
|
2178
3022
|
}
|
|
2179
3023
|
const frame = params.frame;
|
|
2180
3024
|
if (frame?.id && !frame.parentId) {
|
|
2181
|
-
this.
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
this.revisions.set(this.currentTargetId, (this.revisions.get(this.currentTargetId) ?? 0) + 1);
|
|
3025
|
+
if (targetId === this.currentTargetId) {
|
|
3026
|
+
this.mainFrameId = frame.id;
|
|
3027
|
+
this.mainFrameLoaderId = frame.loaderId ?? null;
|
|
2185
3028
|
}
|
|
3029
|
+
this.revisions.set(targetId, (this.revisions.get(targetId) ?? 0) + 1);
|
|
2186
3030
|
}
|
|
2187
3031
|
});
|
|
2188
3032
|
this.cdp.onEvent('Page.navigatedWithinDocument', (_params, eventSessionId) => {
|
|
2189
|
-
|
|
2190
|
-
|
|
3033
|
+
const targetId = [...this.targetSessions].find(([, sid]) => sid === eventSessionId)?.[0];
|
|
3034
|
+
if (targetId) {
|
|
3035
|
+
this.revisions.set(targetId, (this.revisions.get(targetId) ?? 0) + 1);
|
|
2191
3036
|
}
|
|
2192
3037
|
});
|
|
2193
3038
|
// 控制台日志
|
|
@@ -2209,30 +3054,53 @@ class SessionManager {
|
|
|
2209
3054
|
this.consoleLogs.splice(0, this.consoleLogs.length - 800);
|
|
2210
3055
|
}
|
|
2211
3056
|
});
|
|
3057
|
+
this.cdp.onEvent('Runtime.exceptionThrown', (params, eventSessionId) => {
|
|
3058
|
+
if (!this.isCurrentSessionEvent(eventSessionId)) {
|
|
3059
|
+
return;
|
|
3060
|
+
}
|
|
3061
|
+
const p = params;
|
|
3062
|
+
this.consoleLogs.push({
|
|
3063
|
+
sequence: ++this.nextConsoleLogSequence,
|
|
3064
|
+
source: 'javascript',
|
|
3065
|
+
level: 'error',
|
|
3066
|
+
text: formatCdpException(p.exceptionDetails),
|
|
3067
|
+
timestamp: Math.round(p.timestamp),
|
|
3068
|
+
url: p.exceptionDetails.url,
|
|
3069
|
+
lineNumber: p.exceptionDetails.lineNumber,
|
|
3070
|
+
});
|
|
3071
|
+
if (this.consoleLogs.length > SessionManager.MAX_LOG_ENTRIES) {
|
|
3072
|
+
this.consoleLogs.splice(0, this.consoleLogs.length - 800);
|
|
3073
|
+
}
|
|
3074
|
+
});
|
|
2212
3075
|
// 网络请求
|
|
2213
3076
|
this.cdp.onEvent('Network.requestWillBeSent', (params, eventSessionId) => {
|
|
2214
|
-
|
|
3077
|
+
const state = this.networkState(eventSessionId);
|
|
3078
|
+
if (!state) {
|
|
2215
3079
|
return;
|
|
2216
3080
|
}
|
|
2217
3081
|
const p = params;
|
|
2218
|
-
|
|
3082
|
+
state.requests.set(p.requestId, {
|
|
2219
3083
|
url: p.request.url,
|
|
2220
3084
|
method: p.request.method,
|
|
2221
3085
|
type: p.type,
|
|
2222
3086
|
timestamp: Math.round(p.wallTime * 1000), // wallTime 是 epoch 秒 → epoch 毫秒
|
|
2223
3087
|
frameId: p.frameId,
|
|
3088
|
+
loaderId: p.loaderId,
|
|
2224
3089
|
_monotonic: p.timestamp, // MonotonicTime 用于 duration 计算
|
|
2225
3090
|
});
|
|
2226
3091
|
});
|
|
2227
3092
|
this.cdp.onEvent('Network.responseReceived', (params, eventSessionId) => {
|
|
2228
|
-
|
|
3093
|
+
const state = this.networkState(eventSessionId);
|
|
3094
|
+
if (!state) {
|
|
2229
3095
|
return;
|
|
2230
3096
|
}
|
|
2231
3097
|
const p = params;
|
|
2232
|
-
const request =
|
|
3098
|
+
const request = state.requests.get(p.requestId);
|
|
2233
3099
|
if (request) {
|
|
2234
3100
|
const challenge = isCloudflareChallenge(p.response.headers);
|
|
2235
|
-
if (
|
|
3101
|
+
if (this.isCurrentSessionEvent(eventSessionId) &&
|
|
3102
|
+
request.type.toLowerCase() === 'document' &&
|
|
3103
|
+
request.frameId === this.mainFrameId) {
|
|
2236
3104
|
// 仅新的主文档响应可以解除已知 Challenge,清空日志不能解除该状态
|
|
2237
3105
|
this.challengeRequired = challenge;
|
|
2238
3106
|
}
|
|
@@ -2242,26 +3110,28 @@ class SessionManager {
|
|
|
2242
3110
|
});
|
|
2243
3111
|
// 网络请求失败时写入日志再清理 requestMap,防止 diagnostics 丢失失败请求
|
|
2244
3112
|
const finalizeRequest = (params, eventSessionId) => {
|
|
2245
|
-
|
|
3113
|
+
const state = this.networkState(eventSessionId);
|
|
3114
|
+
if (!state) {
|
|
2246
3115
|
return;
|
|
2247
3116
|
}
|
|
2248
3117
|
const p = params;
|
|
2249
|
-
const request =
|
|
3118
|
+
const request = state.requests.get(p.requestId);
|
|
2250
3119
|
if (request) {
|
|
2251
3120
|
const { _monotonic, ...requestData } = request;
|
|
2252
3121
|
delete requestData.frameId;
|
|
2253
|
-
|
|
3122
|
+
delete requestData.loaderId;
|
|
3123
|
+
state.network.push({
|
|
2254
3124
|
sequence: ++this.nextNetworkRequestSequence,
|
|
2255
3125
|
...requestData,
|
|
2256
3126
|
type: p.type ?? requestData.type,
|
|
2257
3127
|
errorText: p.errorText,
|
|
2258
3128
|
duration: Math.round((p.timestamp - _monotonic) * 1000),
|
|
2259
3129
|
});
|
|
2260
|
-
if (
|
|
2261
|
-
|
|
3130
|
+
if (state.network.length > SessionManager.MAX_LOG_ENTRIES) {
|
|
3131
|
+
state.network.splice(0, state.network.length - 800);
|
|
2262
3132
|
}
|
|
2263
3133
|
}
|
|
2264
|
-
|
|
3134
|
+
state.requests.delete(p.requestId);
|
|
2265
3135
|
};
|
|
2266
3136
|
this.cdp.onEvent('Network.loadingFinished', finalizeRequest);
|
|
2267
3137
|
this.cdp.onEvent('Network.loadingFailed', finalizeRequest);
|