@pyrokine/mcp-chrome 2.4.1 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +546 -192
- package/README_zh.md +490 -192
- package/dist/anti-detection/behavior.js +1 -1
- package/dist/anti-detection/behavior.js.map +1 -1
- package/dist/anti-detection/injection.d.ts.map +1 -1
- package/dist/anti-detection/injection.js +5 -4
- package/dist/anti-detection/injection.js.map +1 -1
- package/dist/cdp/client.d.ts +2 -2
- package/dist/cdp/client.d.ts.map +1 -1
- package/dist/cdp/client.js +24 -10
- package/dist/cdp/client.js.map +1 -1
- package/dist/cdp/launcher.d.ts +2 -3
- package/dist/cdp/launcher.d.ts.map +1 -1
- package/dist/cdp/launcher.js +84 -24
- package/dist/cdp/launcher.js.map +1 -1
- package/dist/core/auto-wait.d.ts +3 -3
- package/dist/core/auto-wait.d.ts.map +1 -1
- package/dist/core/auto-wait.js +45 -20
- package/dist/core/auto-wait.js.map +1 -1
- package/dist/core/browser-driver.d.ts +104 -14
- package/dist/core/browser-driver.d.ts.map +1 -1
- package/dist/core/browser-driver.js +1 -0
- package/dist/core/browser-driver.js.map +1 -1
- package/dist/core/errors.d.ts +25 -0
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/errors.js +93 -1
- package/dist/core/errors.js.map +1 -1
- package/dist/core/locator.d.ts.map +1 -1
- package/dist/core/locator.js +6 -4
- package/dist/core/locator.js.map +1 -1
- package/dist/core/os-mouse.d.ts +78 -0
- package/dist/core/os-mouse.d.ts.map +1 -0
- package/dist/core/os-mouse.js +378 -0
- package/dist/core/os-mouse.js.map +1 -0
- package/dist/core/session.d.ts +46 -21
- package/dist/core/session.d.ts.map +1 -1
- package/dist/core/session.js +724 -175
- package/dist/core/session.js.map +1 -1
- package/dist/core/types.d.ts +12 -0
- package/dist/core/types.d.ts.map +1 -1
- package/dist/core/types.js +2 -0
- package/dist/core/types.js.map +1 -1
- package/dist/core/unified-session.d.ts +117 -21
- package/dist/core/unified-session.d.ts.map +1 -1
- package/dist/core/unified-session.js +619 -129
- package/dist/core/unified-session.js.map +1 -1
- package/dist/core/utils.d.ts +5 -0
- package/dist/core/utils.d.ts.map +1 -1
- package/dist/core/utils.js +475 -54
- package/dist/core/utils.js.map +1 -1
- package/dist/extension/bridge.d.ts +61 -35
- package/dist/extension/bridge.d.ts.map +1 -1
- package/dist/extension/bridge.js +290 -106
- package/dist/extension/bridge.js.map +1 -1
- package/dist/extension/http-server.d.ts +3 -0
- package/dist/extension/http-server.d.ts.map +1 -1
- package/dist/extension/http-server.js +25 -3
- package/dist/extension/http-server.js.map +1 -1
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -1
- package/dist/tools/browse.d.ts +1 -1
- package/dist/tools/browse.d.ts.map +1 -1
- package/dist/tools/browse.js +291 -175
- package/dist/tools/browse.js.map +1 -1
- package/dist/tools/challenge.d.ts +153 -0
- package/dist/tools/challenge.d.ts.map +1 -0
- package/dist/tools/challenge.js +611 -0
- package/dist/tools/challenge.js.map +1 -0
- package/dist/tools/cookies.d.ts.map +1 -1
- package/dist/tools/cookies.js +13 -7
- package/dist/tools/cookies.js.map +1 -1
- package/dist/tools/diagnostics.d.ts +5 -5
- package/dist/tools/diagnostics.d.ts.map +1 -1
- package/dist/tools/diagnostics.js +39 -20
- package/dist/tools/diagnostics.js.map +1 -1
- package/dist/tools/evaluate.d.ts.map +1 -1
- package/dist/tools/evaluate.js +106 -23
- package/dist/tools/evaluate.js.map +1 -1
- package/dist/tools/extract.d.ts.map +1 -1
- package/dist/tools/extract.js +199 -208
- package/dist/tools/extract.js.map +1 -1
- package/dist/tools/input.d.ts +1 -1
- package/dist/tools/input.d.ts.map +1 -1
- package/dist/tools/input.js +523 -175
- package/dist/tools/input.js.map +1 -1
- package/dist/tools/logs.d.ts.map +1 -1
- package/dist/tools/logs.js +7 -7
- package/dist/tools/logs.js.map +1 -1
- package/dist/tools/manage.d.ts.map +1 -1
- package/dist/tools/manage.js +400 -64
- package/dist/tools/manage.js.map +1 -1
- package/dist/tools/network-sanitizer.d.ts.map +1 -1
- package/dist/tools/network-sanitizer.js +1 -0
- package/dist/tools/network-sanitizer.js.map +1 -1
- package/dist/tools/page-context.d.ts +17 -0
- package/dist/tools/page-context.d.ts.map +1 -0
- package/dist/tools/page-context.js +103 -0
- package/dist/tools/page-context.js.map +1 -0
- package/dist/tools/png.d.ts +5 -0
- package/dist/tools/png.d.ts.map +1 -1
- package/dist/tools/png.js +89 -22
- package/dist/tools/png.js.map +1 -1
- package/dist/tools/post-condition.d.ts.map +1 -1
- package/dist/tools/post-condition.js +17 -5
- package/dist/tools/post-condition.js.map +1 -1
- package/dist/tools/schema.d.ts +9 -0
- package/dist/tools/schema.d.ts.map +1 -1
- package/dist/tools/schema.js +15 -0
- package/dist/tools/schema.js.map +1 -1
- package/dist/tools/target-diagnostics.d.ts +7 -0
- package/dist/tools/target-diagnostics.d.ts.map +1 -1
- package/dist/tools/target-diagnostics.js +47 -17
- package/dist/tools/target-diagnostics.js.map +1 -1
- package/dist/tools/wait.d.ts.map +1 -1
- package/dist/tools/wait.js +52 -56
- package/dist/tools/wait.js.map +1 -1
- package/extension/dist/assets/content.ts-C4imZ6A9.js +13 -0
- package/extension/dist/assets/content.ts-loader-CnJuCGhl.js +13 -0
- package/extension/dist/assets/{index.ts-GG6dPUPX.js → index.ts-GeHNZBml.js} +2156 -1950
- package/extension/dist/assets/page-scripts-CMIY1zhd.js +1379 -0
- package/extension/dist/assets/{popup.html-B81xccfq.js → popup.html-CgtWL6Py.js} +48 -1
- package/extension/dist/manifest.json +4 -3
- package/extension/dist/service-worker-loader.js +1 -1
- package/extension/dist/src/popup/popup.html +54 -44
- package/package.json +11 -8
- package/scripts/start-chrome.ps1 +58 -0
- package/dist/extension/native-host-installer.d.ts +0 -21
- package/dist/extension/native-host-installer.d.ts.map +0 -1
- package/dist/extension/native-host-installer.js +0 -147
- package/dist/extension/native-host-installer.js.map +0 -1
- package/dist/extension/socket-server.d.ts +0 -32
- package/dist/extension/socket-server.d.ts.map +0 -1
- package/dist/extension/socket-server.js +0 -177
- package/dist/extension/socket-server.js.map +0 -1
- package/dist/extension/ws-server.d.ts +0 -40
- package/dist/extension/ws-server.d.ts.map +0 -1
- package/dist/extension/ws-server.js +0 -246
- package/dist/extension/ws-server.js.map +0 -1
- package/dist/native-host/index.js +0 -280
- package/dist/native-host/mcp-chrome-host +0 -2
- package/extension/dist/assets/content.ts-Cj_iiU2s.js +0 -25
|
@@ -5,10 +5,15 @@
|
|
|
5
5
|
* 1. Extension 模式:通过 Chrome Extension 操作用户浏览器(推荐)
|
|
6
6
|
* 2. CDP 模式:通过 Chrome DevTools Protocol 操作(Fallback)
|
|
7
7
|
*/
|
|
8
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
8
9
|
import { ExtensionBridge } from '../extension/index.js';
|
|
9
10
|
import { DriverCapabilityError, } from './browser-driver.js';
|
|
11
|
+
import { OsMouseError, PagePreconditionError, setErrorPageContext, StructuredToolError, TargetNotFoundError, TimeoutError, } from './errors.js';
|
|
10
12
|
import { isExtensionDisconnected } from './extension-errors.js';
|
|
13
|
+
import { asViewportMetrics, osLeftClick, resolveTurnstileOsClickPoint, } from './os-mouse.js';
|
|
11
14
|
import { getKeyDefinition, getSession as getCdpSession } from './session.js';
|
|
15
|
+
import { DEFAULT_TIMEOUT } from './types.js';
|
|
16
|
+
import { remainingNavigationTimeout, waitForNavigationQueue, withNavigationBudget } from './utils.js';
|
|
12
17
|
import { EvaluateResultTooLargeError, extractCdpValue, formatCdpException, isKnownNonSerializableRemoteObject, MODIFIER_KEYS, NonSerializableEvaluateResultError, } from './types.js';
|
|
13
18
|
class UnifiedSessionManager {
|
|
14
19
|
static instance;
|
|
@@ -16,6 +21,7 @@ class UnifiedSessionManager {
|
|
|
16
21
|
static CDP_MATERIALIZE_MAX_DEPTH = 8;
|
|
17
22
|
static CDP_MATERIALIZE_MAX_NODES = 2000;
|
|
18
23
|
static CDP_MATERIALIZE_MAX_CHARS = 1_000_000;
|
|
24
|
+
static CDP_MATERIALIZE_MAX_FILE_CHARS = 16 * 1024 * 1024;
|
|
19
25
|
extensionBridge = null;
|
|
20
26
|
inputMode = 'precise'; // 默认使用 precise 模式,可绕过 CSP 限制
|
|
21
27
|
currentMousePosition = { x: 0, y: 0 }; // 跟踪鼠标位置
|
|
@@ -25,10 +31,15 @@ class UnifiedSessionManager {
|
|
|
25
31
|
pressedKeys = new Set();
|
|
26
32
|
lastConnectionFailure = 0;
|
|
27
33
|
activeMode = null;
|
|
34
|
+
cdpExplicitlySelected = false;
|
|
35
|
+
extensionChallengeStateUnsupported = false;
|
|
36
|
+
unsupportedChallengeStateBundleHash = null;
|
|
28
37
|
tabSwitchLock = Promise.resolve(); // 串行化 tab 切换,防止并发竞态
|
|
38
|
+
tabLockContext = new AsyncLocalStorage();
|
|
29
39
|
requireExtension = false; // 指定 tabId 或 frame 时为 true,禁止 CDP 回退
|
|
30
40
|
currentFrameOffset = null; // iframe 在主页面的偏移量(withFrame 期间有效)
|
|
31
41
|
lastEvaluationMetadata;
|
|
42
|
+
pageMetadata = new Map();
|
|
32
43
|
constructor() { }
|
|
33
44
|
static getInstance() {
|
|
34
45
|
if (!UnifiedSessionManager.instance) {
|
|
@@ -60,22 +71,24 @@ class UnifiedSessionManager {
|
|
|
60
71
|
if (this.activeMode === 'extension' && this.extensionBridge?.isConnected()) {
|
|
61
72
|
return 'extension';
|
|
62
73
|
}
|
|
63
|
-
if (this.activeMode === 'cdp' && getCdpSession().isConnected()) {
|
|
74
|
+
if (this.activeMode === 'cdp' && this.cdpExplicitlySelected && getCdpSession().isConnected()) {
|
|
64
75
|
return 'cdp';
|
|
65
76
|
}
|
|
66
|
-
this.activeMode = null;
|
|
67
77
|
if (this.extensionBridge?.isConnected()) {
|
|
68
78
|
this.activeMode = 'extension';
|
|
79
|
+
this.cdpExplicitlySelected = false;
|
|
69
80
|
return 'extension';
|
|
70
81
|
}
|
|
71
82
|
if (getCdpSession().isConnected()) {
|
|
72
83
|
this.activeMode = 'cdp';
|
|
73
84
|
return 'cdp';
|
|
74
85
|
}
|
|
86
|
+
this.activeMode = null;
|
|
75
87
|
return 'none';
|
|
76
88
|
}
|
|
77
|
-
setActiveMode(mode) {
|
|
89
|
+
setActiveMode(mode, cdpExplicitlySelected = false) {
|
|
78
90
|
this.activeMode = mode;
|
|
91
|
+
this.cdpExplicitlySelected = mode === 'cdp' && cdpExplicitlySelected;
|
|
79
92
|
}
|
|
80
93
|
/**
|
|
81
94
|
* 获取当前输入模式
|
|
@@ -93,6 +106,35 @@ class UnifiedSessionManager {
|
|
|
93
106
|
}
|
|
94
107
|
return null;
|
|
95
108
|
}
|
|
109
|
+
getPageMetadata(targetId) {
|
|
110
|
+
return (this.pageMetadata.get(this.metadataKey(targetId)) ?? {
|
|
111
|
+
createdBy: 'unknown',
|
|
112
|
+
createdAt: null,
|
|
113
|
+
lastUsedAt: null,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
async setPageMetadata(targetId, updates) {
|
|
117
|
+
await this.getPageSnapshot(targetId);
|
|
118
|
+
const metadata = { ...this.getPageMetadata(targetId) };
|
|
119
|
+
if (updates.taskHint !== undefined) {
|
|
120
|
+
if (updates.taskHint === null) {
|
|
121
|
+
delete metadata.taskHint;
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
metadata.taskHint = updates.taskHint;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (updates.note !== undefined) {
|
|
128
|
+
if (updates.note === null) {
|
|
129
|
+
delete metadata.note;
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
metadata.note = updates.note;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
this.pageMetadata.set(this.metadataKey(targetId), metadata);
|
|
136
|
+
return metadata;
|
|
137
|
+
}
|
|
96
138
|
/**
|
|
97
139
|
* 获取当前 iframe 在主页面的偏移量(仅 withFrame 期间有效)
|
|
98
140
|
*/
|
|
@@ -142,9 +184,7 @@ class UnifiedSessionManager {
|
|
|
142
184
|
* 启动浏览器(CDP 模式)或等待 Extension 连接
|
|
143
185
|
*/
|
|
144
186
|
async launch(options = {}) {
|
|
145
|
-
const extensionReady = this.
|
|
146
|
-
? (this.extensionBridge?.isConnected() ?? false)
|
|
147
|
-
: await this.ensureExtensionConnected(options.timeout);
|
|
187
|
+
const extensionReady = this.cdpExplicitlySelected ? false : await this.ensureExtensionConnected(options.timeout);
|
|
148
188
|
// 优先检查 Extension 是否已连接,如果断开则等待重连(受 timeout 约束)
|
|
149
189
|
if (extensionReady) {
|
|
150
190
|
// newPage 会设置 currentTabId,需要加锁
|
|
@@ -152,6 +192,8 @@ class UnifiedSessionManager {
|
|
|
152
192
|
return this.extensionBridge.newPage(undefined, options.timeout);
|
|
153
193
|
});
|
|
154
194
|
this.activeMode = 'extension';
|
|
195
|
+
this.cdpExplicitlySelected = false;
|
|
196
|
+
this.recordPageUse(result.targetId, true);
|
|
155
197
|
return {
|
|
156
198
|
targetId: result.targetId,
|
|
157
199
|
type: result.type ?? 'page',
|
|
@@ -164,6 +206,8 @@ class UnifiedSessionManager {
|
|
|
164
206
|
// Fallback 到 CDP 模式
|
|
165
207
|
const target = await getCdpSession().launch(options);
|
|
166
208
|
this.activeMode = 'cdp';
|
|
209
|
+
this.cdpExplicitlySelected = false;
|
|
210
|
+
this.recordPageUse(target.targetId, target.targetCreated ?? target.reused !== true);
|
|
167
211
|
return {
|
|
168
212
|
...target,
|
|
169
213
|
mode: 'cdp',
|
|
@@ -172,52 +216,61 @@ class UnifiedSessionManager {
|
|
|
172
216
|
/**
|
|
173
217
|
* 列出所有页面
|
|
174
218
|
*/
|
|
175
|
-
async listTargets() {
|
|
219
|
+
async listTargets(timeout) {
|
|
176
220
|
const mode = this.getMode();
|
|
177
221
|
if (mode === 'none') {
|
|
178
222
|
return [];
|
|
179
223
|
}
|
|
180
|
-
const
|
|
181
|
-
const
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
224
|
+
const deadline = timeout === undefined ? undefined : Date.now() + timeout;
|
|
225
|
+
const driver = await this.getDriver(timeout);
|
|
226
|
+
const targets = await driver.listTargets(deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
|
|
227
|
+
const liveKeys = new Set(targets.map((t) => `${mode}:${t.targetId ?? String(t.id)}`));
|
|
228
|
+
for (const key of this.pageMetadata.keys()) {
|
|
229
|
+
if (key.startsWith(`${mode}:`) && !liveKeys.has(key)) {
|
|
230
|
+
this.pageMetadata.delete(key);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return targets.map(({ id, ...target }) => ({
|
|
234
|
+
...target,
|
|
235
|
+
targetId: target.targetId ?? String(id),
|
|
236
|
+
type: target.type ?? 'page',
|
|
187
237
|
mode,
|
|
188
|
-
isActive:
|
|
189
|
-
|
|
190
|
-
windowId: t.windowId,
|
|
191
|
-
index: t.index,
|
|
192
|
-
pinned: t.pinned,
|
|
193
|
-
incognito: t.incognito,
|
|
194
|
-
status: t.status,
|
|
238
|
+
...(mode === 'extension' ? { isActive: target.active ?? false } : {}),
|
|
239
|
+
metadata: this.getPageMetadata(target.targetId ?? String(id)),
|
|
195
240
|
}));
|
|
196
241
|
}
|
|
197
|
-
async listTopology() {
|
|
242
|
+
async listTopology(timeout) {
|
|
198
243
|
const mode = this.getMode();
|
|
199
244
|
if (mode === 'none') {
|
|
200
245
|
return null;
|
|
201
246
|
}
|
|
202
|
-
const
|
|
247
|
+
const deadline = timeout === undefined ? undefined : Date.now() + timeout;
|
|
248
|
+
const driver = await this.getDriver(timeout);
|
|
203
249
|
if (!driver.listWindows) {
|
|
204
250
|
return null;
|
|
205
251
|
}
|
|
206
|
-
return driver.listWindows();
|
|
252
|
+
return driver.listWindows(deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
|
|
253
|
+
}
|
|
254
|
+
async setReadAccess(targetId, allow) {
|
|
255
|
+
const driver = await this.getDriver();
|
|
256
|
+
if (!driver.setReadAccess) {
|
|
257
|
+
throw new DriverCapabilityError('普通只读授权仅支持 Extension 模式,未执行');
|
|
258
|
+
}
|
|
259
|
+
return this.withTabLock(() => driver.setReadAccess(targetId, allow));
|
|
207
260
|
}
|
|
208
261
|
async adoptPage(targetId) {
|
|
209
262
|
const driver = await this.getDriver();
|
|
210
263
|
if (!driver.adoptPage) {
|
|
211
264
|
throw new DriverCapabilityError('adoptPage 仅支持 Extension 模式');
|
|
212
265
|
}
|
|
213
|
-
return driver.adoptPage(targetId);
|
|
266
|
+
return this.withTabLock(() => driver.adoptPage(targetId));
|
|
214
267
|
}
|
|
215
268
|
async releasePage(targetId) {
|
|
216
269
|
const driver = await this.getDriver();
|
|
217
270
|
if (!driver.releasePage) {
|
|
218
271
|
throw new DriverCapabilityError('releasePage 仅支持 Extension 模式');
|
|
219
272
|
}
|
|
220
|
-
return driver.releasePage(targetId);
|
|
273
|
+
return this.withTabLock(() => driver.releasePage(targetId));
|
|
221
274
|
}
|
|
222
275
|
async movePage(targetId, options) {
|
|
223
276
|
const driver = await this.getDriver();
|
|
@@ -226,6 +279,41 @@ class UnifiedSessionManager {
|
|
|
226
279
|
}
|
|
227
280
|
return driver.movePage(targetId, options);
|
|
228
281
|
}
|
|
282
|
+
async updatePage(targetId, options) {
|
|
283
|
+
const driver = await this.getDriver();
|
|
284
|
+
if (!driver.updatePage) {
|
|
285
|
+
throw new DriverCapabilityError('updatePage 原生 tab 配置仅支持 Extension 模式');
|
|
286
|
+
}
|
|
287
|
+
return this.withTabLock(() => driver.updatePage(targetId, options));
|
|
288
|
+
}
|
|
289
|
+
async groupPages(targetIds, options) {
|
|
290
|
+
const driver = await this.getDriver();
|
|
291
|
+
if (!driver.groupPages) {
|
|
292
|
+
throw new DriverCapabilityError('groupPages 仅支持 Extension 模式');
|
|
293
|
+
}
|
|
294
|
+
return this.withTabLock(() => driver.groupPages(targetIds, options));
|
|
295
|
+
}
|
|
296
|
+
async ungroupPages(targetIds) {
|
|
297
|
+
const driver = await this.getDriver();
|
|
298
|
+
if (!driver.ungroupPages) {
|
|
299
|
+
throw new DriverCapabilityError('ungroupPages 仅支持 Extension 模式');
|
|
300
|
+
}
|
|
301
|
+
return this.withTabLock(() => driver.ungroupPages(targetIds));
|
|
302
|
+
}
|
|
303
|
+
async updateGroup(groupId, options) {
|
|
304
|
+
const driver = await this.getDriver();
|
|
305
|
+
if (!driver.updateGroup) {
|
|
306
|
+
throw new DriverCapabilityError('updateGroup 仅支持 Extension 模式');
|
|
307
|
+
}
|
|
308
|
+
return this.withTabLock(() => driver.updateGroup(groupId, options));
|
|
309
|
+
}
|
|
310
|
+
async moveGroup(groupId, options) {
|
|
311
|
+
const driver = await this.getDriver();
|
|
312
|
+
if (!driver.moveGroup) {
|
|
313
|
+
throw new DriverCapabilityError('moveGroup 仅支持 Extension 模式');
|
|
314
|
+
}
|
|
315
|
+
return this.withTabLock(() => driver.moveGroup(groupId, options));
|
|
316
|
+
}
|
|
229
317
|
async reorderPage(targetId, index) {
|
|
230
318
|
const driver = await this.getDriver();
|
|
231
319
|
if (!driver.reorderPage) {
|
|
@@ -262,40 +350,72 @@ class UnifiedSessionManager {
|
|
|
262
350
|
}
|
|
263
351
|
return driver.resizeWindow(windowId, options);
|
|
264
352
|
}
|
|
353
|
+
async updateWindow(windowId, options) {
|
|
354
|
+
const driver = await this.getDriver();
|
|
355
|
+
if (!driver.updateWindow) {
|
|
356
|
+
throw new DriverCapabilityError('updateWindow 仅支持 Extension 模式');
|
|
357
|
+
}
|
|
358
|
+
return this.withTabLock(() => driver.updateWindow(windowId, options));
|
|
359
|
+
}
|
|
265
360
|
async newWindow(options) {
|
|
266
361
|
const driver = await this.getDriver();
|
|
267
362
|
if (!driver.newWindow) {
|
|
268
363
|
throw new DriverCapabilityError('newWindow 仅支持 Extension 模式');
|
|
269
364
|
}
|
|
270
|
-
return this.withTabLock(() =>
|
|
365
|
+
return this.withTabLock(async () => {
|
|
366
|
+
const result = await driver.newWindow(options);
|
|
367
|
+
if (result.after && 'tabs' in result.after) {
|
|
368
|
+
for (const tab of result.after.tabs) {
|
|
369
|
+
const targetId = tab.targetId ?? String(tab.id);
|
|
370
|
+
this.recordPageUse(targetId, targetId !== options.targetId);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
else if (result.targetId) {
|
|
374
|
+
this.recordPageUse(result.targetId, options.targetId === undefined);
|
|
375
|
+
}
|
|
376
|
+
return result;
|
|
377
|
+
});
|
|
271
378
|
}
|
|
272
379
|
async closeWindow(windowId) {
|
|
273
380
|
const driver = await this.getDriver();
|
|
274
381
|
if (!driver.closeWindow) {
|
|
275
382
|
throw new DriverCapabilityError('closeWindow 仅支持 Extension 模式');
|
|
276
383
|
}
|
|
277
|
-
return this.withTabLock(() =>
|
|
384
|
+
return this.withTabLock(async () => {
|
|
385
|
+
const result = await driver.closeWindow(windowId);
|
|
386
|
+
if (result.before && 'tabs' in result.before) {
|
|
387
|
+
for (const tab of result.before.tabs) {
|
|
388
|
+
this.pageMetadata.delete(this.metadataKey(tab.targetId ?? String(tab.id)));
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
return result;
|
|
392
|
+
});
|
|
278
393
|
}
|
|
279
394
|
/**
|
|
280
395
|
* 导航到 URL
|
|
281
396
|
*/
|
|
282
397
|
async navigate(url, options = {}) {
|
|
283
|
-
const
|
|
284
|
-
await this.
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
398
|
+
const deadline = Date.now() + (options.timeout ?? DEFAULT_TIMEOUT);
|
|
399
|
+
const driver = await this.getDriver(remainingNavigationTimeout(deadline));
|
|
400
|
+
const navigate = () => driver.navigate(url, { wait: options.wait, timeout: remainingNavigationTimeout(deadline) });
|
|
401
|
+
await (this.getMode() === 'extension' ? this.withTabLock(navigate, deadline) : navigate());
|
|
402
|
+
}
|
|
403
|
+
async goBack(timeout = DEFAULT_TIMEOUT) {
|
|
404
|
+
const deadline = Date.now() + timeout;
|
|
405
|
+
const driver = await this.getDriver(remainingNavigationTimeout(deadline));
|
|
406
|
+
const result = await this.withTabLock(() => driver.goBack(remainingNavigationTimeout(deadline)), deadline);
|
|
289
407
|
return { navigated: result.navigated };
|
|
290
408
|
}
|
|
291
|
-
async goForward(timeout) {
|
|
292
|
-
const
|
|
293
|
-
const
|
|
409
|
+
async goForward(timeout = DEFAULT_TIMEOUT) {
|
|
410
|
+
const deadline = Date.now() + timeout;
|
|
411
|
+
const driver = await this.getDriver(remainingNavigationTimeout(deadline));
|
|
412
|
+
const result = await this.withTabLock(() => driver.goForward(remainingNavigationTimeout(deadline)), deadline);
|
|
294
413
|
return { navigated: result.navigated };
|
|
295
414
|
}
|
|
296
415
|
async reload(options = {}) {
|
|
297
|
-
const
|
|
298
|
-
await this.
|
|
416
|
+
const deadline = Date.now() + (options.timeout ?? DEFAULT_TIMEOUT);
|
|
417
|
+
const driver = await this.getDriver(remainingNavigationTimeout(deadline));
|
|
418
|
+
await this.withTabLock(() => driver.reload(options.ignoreCache, options.waitUntil, remainingNavigationTimeout(deadline)), deadline);
|
|
299
419
|
}
|
|
300
420
|
/**
|
|
301
421
|
* 读取页面(Accessibility Tree)
|
|
@@ -322,13 +442,24 @@ class UnifiedSessionManager {
|
|
|
322
442
|
*
|
|
323
443
|
* 返回结构化结果,让调用方知道操作是否真正生效
|
|
324
444
|
*/
|
|
325
|
-
async actionableClick(refId, force) {
|
|
326
|
-
const driver = await this.getDriver();
|
|
327
|
-
return driver.actionableClick(refId, force);
|
|
328
|
-
}
|
|
329
|
-
async checkActionability(refId) {
|
|
445
|
+
async actionableClick(refId, force = false, button = 'left', clickCount = 1) {
|
|
330
446
|
const driver = await this.getDriver();
|
|
331
|
-
|
|
447
|
+
if (button === 'left' && clickCount === 1) {
|
|
448
|
+
return driver.actionableClick(refId, force);
|
|
449
|
+
}
|
|
450
|
+
if (!force) {
|
|
451
|
+
const result = await driver.checkActionability(refId);
|
|
452
|
+
if (!result.success)
|
|
453
|
+
return result;
|
|
454
|
+
}
|
|
455
|
+
if (force) {
|
|
456
|
+
const { x, y } = this.currentMousePosition;
|
|
457
|
+
await driver.stealthClick(x, y, button, clickCount, refId);
|
|
458
|
+
}
|
|
459
|
+
else {
|
|
460
|
+
await this.mouseClick(button, clickCount, refId);
|
|
461
|
+
}
|
|
462
|
+
return { success: true };
|
|
332
463
|
}
|
|
333
464
|
/**
|
|
334
465
|
* dispatch 模式输入(ISOLATED 世界,兼容 React/Vue 受控组件)
|
|
@@ -388,7 +519,7 @@ class UnifiedSessionManager {
|
|
|
388
519
|
const entryStart = Date.now();
|
|
389
520
|
this.lastEvaluationMetadata = undefined;
|
|
390
521
|
const effectiveMode = mode ?? this.inputMode;
|
|
391
|
-
const hasArgs = args
|
|
522
|
+
const hasArgs = args !== undefined;
|
|
392
523
|
// stealth 模式:args 只能通过字符串拼接(chrome.scripting 不支持协议级参数传递)
|
|
393
524
|
let expression = code;
|
|
394
525
|
if (hasArgs && effectiveMode === 'stealth') {
|
|
@@ -412,7 +543,7 @@ class UnifiedSessionManager {
|
|
|
412
543
|
}
|
|
413
544
|
// Extension 路径
|
|
414
545
|
if (effectiveMode === 'precise') {
|
|
415
|
-
return this.evaluateViaExtensionPrecise(code, expression, args, timeout, options
|
|
546
|
+
return this.evaluateViaExtensionPrecise(code, expression, args, timeout, options);
|
|
416
547
|
}
|
|
417
548
|
return this.evaluateViaExtensionStealth(expression, timeout);
|
|
418
549
|
}
|
|
@@ -453,6 +584,24 @@ class UnifiedSessionManager {
|
|
|
453
584
|
async getHtml(selector, outer = true) {
|
|
454
585
|
return (await this.getDriver()).getPageHtml(selector, outer);
|
|
455
586
|
}
|
|
587
|
+
async getTextByRef(refId) {
|
|
588
|
+
return this.extensionReadBridge().getText(undefined, refId);
|
|
589
|
+
}
|
|
590
|
+
async getHtmlByRef(refId, outer = true) {
|
|
591
|
+
return this.extensionReadBridge().getHtml(undefined, outer, refId);
|
|
592
|
+
}
|
|
593
|
+
async getAttributeByRef(refId, attribute) {
|
|
594
|
+
return this.extensionReadBridge().getAttribute(undefined, refId, attribute);
|
|
595
|
+
}
|
|
596
|
+
async getComputedStyleByRef(refId, prop) {
|
|
597
|
+
return this.extensionReadBridge().getComputedStyle(refId, prop);
|
|
598
|
+
}
|
|
599
|
+
async findAtPoint(x, y, matchIndex, timeout) {
|
|
600
|
+
return this.extensionReadBridge().find(undefined, undefined, undefined, timeout, { x, y }, matchIndex);
|
|
601
|
+
}
|
|
602
|
+
async getHtmlWithImagesByRef(refId) {
|
|
603
|
+
return this.extensionReadBridge().getHtmlWithImages(undefined, true, refId);
|
|
604
|
+
}
|
|
456
605
|
/**
|
|
457
606
|
* 获取页面 HTML + 图片元信息
|
|
458
607
|
*/
|
|
@@ -465,7 +614,13 @@ class UnifiedSessionManager {
|
|
|
465
614
|
*/
|
|
466
615
|
async getMetadata() {
|
|
467
616
|
const driver = await this.getDriver();
|
|
468
|
-
|
|
617
|
+
const targetId = this.getCurrentTargetId();
|
|
618
|
+
const metadata = await driver.getMetadata();
|
|
619
|
+
const target = (await this.listTargets()).find((page) => page.targetId === targetId);
|
|
620
|
+
if (!target) {
|
|
621
|
+
throw new TargetNotFoundError(targetId ?? 'current');
|
|
622
|
+
}
|
|
623
|
+
return { ...metadata, managed: target.managed ?? false, metadata: target.metadata };
|
|
469
624
|
}
|
|
470
625
|
/**
|
|
471
626
|
* 批量从浏览器缓存获取资源内容
|
|
@@ -515,7 +670,10 @@ class UnifiedSessionManager {
|
|
|
515
670
|
* @param xpath XPath 表达式
|
|
516
671
|
* @param timeout 端到端预算(毫秒),包含连接等待和请求超时,传给 bridge.find → sendCommand
|
|
517
672
|
*/
|
|
518
|
-
async find(selector, text, xpath, timeout) {
|
|
673
|
+
async find(selector, text, xpath, timeout, matchIndex) {
|
|
674
|
+
if (matchIndex !== undefined) {
|
|
675
|
+
return this.extensionReadBridge().find(selector, text, xpath, timeout, undefined, matchIndex);
|
|
676
|
+
}
|
|
519
677
|
if (timeout !== undefined) {
|
|
520
678
|
// 轮询上下文:快速失败,端到端预算受控
|
|
521
679
|
if (this.isExtensionConnected()) {
|
|
@@ -556,17 +714,22 @@ class UnifiedSessionManager {
|
|
|
556
714
|
return (await this.getDriver()).deleteCookie(url, name);
|
|
557
715
|
}
|
|
558
716
|
async clearCookies(filter) {
|
|
717
|
+
if (!filter || (!filter.url && !filter.domain)) {
|
|
718
|
+
throw new Error('clearCookies 必须带 url 或 domain 过滤参数,name 只能在该范围内进一步过滤(防止跨站误清同名 cookie)');
|
|
719
|
+
}
|
|
559
720
|
return (await this.getDriver()).clearCookies(filter);
|
|
560
721
|
}
|
|
561
722
|
/**
|
|
562
723
|
* 创建新页面
|
|
563
724
|
*/
|
|
564
|
-
async newPage(url) {
|
|
725
|
+
async newPage(url, options, timeout) {
|
|
565
726
|
const driver = await this.getDriver();
|
|
566
727
|
const isExt = this.isExtensionConnected();
|
|
567
728
|
const op = async () => {
|
|
568
|
-
const result = await driver.newPage(url);
|
|
729
|
+
const result = await driver.newPage(url, timeout, options);
|
|
730
|
+
this.recordPageUse(result.targetId, true);
|
|
569
731
|
return {
|
|
732
|
+
...result,
|
|
570
733
|
targetId: result.targetId,
|
|
571
734
|
type: result.type ?? 'page',
|
|
572
735
|
url: result.url,
|
|
@@ -581,9 +744,16 @@ class UnifiedSessionManager {
|
|
|
581
744
|
* 关闭页面
|
|
582
745
|
*/
|
|
583
746
|
async closePage(targetId) {
|
|
747
|
+
if (!targetId) {
|
|
748
|
+
throw new DriverCapabilityError('closePage 需要显式 targetId,未关闭页面');
|
|
749
|
+
}
|
|
584
750
|
const driver = await this.getDriver();
|
|
585
751
|
const isExt = this.isExtensionConnected();
|
|
586
|
-
const op = () =>
|
|
752
|
+
const op = async () => {
|
|
753
|
+
const result = await driver.closePage(targetId);
|
|
754
|
+
this.pageMetadata.delete(this.metadataKey(targetId));
|
|
755
|
+
return result;
|
|
756
|
+
};
|
|
587
757
|
if (isExt) {
|
|
588
758
|
return this.withTabLock(op);
|
|
589
759
|
}
|
|
@@ -616,6 +786,40 @@ class UnifiedSessionManager {
|
|
|
616
786
|
else {
|
|
617
787
|
await op();
|
|
618
788
|
}
|
|
789
|
+
this.recordPageUse(targetId);
|
|
790
|
+
}
|
|
791
|
+
/**
|
|
792
|
+
* 串行化所有 tab 切换操作,防止并发请求互相覆盖 currentTabId,
|
|
793
|
+
* 调用者:selectPage/activatePage/adoptPage/releasePage/newPage/closePage/navigate/reload/launch/withTabId
|
|
794
|
+
*
|
|
795
|
+
* 同一请求内的嵌套调用可重入,恢复状态只保存在当前请求的 AsyncLocalStorage 中
|
|
796
|
+
*/
|
|
797
|
+
async withTabLock(fn, deadline) {
|
|
798
|
+
if (this.tabLockContext.getStore()?.session === this) {
|
|
799
|
+
if (deadline !== undefined) {
|
|
800
|
+
remainingNavigationTimeout(deadline);
|
|
801
|
+
}
|
|
802
|
+
return fn();
|
|
803
|
+
}
|
|
804
|
+
const previousLock = this.tabSwitchLock;
|
|
805
|
+
let releaseLock;
|
|
806
|
+
this.tabSwitchLock = new Promise((resolve) => {
|
|
807
|
+
releaseLock = resolve;
|
|
808
|
+
});
|
|
809
|
+
let acquired = false;
|
|
810
|
+
try {
|
|
811
|
+
await waitForNavigationQueue(previousLock, deadline);
|
|
812
|
+
acquired = true;
|
|
813
|
+
return await this.tabLockContext.run({ session: this }, fn);
|
|
814
|
+
}
|
|
815
|
+
finally {
|
|
816
|
+
if (acquired) {
|
|
817
|
+
releaseLock();
|
|
818
|
+
}
|
|
819
|
+
else {
|
|
820
|
+
void previousLock.then(releaseLock, releaseLock);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
619
823
|
}
|
|
620
824
|
/**
|
|
621
825
|
* 临时切换操作目标 tab,执行完后恢复
|
|
@@ -626,44 +830,178 @@ class UnifiedSessionManager {
|
|
|
626
830
|
* 即使不传 tabId,也需要加锁:fn() 内调用 bridge 方法会读取 currentTabId,
|
|
627
831
|
* 不加锁则并发的 withTabId(someId, ...) 可能在 fn() 执行中途修改 currentTabId
|
|
628
832
|
*/
|
|
629
|
-
async withTabId(
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
833
|
+
async withTabId(targetId, fn, deadline) {
|
|
834
|
+
return this.withTabLock(async () => {
|
|
835
|
+
const remaining = () => (deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
|
|
836
|
+
const mode = this.getMode();
|
|
837
|
+
if (!targetId) {
|
|
838
|
+
const current = this.getCurrentTargetId();
|
|
839
|
+
if (current) {
|
|
840
|
+
this.recordPageUse(current);
|
|
841
|
+
}
|
|
633
842
|
const previousRequireExtension = this.requireExtension;
|
|
634
|
-
|
|
843
|
+
const previousCdpSelection = this.cdpExplicitlySelected;
|
|
844
|
+
if (mode === 'extension') {
|
|
845
|
+
this.requireExtension = true;
|
|
846
|
+
}
|
|
847
|
+
else if (mode === 'cdp') {
|
|
848
|
+
this.cdpExplicitlySelected = true;
|
|
849
|
+
}
|
|
635
850
|
try {
|
|
636
|
-
|
|
851
|
+
return await fn();
|
|
637
852
|
}
|
|
638
853
|
finally {
|
|
639
854
|
this.requireExtension = previousRequireExtension;
|
|
855
|
+
this.cdpExplicitlySelected = previousCdpSelection;
|
|
640
856
|
}
|
|
641
857
|
}
|
|
642
|
-
|
|
858
|
+
if (mode === 'none') {
|
|
859
|
+
throw new DriverCapabilityError('浏览器未连接,无法选择目标页面');
|
|
860
|
+
}
|
|
861
|
+
const driver = mode === 'extension' ? this.extensionBridge : getCdpSession();
|
|
862
|
+
const targets = await driver.listTargets(remaining());
|
|
863
|
+
if (!targets.some((target) => (target.targetId ?? String(target.id)) === targetId)) {
|
|
864
|
+
throw new DriverCapabilityError(`目标页面 ${targetId} 不存在于当前 ${mode} 连接`);
|
|
865
|
+
}
|
|
866
|
+
const previousId = driver.getCurrentTargetId();
|
|
867
|
+
const previousRequireExtension = this.requireExtension;
|
|
868
|
+
const previousCdpSelection = this.cdpExplicitlySelected;
|
|
869
|
+
const previousMode = this.activeMode;
|
|
870
|
+
if (mode === 'extension') {
|
|
871
|
+
this.requireExtension = true;
|
|
872
|
+
}
|
|
873
|
+
else {
|
|
874
|
+
this.cdpExplicitlySelected = true;
|
|
875
|
+
}
|
|
876
|
+
try {
|
|
877
|
+
if (targetId !== previousId) {
|
|
878
|
+
await driver.selectPage(targetId, remaining());
|
|
879
|
+
}
|
|
880
|
+
this.activeMode = mode;
|
|
881
|
+
this.recordPageUse(targetId);
|
|
882
|
+
return await fn();
|
|
883
|
+
}
|
|
884
|
+
finally {
|
|
885
|
+
this.requireExtension = previousRequireExtension;
|
|
886
|
+
this.cdpExplicitlySelected = previousCdpSelection;
|
|
887
|
+
this.activeMode = previousMode;
|
|
888
|
+
if (targetId !== previousId) {
|
|
889
|
+
const restoration = {
|
|
890
|
+
status: previousId ? 'restored' : 'cleared',
|
|
891
|
+
previousTargetId: previousId,
|
|
892
|
+
temporaryTargetId: targetId,
|
|
893
|
+
currentTargetId: null,
|
|
894
|
+
};
|
|
895
|
+
let clearTarget = true;
|
|
896
|
+
try {
|
|
897
|
+
if (previousId) {
|
|
898
|
+
const targets = await driver.listTargets(remaining());
|
|
899
|
+
if (targets.some((target) => (target.targetId ?? String(target.id)) === previousId)) {
|
|
900
|
+
await driver.selectPage(previousId, remaining());
|
|
901
|
+
clearTarget = false;
|
|
902
|
+
}
|
|
903
|
+
else {
|
|
904
|
+
restoration.status = 'previous_target_closed';
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
catch (error) {
|
|
909
|
+
restoration.status = 'failed';
|
|
910
|
+
restoration.error = error instanceof Error ? error.message : String(error);
|
|
911
|
+
}
|
|
912
|
+
if (clearTarget) {
|
|
913
|
+
try {
|
|
914
|
+
if (mode === 'extension') {
|
|
915
|
+
driver.setCurrentTargetId(null);
|
|
916
|
+
}
|
|
917
|
+
else {
|
|
918
|
+
await getCdpSession().deselectPage(deadline === undefined ? undefined : Math.max(0, deadline - Date.now()));
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
catch (error) {
|
|
922
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
923
|
+
if (restoration.error) {
|
|
924
|
+
restoration.cleanupError = message;
|
|
925
|
+
}
|
|
926
|
+
else {
|
|
927
|
+
restoration.status = 'failed';
|
|
928
|
+
restoration.error = message;
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
restoration.currentTargetId = driver.getCurrentTargetId();
|
|
933
|
+
this.tabLockContext.getStore().targetRestoration = restoration;
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
}, deadline);
|
|
937
|
+
}
|
|
938
|
+
getTargetRestoration() {
|
|
939
|
+
return this.tabLockContext.getStore()?.targetRestoration;
|
|
940
|
+
}
|
|
941
|
+
async getPageSnapshot(targetId, timeout) {
|
|
942
|
+
const mode = this.getMode();
|
|
943
|
+
if (mode === 'none') {
|
|
944
|
+
throw new DriverCapabilityError('浏览器未连接,无法读取页面状态');
|
|
643
945
|
}
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
946
|
+
const id = targetId ?? this.getCurrentTargetId();
|
|
947
|
+
if (!id) {
|
|
948
|
+
throw new DriverCapabilityError('没有操作目标,请先选择页面');
|
|
949
|
+
}
|
|
950
|
+
const snapshot = mode === 'extension'
|
|
951
|
+
? await this.extensionBridge.getPageSnapshot(id, timeout)
|
|
952
|
+
: await getCdpSession().getPageSnapshot(id, timeout);
|
|
953
|
+
this.recordPageUse(id);
|
|
954
|
+
return snapshot;
|
|
955
|
+
}
|
|
956
|
+
async withPageCondition(condition, fn, deadline) {
|
|
957
|
+
if (condition.expectedUrl === undefined && condition.expectedRevision === undefined) {
|
|
958
|
+
return fn();
|
|
647
959
|
}
|
|
648
|
-
const driver = this.extensionBridge;
|
|
649
960
|
return this.withTabLock(async () => {
|
|
650
|
-
const
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
961
|
+
const mode = this.getMode();
|
|
962
|
+
const targetId = condition.targetId ?? this.getCurrentTargetId();
|
|
963
|
+
if (mode === 'none' || !targetId) {
|
|
964
|
+
throw new DriverCapabilityError('没有操作目标,请先选择页面');
|
|
965
|
+
}
|
|
966
|
+
const driver = mode === 'extension' ? this.extensionBridge : getCdpSession();
|
|
654
967
|
const previousRequireExtension = this.requireExtension;
|
|
655
|
-
const
|
|
656
|
-
|
|
657
|
-
|
|
968
|
+
const previousCdpSelection = this.cdpExplicitlySelected;
|
|
969
|
+
const previousMode = this.activeMode;
|
|
970
|
+
if (mode === 'extension') {
|
|
971
|
+
this.requireExtension = true;
|
|
972
|
+
}
|
|
973
|
+
else {
|
|
974
|
+
this.cdpExplicitlySelected = true;
|
|
975
|
+
}
|
|
658
976
|
try {
|
|
977
|
+
const snapshot = await driver.getPageSnapshot(targetId, deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
|
|
978
|
+
if (snapshot.revision === null) {
|
|
979
|
+
throw new StructuredToolError('DRIVER_CAPABILITY_ERROR', '当前 Extension 不支持原子页面条件,未执行操作', '更新 Extension 后再使用 expectedUrl 或 expectedRevision', { targetId, actionExecuted: false, actionStatus: 'not_started', failureStage: 'precondition' });
|
|
980
|
+
}
|
|
981
|
+
if ((condition.expectedUrl !== undefined && snapshot.url !== condition.expectedUrl) ||
|
|
982
|
+
(condition.expectedRevision !== undefined && snapshot.revision !== condition.expectedRevision)) {
|
|
983
|
+
throw new PagePreconditionError({
|
|
984
|
+
targetId,
|
|
985
|
+
expectedUrl: condition.expectedUrl ?? null,
|
|
986
|
+
expectedRevision: condition.expectedRevision ?? null,
|
|
987
|
+
actualUrl: snapshot.url,
|
|
988
|
+
actualRevision: snapshot.revision,
|
|
989
|
+
});
|
|
990
|
+
}
|
|
991
|
+
driver.setPageCondition({
|
|
992
|
+
targetId,
|
|
993
|
+
expectedUrl: condition.expectedUrl,
|
|
994
|
+
expectedRevision: condition.expectedRevision,
|
|
995
|
+
});
|
|
659
996
|
return await fn();
|
|
660
997
|
}
|
|
661
998
|
finally {
|
|
999
|
+
driver.setPageCondition(null);
|
|
662
1000
|
this.requireExtension = previousRequireExtension;
|
|
663
|
-
this.
|
|
664
|
-
|
|
1001
|
+
this.cdpExplicitlySelected = previousCdpSelection;
|
|
1002
|
+
this.activeMode = previousMode;
|
|
665
1003
|
}
|
|
666
|
-
});
|
|
1004
|
+
}, deadline);
|
|
667
1005
|
}
|
|
668
1006
|
/**
|
|
669
1007
|
* 临时切换操作目标 iframe,执行完后恢复
|
|
@@ -682,7 +1020,7 @@ class UnifiedSessionManager {
|
|
|
682
1020
|
throw new Error('iframe 穿透需要 Extension 模式');
|
|
683
1021
|
}
|
|
684
1022
|
const driver = this.extensionBridge;
|
|
685
|
-
const { frameId, offset } = await driver.resolveFrame(frame);
|
|
1023
|
+
const { frameId, offset, frameContext } = await driver.resolveFrame(frame);
|
|
686
1024
|
const previousFrameId = driver.getCurrentFrameId();
|
|
687
1025
|
const previousFrameOffset = this.currentFrameOffset;
|
|
688
1026
|
const previousRequireExtension = this.requireExtension;
|
|
@@ -694,6 +1032,11 @@ class UnifiedSessionManager {
|
|
|
694
1032
|
try {
|
|
695
1033
|
return await fn();
|
|
696
1034
|
}
|
|
1035
|
+
catch (error) {
|
|
1036
|
+
throw setErrorPageContext(error, {
|
|
1037
|
+
frameContext: { selection: frame, frameId, ...frameContext },
|
|
1038
|
+
});
|
|
1039
|
+
}
|
|
697
1040
|
finally {
|
|
698
1041
|
// 字段赋值不会 throw,driver.setCurrentFrameId 是同步函数也不会 throw,无需嵌套 try
|
|
699
1042
|
this.requireExtension = previousRequireExtension;
|
|
@@ -714,7 +1057,7 @@ class UnifiedSessionManager {
|
|
|
714
1057
|
}
|
|
715
1058
|
async getLiveState() {
|
|
716
1059
|
if (this.getMode() !== 'extension') {
|
|
717
|
-
return getCdpSession().
|
|
1060
|
+
return getCdpSession().getLiveState();
|
|
718
1061
|
}
|
|
719
1062
|
const targetId = this.extensionBridge.getCurrentTargetId();
|
|
720
1063
|
if (!targetId) {
|
|
@@ -754,6 +1097,12 @@ class UnifiedSessionManager {
|
|
|
754
1097
|
// Puppeteer 风格:连续 keyDown 同 key → rawKeyDown + autoRepeat(长按重复)
|
|
755
1098
|
const isRepeat = this.pressedKeys.has(key);
|
|
756
1099
|
const nextModifiers = MODIFIER_KEYS[key] ? this.modifiers | MODIFIER_KEYS[key] : this.modifiers;
|
|
1100
|
+
if (!isExt) {
|
|
1101
|
+
await getCdpSession().keyDown(key, commands, { rawKeyDown: isRepeat, autoRepeat: isRepeat });
|
|
1102
|
+
this.modifiers = nextModifiers;
|
|
1103
|
+
this.pressedKeys.add(key);
|
|
1104
|
+
return;
|
|
1105
|
+
}
|
|
757
1106
|
if (isExt && this.inputMode === 'stealth') {
|
|
758
1107
|
await driver.stealthKey(key, 'down', this.getModifierNames(nextModifiers));
|
|
759
1108
|
this.modifiers = nextModifiers;
|
|
@@ -780,7 +1129,10 @@ class UnifiedSessionManager {
|
|
|
780
1129
|
const driver = await this.getDriver();
|
|
781
1130
|
const isExt = this.isExtensionConnected();
|
|
782
1131
|
const nextModifiers = MODIFIER_KEYS[key] ? this.modifiers & ~MODIFIER_KEYS[key] : this.modifiers;
|
|
783
|
-
if (isExt
|
|
1132
|
+
if (!isExt) {
|
|
1133
|
+
await getCdpSession().keyUp(key);
|
|
1134
|
+
}
|
|
1135
|
+
else if (this.inputMode === 'stealth') {
|
|
784
1136
|
await driver.stealthKey(key, 'up', this.getModifierNames(nextModifiers));
|
|
785
1137
|
}
|
|
786
1138
|
else {
|
|
@@ -798,28 +1150,35 @@ class UnifiedSessionManager {
|
|
|
798
1150
|
/**
|
|
799
1151
|
* 输入文本
|
|
800
1152
|
*/
|
|
801
|
-
async typeText(text, delay = 0) {
|
|
1153
|
+
async typeText(text, delay = 0, timeout) {
|
|
1154
|
+
const startedAt = Date.now();
|
|
802
1155
|
const driver = await this.getDriver();
|
|
1156
|
+
const remaining = timeout === undefined ? undefined : Math.max(0, timeout - (Date.now() - startedAt));
|
|
803
1157
|
const isExt = this.isExtensionConnected();
|
|
804
1158
|
if (isExt && this.inputMode === 'stealth') {
|
|
805
|
-
await driver.stealthType(text, delay);
|
|
1159
|
+
await driver.stealthType(text, delay, remaining);
|
|
806
1160
|
}
|
|
807
1161
|
else {
|
|
808
|
-
await driver.inputType(text, delay);
|
|
1162
|
+
await driver.inputType(text, delay, remaining);
|
|
809
1163
|
}
|
|
810
1164
|
}
|
|
811
1165
|
/**
|
|
812
1166
|
* 鼠标移动
|
|
813
1167
|
*/
|
|
814
|
-
async mouseMove(x, y) {
|
|
1168
|
+
async mouseMove(x, y, timeout) {
|
|
1169
|
+
const startedAt = Date.now();
|
|
1170
|
+
const driver = await this.getDriver(timeout);
|
|
1171
|
+
const remaining = timeout === undefined ? undefined : timeout - (Date.now() - startedAt);
|
|
1172
|
+
if (remaining !== undefined && remaining <= 0) {
|
|
1173
|
+
throw new TimeoutError('input timeout before mouse movement');
|
|
1174
|
+
}
|
|
815
1175
|
this.currentMousePosition = { x, y }; // 更新位置
|
|
816
|
-
const driver = await this.getDriver();
|
|
817
1176
|
const isExt = this.isExtensionConnected();
|
|
818
1177
|
if (isExt && this.inputMode === 'stealth') {
|
|
819
|
-
await driver.stealthMouse('mousemove', x, y);
|
|
1178
|
+
await driver.stealthMouse('mousemove', x, y, undefined, remaining);
|
|
820
1179
|
}
|
|
821
1180
|
else {
|
|
822
|
-
await driver.inputMouse('mouseMoved', x, y, { modifiers: this.modifiers });
|
|
1181
|
+
await driver.inputMouse('mouseMoved', x, y, { modifiers: this.modifiers }, remaining);
|
|
823
1182
|
}
|
|
824
1183
|
}
|
|
825
1184
|
/**
|
|
@@ -880,6 +1239,93 @@ class UnifiedSessionManager {
|
|
|
880
1239
|
await this.mouseUp(button, i);
|
|
881
1240
|
}
|
|
882
1241
|
}
|
|
1242
|
+
/**
|
|
1243
|
+
* Turnstile 点击:同页控件走页面鼠标;Cloudflare iframe 只在已聚焦窗口的活动受控 tab 上使用系统鼠标
|
|
1244
|
+
*/
|
|
1245
|
+
// noinspection JSUnusedGlobalSymbols — resolveChallenge 通过 ChallengeHost 结构类型调用
|
|
1246
|
+
async clickTurnstile(snapshot, timeout) {
|
|
1247
|
+
const deadline = timeout === undefined ? undefined : Date.now() + timeout;
|
|
1248
|
+
const remaining = () => (deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
|
|
1249
|
+
if (snapshot.clickSource !== 'iframe') {
|
|
1250
|
+
const point = snapshot.clickPoint;
|
|
1251
|
+
if (!point) {
|
|
1252
|
+
throw new OsMouseError('TURNSTILE_OS_CLICK_UNAVAILABLE', '页面未返回可点击的 Turnstile 坐标', '重新检查页面状态后再重试;交互式验证码无法自动完成');
|
|
1253
|
+
}
|
|
1254
|
+
const driver = await withNavigationBudget(() => this.getDriver(remaining()), deadline);
|
|
1255
|
+
if (this.isExtensionConnected()) {
|
|
1256
|
+
await withNavigationBudget(() => driver.stealthClick(point.x, point.y, 'left', 1, undefined, remaining()), deadline);
|
|
1257
|
+
return;
|
|
1258
|
+
}
|
|
1259
|
+
const frameOffset = this.currentFrameOffset;
|
|
1260
|
+
const clickPoint = frameOffset && this.inputMode !== 'stealth'
|
|
1261
|
+
? { x: point.x + frameOffset.x, y: point.y + frameOffset.y }
|
|
1262
|
+
: point;
|
|
1263
|
+
this.currentMousePosition = clickPoint;
|
|
1264
|
+
await withNavigationBudget(() => driver.inputMouse('mouseMoved', clickPoint.x, clickPoint.y, { modifiers: this.modifiers }), deadline);
|
|
1265
|
+
await withNavigationBudget(() => getCdpSession().inputMouse('mousePressed', clickPoint.x, clickPoint.y, {
|
|
1266
|
+
button: 'left',
|
|
1267
|
+
clickCount: 1,
|
|
1268
|
+
modifiers: this.modifiers,
|
|
1269
|
+
releaseAfterPress: true,
|
|
1270
|
+
}, remaining()), deadline);
|
|
1271
|
+
return;
|
|
1272
|
+
}
|
|
1273
|
+
if (this.getMode() !== 'extension' || !this.extensionBridge) {
|
|
1274
|
+
throw new OsMouseError('TURNSTILE_OS_CLICK_UNAVAILABLE', 'Cloudflare iframe 需要 Extension 模式下的系统鼠标点击', '先确认 Chrome Extension 已连接,把受控测试页放到已经聚焦的窗口并保持该 tab 为活动页后重试;混合窗口不会调用 focusWindow', { mode: this.getMode() });
|
|
1275
|
+
}
|
|
1276
|
+
const targetId = this.getCurrentTargetId();
|
|
1277
|
+
if (!targetId) {
|
|
1278
|
+
throw new OsMouseError('TURNSTILE_OS_CLICK_UNAVAILABLE', '没有当前受控页面,无法使用系统鼠标点击 Turnstile', '先 browse attach 到受控测试页,把该页放到已经聚焦的窗口并保持为活动 tab 后重试');
|
|
1279
|
+
}
|
|
1280
|
+
const topology = await this.listTopology(remaining());
|
|
1281
|
+
const windowInfo = topology?.windows.find((item) => item.tabs.some((tab) => String(tab.id) === targetId || tab.targetId === targetId));
|
|
1282
|
+
const tab = windowInfo?.tabs.find((item) => String(item.id) === targetId || item.targetId === targetId);
|
|
1283
|
+
if (!windowInfo || !tab) {
|
|
1284
|
+
throw new OsMouseError('TURNSTILE_OS_CLICK_UNAVAILABLE', '找不到当前受控页面所在窗口,无法使用系统鼠标点击 Turnstile', '先 browse list 确认受控测试页仍在,再把它放到已经聚焦的窗口后重试');
|
|
1285
|
+
}
|
|
1286
|
+
if (tab.managed !== true) {
|
|
1287
|
+
throw new OsMouseError('TURNSTILE_OS_CLICK_UNAVAILABLE', '当前页面不是受控测试页,拒绝系统鼠标点击', '只对 assistant 创建或 adopt 的受控测试页使用 Turnstile 系统鼠标');
|
|
1288
|
+
}
|
|
1289
|
+
if (!windowInfo.focused) {
|
|
1290
|
+
throw new OsMouseError('TURNSTILE_OS_CLICK_UNAVAILABLE', '当前窗口未聚焦,拒绝系统鼠标点击', '把受控测试页放到已经聚焦的窗口并保持该 tab 为活动页后重试;混合窗口不会调用 focusWindow');
|
|
1291
|
+
}
|
|
1292
|
+
const activeTabId = windowInfo.activeTabId;
|
|
1293
|
+
if (tab.active !== true && (activeTabId === undefined || String(activeTabId) !== targetId)) {
|
|
1294
|
+
throw new OsMouseError('TURNSTILE_OS_CLICK_UNAVAILABLE', '受控测试页不是当前窗口的活动 tab,拒绝系统鼠标点击', '先把受控测试页设为该窗口的活动 tab,且窗口已经聚焦后再重试');
|
|
1295
|
+
}
|
|
1296
|
+
await withNavigationBudget(() => this.extensionBridge.debuggerDetach(undefined, remaining()), deadline);
|
|
1297
|
+
const viewport = await withNavigationBudget(() => this.readViewportMetrics(0), deadline);
|
|
1298
|
+
const refreshedTopology = await this.listTopology(remaining());
|
|
1299
|
+
const refreshedWindow = refreshedTopology?.windows.find((item) => item.tabs.some((candidate) => String(candidate.id) === targetId || candidate.targetId === targetId));
|
|
1300
|
+
const refreshedTab = refreshedWindow?.tabs.find((candidate) => String(candidate.id) === targetId || candidate.targetId === targetId);
|
|
1301
|
+
const refreshedActiveTabId = refreshedWindow?.activeTabId;
|
|
1302
|
+
if (!refreshedWindow?.focused ||
|
|
1303
|
+
refreshedTab?.managed !== true ||
|
|
1304
|
+
(refreshedTab.active !== true &&
|
|
1305
|
+
(refreshedActiveTabId === undefined || String(refreshedActiveTabId) !== targetId))) {
|
|
1306
|
+
throw new OsMouseError('TURNSTILE_OS_CLICK_UNAVAILABLE', '系统鼠标点击前,受控测试页的窗口或活动 tab 已变化', '重新聚焦受控测试页并保持为活动 tab 后重试');
|
|
1307
|
+
}
|
|
1308
|
+
const frameOffset = this.currentFrameOffset;
|
|
1309
|
+
const clickPoint = snapshot.clickPoint && frameOffset
|
|
1310
|
+
? { x: snapshot.clickPoint.x + frameOffset.x, y: snapshot.clickPoint.y + frameOffset.y }
|
|
1311
|
+
: snapshot.clickPoint;
|
|
1312
|
+
const screen = await withNavigationBudget(() => resolveTurnstileOsClickPoint({
|
|
1313
|
+
...snapshot,
|
|
1314
|
+
clickPoint,
|
|
1315
|
+
screenPoint: null,
|
|
1316
|
+
viewport,
|
|
1317
|
+
}, { deadline }), deadline);
|
|
1318
|
+
await withNavigationBudget(() => osLeftClick(screen.x, screen.y, { deadline }), deadline);
|
|
1319
|
+
}
|
|
1320
|
+
// noinspection JSUnusedGlobalSymbols — resolveChallenge 通过 ChallengeHost 结构类型调用
|
|
1321
|
+
async inspectChallenge(options, timeout) {
|
|
1322
|
+
if (this.getMode() !== 'extension' || !this.extensionBridge) {
|
|
1323
|
+
throw new Error('challenge_inspect 仅在 Extension 模式可用');
|
|
1324
|
+
}
|
|
1325
|
+
const deadline = timeout === undefined ? undefined : Date.now() + timeout;
|
|
1326
|
+
await withNavigationBudget(() => this.extensionBridge.debuggerDetach(undefined, deadline === undefined ? undefined : remainingNavigationTimeout(deadline)), deadline);
|
|
1327
|
+
return this.extensionBridge.inspectChallenge(options, deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
|
|
1328
|
+
}
|
|
883
1329
|
/**
|
|
884
1330
|
* 鼠标滚轮
|
|
885
1331
|
*/
|
|
@@ -935,6 +1381,36 @@ class UnifiedSessionManager {
|
|
|
935
1381
|
async getNetworkRequests(options = {}) {
|
|
936
1382
|
return (await this.getDriver()).getNetworkRequests(options);
|
|
937
1383
|
}
|
|
1384
|
+
// noinspection JSUnusedGlobalSymbols — resolveChallenge 通过 ChallengeHost 结构类型调用
|
|
1385
|
+
async getChallengeState() {
|
|
1386
|
+
const mode = this.getMode();
|
|
1387
|
+
if (mode === 'none') {
|
|
1388
|
+
return null;
|
|
1389
|
+
}
|
|
1390
|
+
const extensionBundleHash = this.extensionBridge?.getConnectionInfo().extensionBackgroundBundleHash ?? null;
|
|
1391
|
+
if (mode === 'extension' && this.extensionChallengeStateUnsupported) {
|
|
1392
|
+
if (this.unsupportedChallengeStateBundleHash === extensionBundleHash) {
|
|
1393
|
+
return null;
|
|
1394
|
+
}
|
|
1395
|
+
this.extensionChallengeStateUnsupported = false;
|
|
1396
|
+
}
|
|
1397
|
+
try {
|
|
1398
|
+
const challengeRequired = await (await this.getDriver()).getChallengeState();
|
|
1399
|
+
return challengeRequired ? { state: 'pending', mode } : null;
|
|
1400
|
+
}
|
|
1401
|
+
catch (error) {
|
|
1402
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1403
|
+
const errorCode = error && typeof error === 'object' && 'code' in error ? error.code : undefined;
|
|
1404
|
+
if (mode === 'extension' &&
|
|
1405
|
+
(errorCode === 'UNKNOWN_ACTION' || message.includes('Unknown action: network_challenge_state'))) {
|
|
1406
|
+
this.extensionChallengeStateUnsupported = true;
|
|
1407
|
+
this.unsupportedChallengeStateBundleHash = extensionBundleHash;
|
|
1408
|
+
console.warn('[MCP] Extension 未实现 network_challenge_state,改用页面标题和 DOM 检测 Cloudflare');
|
|
1409
|
+
return null;
|
|
1410
|
+
}
|
|
1411
|
+
throw error;
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
938
1414
|
async enableNetwork() {
|
|
939
1415
|
const driver = await this.getDriver();
|
|
940
1416
|
await driver.networkEnable();
|
|
@@ -949,15 +1425,34 @@ class UnifiedSessionManager {
|
|
|
949
1425
|
const driver = await this.getDriver();
|
|
950
1426
|
return driver.debuggerSend(method, params);
|
|
951
1427
|
}
|
|
1428
|
+
extensionReadBridge() {
|
|
1429
|
+
if (this.getMode() !== 'extension' || !this.extensionBridge?.isConnected()) {
|
|
1430
|
+
throw new DriverCapabilityError('定向读取需要已连接的 Extension');
|
|
1431
|
+
}
|
|
1432
|
+
return this.extensionBridge;
|
|
1433
|
+
}
|
|
1434
|
+
metadataKey(targetId) {
|
|
1435
|
+
return `${this.getMode()}:${targetId}`;
|
|
1436
|
+
}
|
|
1437
|
+
recordPageUse(targetId, created = false) {
|
|
1438
|
+
const metadata = this.getPageMetadata(targetId);
|
|
1439
|
+
this.pageMetadata.set(this.metadataKey(targetId), {
|
|
1440
|
+
...metadata,
|
|
1441
|
+
createdBy: created ? 'mcp-chrome' : metadata.createdBy,
|
|
1442
|
+
createdAt: created ? new Date().toISOString() : metadata.createdAt,
|
|
1443
|
+
lastUsedAt: new Date().toISOString(),
|
|
1444
|
+
});
|
|
1445
|
+
}
|
|
952
1446
|
evaluateViaCdp(script, args, timeout) {
|
|
953
1447
|
return getCdpSession().evaluate(script, args, timeout);
|
|
954
1448
|
}
|
|
955
|
-
async evaluateViaExtensionPrecise(code, expression, args, timeout,
|
|
956
|
-
const hasArgs = args !== undefined
|
|
1449
|
+
async evaluateViaExtensionPrecise(code, expression, args, timeout, options = {}) {
|
|
1450
|
+
const hasArgs = args !== undefined;
|
|
957
1451
|
const currentFrameId = this.extensionBridge.getCurrentFrameId();
|
|
1452
|
+
const staleContextRetry = options.staleContextRetry ?? 'never';
|
|
958
1453
|
// precise + args + 主 frame:使用 callFunctionOn 避免大 payload 字符串拼接
|
|
959
1454
|
if (hasArgs && currentFrameId === 0) {
|
|
960
|
-
return this.callFunctionOn(code, args, timeout);
|
|
1455
|
+
return this.callFunctionOn(code, args, timeout, options);
|
|
961
1456
|
}
|
|
962
1457
|
if (currentFrameId !== 0) {
|
|
963
1458
|
// iframe:args 仍用字符串拼接(evaluateInFrame 使用 expression 字符串)
|
|
@@ -989,11 +1484,26 @@ class UnifiedSessionManager {
|
|
|
989
1484
|
if (result.exceptionDetails) {
|
|
990
1485
|
throw new Error(formatCdpException(result.exceptionDetails));
|
|
991
1486
|
}
|
|
992
|
-
return this.materializeCdpResult(result.result, timeout);
|
|
1487
|
+
return this.materializeCdpResult(result.result, timeout, options.fileOutput);
|
|
993
1488
|
}
|
|
994
1489
|
async evaluateViaExtensionStealth(expression, timeout) {
|
|
995
1490
|
return (await this.extensionBridge.evaluate(expression, undefined, timeout));
|
|
996
1491
|
}
|
|
1492
|
+
async readViewportMetrics(frameId) {
|
|
1493
|
+
let raw;
|
|
1494
|
+
try {
|
|
1495
|
+
raw = await this.extensionBridge.getViewportMetrics(frameId);
|
|
1496
|
+
}
|
|
1497
|
+
catch (error) {
|
|
1498
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1499
|
+
throw new OsMouseError('TURNSTILE_OS_CLICK_UNAVAILABLE', `卸掉 debugger 后无法读取视口: ${message}`, '把受控测试页放到已经聚焦的窗口并保持该 tab 为活动页后重试;混合窗口不会调用 focusWindow');
|
|
1500
|
+
}
|
|
1501
|
+
const viewport = asViewportMetrics(raw);
|
|
1502
|
+
if (!viewport) {
|
|
1503
|
+
throw new OsMouseError('TURNSTILE_OS_CLICK_UNAVAILABLE', '卸掉 debugger 后读到的视口无效', '把受控测试页放到已经聚焦的窗口并保持该 tab 为活动页后重试;混合窗口不会调用 focusWindow');
|
|
1504
|
+
}
|
|
1505
|
+
return viewport;
|
|
1506
|
+
}
|
|
997
1507
|
/**
|
|
998
1508
|
* Extension 操作断连自动重试
|
|
999
1509
|
*
|
|
@@ -1047,12 +1557,19 @@ class UnifiedSessionManager {
|
|
|
1047
1557
|
}
|
|
1048
1558
|
return extractCdpValue(result.result);
|
|
1049
1559
|
}
|
|
1050
|
-
async materializeCdpResult(result, timeout) {
|
|
1560
|
+
async materializeCdpResult(result, timeout, fileOutput = false) {
|
|
1051
1561
|
if (!result?.objectId) {
|
|
1052
1562
|
return extractCdpValue(result);
|
|
1053
1563
|
}
|
|
1054
1564
|
try {
|
|
1055
|
-
return await this.materializeRemoteObject(result, timeout, {
|
|
1565
|
+
return await this.materializeRemoteObject(result, timeout, {
|
|
1566
|
+
seen: new Set(),
|
|
1567
|
+
nodes: 0,
|
|
1568
|
+
chars: 0,
|
|
1569
|
+
maxChars: fileOutput
|
|
1570
|
+
? UnifiedSessionManager.CDP_MATERIALIZE_MAX_FILE_CHARS
|
|
1571
|
+
: UnifiedSessionManager.CDP_MATERIALIZE_MAX_CHARS,
|
|
1572
|
+
}, 0);
|
|
1056
1573
|
}
|
|
1057
1574
|
finally {
|
|
1058
1575
|
this.extensionBridge.debuggerSend('Runtime.releaseObject', { objectId: result.objectId }).catch(() => { });
|
|
@@ -1149,7 +1666,7 @@ class UnifiedSessionManager {
|
|
|
1149
1666
|
assertMaterializeBudget(state, depth, result) {
|
|
1150
1667
|
if (depth > UnifiedSessionManager.CDP_MATERIALIZE_MAX_DEPTH ||
|
|
1151
1668
|
state.nodes > UnifiedSessionManager.CDP_MATERIALIZE_MAX_NODES ||
|
|
1152
|
-
state.chars >
|
|
1669
|
+
state.chars > state.maxChars) {
|
|
1153
1670
|
this.throwMaterializeLimit(state, depth, result);
|
|
1154
1671
|
}
|
|
1155
1672
|
}
|
|
@@ -1166,7 +1683,7 @@ class UnifiedSessionManager {
|
|
|
1166
1683
|
chars: state.chars,
|
|
1167
1684
|
maxDepth: UnifiedSessionManager.CDP_MATERIALIZE_MAX_DEPTH,
|
|
1168
1685
|
maxNodes: UnifiedSessionManager.CDP_MATERIALIZE_MAX_NODES,
|
|
1169
|
-
maxChars:
|
|
1686
|
+
maxChars: state.maxChars,
|
|
1170
1687
|
type: result?.type,
|
|
1171
1688
|
subtype: result?.subtype,
|
|
1172
1689
|
className: result?.className,
|
|
@@ -1200,31 +1717,35 @@ class UnifiedSessionManager {
|
|
|
1200
1717
|
* 避免工具 timeout 被连接等待吞掉,不传则使用默认 30s
|
|
1201
1718
|
*/
|
|
1202
1719
|
async getDriver(timeout) {
|
|
1203
|
-
if (this.activeMode === 'cdp' && getCdpSession().isConnected()) {
|
|
1720
|
+
if (this.activeMode === 'cdp' && this.cdpExplicitlySelected && getCdpSession().isConnected()) {
|
|
1204
1721
|
this.assertCdpFallbackAllowed();
|
|
1205
1722
|
return getCdpSession();
|
|
1206
1723
|
}
|
|
1207
1724
|
if (await this.ensureExtensionConnected(timeout)) {
|
|
1208
1725
|
this.activeMode = 'extension';
|
|
1726
|
+
this.cdpExplicitlySelected = false;
|
|
1209
1727
|
return this.extensionBridge;
|
|
1210
1728
|
}
|
|
1211
1729
|
this.activeMode = 'cdp';
|
|
1730
|
+
this.cdpExplicitlySelected = false;
|
|
1212
1731
|
return getCdpSession();
|
|
1213
1732
|
}
|
|
1214
1733
|
async ensureExtensionConnected(maxWait) {
|
|
1215
1734
|
if (!this.extensionBridge) {
|
|
1216
1735
|
return this.assertCdpFallbackAllowed();
|
|
1217
1736
|
}
|
|
1218
|
-
if (this.activeMode === 'cdp' && getCdpSession().isConnected()) {
|
|
1737
|
+
if (this.activeMode === 'cdp' && this.cdpExplicitlySelected && getCdpSession().isConnected()) {
|
|
1219
1738
|
return this.assertCdpFallbackAllowed();
|
|
1220
1739
|
}
|
|
1221
1740
|
if (this.extensionBridge.isConnected()) {
|
|
1222
1741
|
this.activeMode = 'extension';
|
|
1742
|
+
this.cdpExplicitlySelected = false;
|
|
1223
1743
|
return true;
|
|
1224
1744
|
}
|
|
1225
1745
|
// CDP 已连接时跳过 Extension 等待,直接使用 CDP 回退
|
|
1226
1746
|
if (getCdpSession().isConnected()) {
|
|
1227
1747
|
this.activeMode = 'cdp';
|
|
1748
|
+
this.cdpExplicitlySelected = false;
|
|
1228
1749
|
return this.assertCdpFallbackAllowed();
|
|
1229
1750
|
}
|
|
1230
1751
|
// 冷却期内不重复等待,避免每次操作都阻塞 30 秒
|
|
@@ -1255,7 +1776,7 @@ class UnifiedSessionManager {
|
|
|
1255
1776
|
* 参数通过 CDP 协议结构化传递,避免大 payload 字符串拼接导致的长度限制和转义问题,
|
|
1256
1777
|
* 要求 code 必须是函数表达式(如 "(x) => x + 1")
|
|
1257
1778
|
*/
|
|
1258
|
-
async callFunctionOn(code, args, timeout) {
|
|
1779
|
+
async callFunctionOn(code, args, timeout, options = {}) {
|
|
1259
1780
|
const buildFallbackExpression = () => `(${code})(${args.map((a) => JSON.stringify(a)).join(', ')})`;
|
|
1260
1781
|
const globalResult = (await this.extensionBridge.debuggerSend('Runtime.evaluate', {
|
|
1261
1782
|
expression: 'globalThis',
|
|
@@ -1263,8 +1784,9 @@ class UnifiedSessionManager {
|
|
|
1263
1784
|
}, undefined, timeout));
|
|
1264
1785
|
const globalObjectId = globalResult.result?.objectId;
|
|
1265
1786
|
if (!globalObjectId) {
|
|
1787
|
+
console.warn('[MCP] Runtime.evaluate 未返回 globalThis objectId,改用表达式传递 evaluate args');
|
|
1266
1788
|
const fallbackExpression = buildFallbackExpression();
|
|
1267
|
-
return this.evaluateViaExtensionPrecise(fallbackExpression, fallbackExpression, undefined, timeout);
|
|
1789
|
+
return this.evaluateViaExtensionPrecise(fallbackExpression, fallbackExpression, undefined, timeout, options);
|
|
1268
1790
|
}
|
|
1269
1791
|
try {
|
|
1270
1792
|
const params = {
|
|
@@ -1277,22 +1799,11 @@ class UnifiedSessionManager {
|
|
|
1277
1799
|
if (timeout !== undefined) {
|
|
1278
1800
|
params.timeout = timeout;
|
|
1279
1801
|
}
|
|
1280
|
-
|
|
1281
|
-
try {
|
|
1282
|
-
result = (await this.extensionBridge.debuggerSend('Runtime.callFunctionOn', params, undefined, timeout));
|
|
1283
|
-
}
|
|
1284
|
-
catch (error) {
|
|
1285
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
1286
|
-
if (message.includes('Either objectId or executionContextId or uniqueContextId must be specified')) {
|
|
1287
|
-
const fallbackExpression = buildFallbackExpression();
|
|
1288
|
-
return this.evaluateViaExtensionPrecise(fallbackExpression, fallbackExpression, undefined, timeout);
|
|
1289
|
-
}
|
|
1290
|
-
throw error;
|
|
1291
|
-
}
|
|
1802
|
+
const result = (await this.extensionBridge.debuggerSend('Runtime.callFunctionOn', params, undefined, timeout));
|
|
1292
1803
|
if (result.exceptionDetails) {
|
|
1293
1804
|
throw new Error(formatCdpException(result.exceptionDetails));
|
|
1294
1805
|
}
|
|
1295
|
-
return await this.materializeCdpResult(result.result, timeout);
|
|
1806
|
+
return await this.materializeCdpResult(result.result, timeout, options.fileOutput);
|
|
1296
1807
|
}
|
|
1297
1808
|
finally {
|
|
1298
1809
|
this.extensionBridge.debuggerSend('Runtime.releaseObject', {
|
|
@@ -1300,27 +1811,6 @@ class UnifiedSessionManager {
|
|
|
1300
1811
|
}).catch(() => { });
|
|
1301
1812
|
}
|
|
1302
1813
|
}
|
|
1303
|
-
/**
|
|
1304
|
-
* 串行化所有 tab 切换操作,防止并发请求互相覆盖 currentTabId,
|
|
1305
|
-
* 调用者:selectPage/activatePage/newPage/closePage/navigate/reload/launch/withTabId
|
|
1306
|
-
*
|
|
1307
|
-
* 注意:此锁不可重入,fn() 内禁止调用任何使用 withTabLock 的方法,否则会死锁,
|
|
1308
|
-
* 当前所有 fn() 只调用 bridge 的原子操作(createTab/navigate/evaluate 等),不存在此问题
|
|
1309
|
-
*/
|
|
1310
|
-
async withTabLock(fn) {
|
|
1311
|
-
const previousLock = this.tabSwitchLock;
|
|
1312
|
-
let releaseLock;
|
|
1313
|
-
this.tabSwitchLock = new Promise((resolve) => {
|
|
1314
|
-
releaseLock = resolve;
|
|
1315
|
-
});
|
|
1316
|
-
try {
|
|
1317
|
-
await previousLock;
|
|
1318
|
-
return await fn();
|
|
1319
|
-
}
|
|
1320
|
-
finally {
|
|
1321
|
-
releaseLock();
|
|
1322
|
-
}
|
|
1323
|
-
}
|
|
1324
1814
|
}
|
|
1325
1815
|
/**
|
|
1326
1816
|
* 获取统一会话管理器实例
|