@thinkingos/vsl-mcp-server 1.4.4 → 1.4.6
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/dist/index.js +1230 -698
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -219,7 +219,8 @@ var init_browserBinary = __esm({
|
|
|
219
219
|
// src/config/loader.ts
|
|
220
220
|
var loader_exports = {};
|
|
221
221
|
__export(loader_exports, {
|
|
222
|
-
loadConfig: () => loadConfig
|
|
222
|
+
loadConfig: () => loadConfig,
|
|
223
|
+
parseManualLoginConfig: () => parseManualLoginConfig
|
|
223
224
|
});
|
|
224
225
|
import { readFileSync, existsSync as existsSync2 } from "fs";
|
|
225
226
|
import { homedir } from "os";
|
|
@@ -245,7 +246,8 @@ function loadConfig() {
|
|
|
245
246
|
cdpPort: process.env.VSL_CDP_PORT ? parseInt(process.env.VSL_CDP_PORT, 10) : fileConfig.browser?.cdpPort ?? DEFAULT_BROWSER_CONFIG.cdpPort,
|
|
246
247
|
autoInstallBrowser: process.env.VSL_BROWSER_AUTO_INSTALL ? process.env.VSL_BROWSER_AUTO_INSTALL === "true" : fileConfig.browser?.autoInstallBrowser ?? DEFAULT_BROWSER_CONFIG.autoInstallBrowser,
|
|
247
248
|
browserInstallTimeout: process.env.VSL_BROWSER_INSTALL_TIMEOUT ? parseInt(process.env.VSL_BROWSER_INSTALL_TIMEOUT, 10) : fileConfig.browser?.browserInstallTimeout ?? DEFAULT_BROWSER_CONFIG.browserInstallTimeout,
|
|
248
|
-
proxy: parseProxyConfig(fileConfig)
|
|
249
|
+
proxy: parseProxyConfig(fileConfig),
|
|
250
|
+
manualLogin: parseManualLoginConfig(fileConfig)
|
|
249
251
|
};
|
|
250
252
|
const humanization = parseHumanizationConfig(fileConfig);
|
|
251
253
|
const domStabilization = parseDomStabilizationConfig(fileConfig);
|
|
@@ -290,6 +292,30 @@ function parseDomStabilizationConfig(fileConfig) {
|
|
|
290
292
|
const networkIdleTimeout = process.env.VSL_DOM_STABILIZATION_NETWORK_IDLE_TIMEOUT ? parseInt(process.env.VSL_DOM_STABILIZATION_NETWORK_IDLE_TIMEOUT, 10) : fileDomStab?.networkIdleTimeout ?? DEFAULT_DOM_STABILIZATION_CONFIG.networkIdleTimeout;
|
|
291
293
|
return { enabled, timeout, stablePeriod, pollInterval, waitForNetworkIdle, networkIdleTimeout };
|
|
292
294
|
}
|
|
295
|
+
function parseManualLoginConfig(fileConfig) {
|
|
296
|
+
const fileManualLogin = fileConfig.browser?.manualLogin;
|
|
297
|
+
const timeoutMs = parseManualLoginInt(
|
|
298
|
+
process.env.VSL_MANUAL_LOGIN_TIMEOUT,
|
|
299
|
+
fileManualLogin?.timeoutMs,
|
|
300
|
+
DEFAULT_MANUAL_LOGIN_CONFIG.timeoutMs,
|
|
301
|
+
1e3,
|
|
302
|
+
6e5
|
|
303
|
+
);
|
|
304
|
+
const pollIntervalMs = parseManualLoginInt(
|
|
305
|
+
process.env.VSL_MANUAL_LOGIN_POLL_INTERVAL,
|
|
306
|
+
fileManualLogin?.pollIntervalMs,
|
|
307
|
+
DEFAULT_MANUAL_LOGIN_CONFIG.pollIntervalMs,
|
|
308
|
+
250,
|
|
309
|
+
1e4
|
|
310
|
+
);
|
|
311
|
+
const restoreHeadless = process.env.VSL_MANUAL_LOGIN_RESTORE_HEADLESS !== void 0 && process.env.VSL_MANUAL_LOGIN_RESTORE_HEADLESS !== "" ? process.env.VSL_MANUAL_LOGIN_RESTORE_HEADLESS === "true" : fileManualLogin?.restoreHeadless ?? DEFAULT_MANUAL_LOGIN_CONFIG.restoreHeadless;
|
|
312
|
+
return { timeoutMs, pollIntervalMs, restoreHeadless };
|
|
313
|
+
}
|
|
314
|
+
function parseManualLoginInt(envValue, fileValue, defaultValue, min, max) {
|
|
315
|
+
const raw = envValue !== void 0 && envValue !== "" ? Number(envValue) : fileValue;
|
|
316
|
+
if (raw === void 0 || !Number.isFinite(raw)) return defaultValue;
|
|
317
|
+
return Math.min(max, Math.max(min, Math.trunc(raw)));
|
|
318
|
+
}
|
|
293
319
|
function loadConfigFile() {
|
|
294
320
|
if (!existsSync2(DEFAULT_CONFIG_PATH)) {
|
|
295
321
|
return {};
|
|
@@ -302,7 +328,7 @@ function loadConfigFile() {
|
|
|
302
328
|
return {};
|
|
303
329
|
}
|
|
304
330
|
}
|
|
305
|
-
var DEFAULT_CONFIG_PATH, DEFAULT_VISION_MODELS, DEFAULT_BROWSER_CONFIG, DEFAULT_HUMANIZATION_CONFIG;
|
|
331
|
+
var DEFAULT_CONFIG_PATH, DEFAULT_VISION_MODELS, DEFAULT_MANUAL_LOGIN_CONFIG, DEFAULT_BROWSER_CONFIG, DEFAULT_HUMANIZATION_CONFIG;
|
|
306
332
|
var init_loader = __esm({
|
|
307
333
|
"src/config/loader.ts"() {
|
|
308
334
|
"use strict";
|
|
@@ -315,6 +341,14 @@ var init_loader = __esm({
|
|
|
315
341
|
custom: ""
|
|
316
342
|
// Пользователь должен указать модель для custom провайдера
|
|
317
343
|
};
|
|
344
|
+
DEFAULT_MANUAL_LOGIN_CONFIG = {
|
|
345
|
+
timeoutMs: 18e4,
|
|
346
|
+
// 3 минуты на ручной вход (капча, 2FA)
|
|
347
|
+
pollIntervalMs: 2e3,
|
|
348
|
+
// опрос признака входа каждые 2с
|
|
349
|
+
restoreHeadless: false
|
|
350
|
+
// видимое окно остаётся жить (session-cookie/sessionStorage)
|
|
351
|
+
};
|
|
318
352
|
DEFAULT_BROWSER_CONFIG = {
|
|
319
353
|
headless: true,
|
|
320
354
|
navigationTimeout: 3e4,
|
|
@@ -328,7 +362,8 @@ var init_loader = __esm({
|
|
|
328
362
|
// Дефолтный CDP port для подключения множественных агентов
|
|
329
363
|
autoInstallBrowser: true,
|
|
330
364
|
// Self-heal: скачивать браузер, если кэш Playwright очищен
|
|
331
|
-
browserInstallTimeout: DEFAULT_BROWSER_INSTALL_TIMEOUT_MS
|
|
365
|
+
browserInstallTimeout: DEFAULT_BROWSER_INSTALL_TIMEOUT_MS,
|
|
366
|
+
manualLogin: DEFAULT_MANUAL_LOGIN_CONFIG
|
|
332
367
|
};
|
|
333
368
|
DEFAULT_HUMANIZATION_CONFIG = {
|
|
334
369
|
enabled: true,
|
|
@@ -3972,492 +4007,135 @@ async function handleClickCoordinates(args, browser, session, sessionId) {
|
|
|
3972
4007
|
}
|
|
3973
4008
|
}
|
|
3974
4009
|
|
|
3975
|
-
// src/
|
|
3976
|
-
|
|
3977
|
-
|
|
3978
|
-
|
|
3979
|
-
|
|
3980
|
-
|
|
3981
|
-
|
|
3982
|
-
|
|
3983
|
-
|
|
3984
|
-
|
|
3985
|
-
|
|
3986
|
-
|
|
3987
|
-
|
|
3988
|
-
|
|
3989
|
-
|
|
3990
|
-
|
|
3991
|
-
|
|
3992
|
-
|
|
3993
|
-
|
|
3994
|
-
|
|
3995
|
-
|
|
3996
|
-
|
|
3997
|
-
|
|
3998
|
-
|
|
4010
|
+
// src/browser/manager.ts
|
|
4011
|
+
import path2 from "path";
|
|
4012
|
+
import os from "os";
|
|
4013
|
+
|
|
4014
|
+
// src/browser/challengeResolver.ts
|
|
4015
|
+
var ChallengeResolutionError = class extends Error {
|
|
4016
|
+
constructor(url, timeoutMs) {
|
|
4017
|
+
super(
|
|
4018
|
+
`Anti-bot challenge was not resolved within ${timeoutMs}ms for ${url}. The persistent browser profile stores cf_clearance cookies \u2014 retrying later may pass automatically. Alternatives: connect to a real browser via CDP (browser.cdpPort) or configure a proxy (browser.proxy). Or log in manually in a visible window: call vsl_manual_login with {action:"open", url:"<login page URL>"}.`
|
|
4019
|
+
);
|
|
4020
|
+
this.name = "ChallengeResolutionError";
|
|
4021
|
+
}
|
|
4022
|
+
};
|
|
4023
|
+
var TITLE_MARKERS = [
|
|
4024
|
+
/just a moment/i,
|
|
4025
|
+
/attention required/i,
|
|
4026
|
+
/checking your browser/i,
|
|
4027
|
+
/verify you are human/i
|
|
4028
|
+
];
|
|
4029
|
+
var PRIMARY_HTML_MARKERS = ["cf-chl", "challenges.cloudflare.com"];
|
|
4030
|
+
var PRIMARY_URL_MARKERS = ["/cdn-cgi/challenge-platform", "challenges.cloudflare.com"];
|
|
4031
|
+
function detectChallengeMarkers(input) {
|
|
4032
|
+
const title = input.title ?? "";
|
|
4033
|
+
const html = (input.html ?? "").toLowerCase();
|
|
4034
|
+
const url = input.url ?? "";
|
|
4035
|
+
const titleHit = TITLE_MARKERS.some((m) => m.test(title));
|
|
4036
|
+
const htmlHit = PRIMARY_HTML_MARKERS.some((m) => html.includes(m));
|
|
4037
|
+
const urlHit = PRIMARY_URL_MARKERS.some((m) => url.includes(m));
|
|
4038
|
+
if (!titleHit && !htmlHit && !urlHit) {
|
|
4039
|
+
return { isChallenge: false, kind: null };
|
|
4040
|
+
}
|
|
4041
|
+
const kind = html.includes("challenges.cloudflare.com") || html.includes("turnstile") ? "turnstile" : "cloudflare";
|
|
4042
|
+
return { isChallenge: true, kind };
|
|
4043
|
+
}
|
|
4044
|
+
function pickCheckboxPoint(rect, rng = Math.random) {
|
|
4045
|
+
const offsetX = Math.min(rect.width * 0.2, 24 + rng() * 8);
|
|
4046
|
+
const offsetY = rect.height / 2 + (rng() - 0.5) * Math.min(6, rect.height * 0.2);
|
|
4047
|
+
return { x: rect.x + offsetX, y: rect.y + offsetY };
|
|
4048
|
+
}
|
|
4049
|
+
async function inspectPage(page) {
|
|
4050
|
+
const probe = await page.evaluate(() => {
|
|
4051
|
+
let turnstileRect = null;
|
|
4052
|
+
const iframes = Array.from(document.querySelectorAll("iframe"));
|
|
4053
|
+
for (const frame of iframes) {
|
|
4054
|
+
const src = frame.getAttribute("src") ?? "";
|
|
4055
|
+
if (src.includes("challenges.cloudflare.com") || src.includes("challenge-platform") || src.includes("turnstile")) {
|
|
4056
|
+
const rect = frame.getBoundingClientRect();
|
|
4057
|
+
if (rect.width > 0 && rect.height > 0) {
|
|
4058
|
+
turnstileRect = { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
|
|
4059
|
+
break;
|
|
3999
4060
|
}
|
|
4000
4061
|
}
|
|
4001
4062
|
}
|
|
4002
|
-
|
|
4003
|
-
|
|
4004
|
-
|
|
4005
|
-
|
|
4006
|
-
|
|
4007
|
-
|
|
4008
|
-
|
|
4009
|
-
|
|
4010
|
-
|
|
4011
|
-
|
|
4012
|
-
|
|
4013
|
-
|
|
4014
|
-
|
|
4015
|
-
|
|
4016
|
-
|
|
4017
|
-
|
|
4018
|
-
|
|
4019
|
-
|
|
4020
|
-
|
|
4021
|
-
|
|
4022
|
-
|
|
4023
|
-
|
|
4024
|
-
|
|
4025
|
-
|
|
4026
|
-
|
|
4027
|
-
|
|
4028
|
-
|
|
4029
|
-
|
|
4030
|
-
|
|
4031
|
-
|
|
4032
|
-
|
|
4033
|
-
|
|
4034
|
-
|
|
4035
|
-
|
|
4036
|
-
}
|
|
4037
|
-
|
|
4038
|
-
|
|
4039
|
-
|
|
4040
|
-
|
|
4041
|
-
|
|
4042
|
-
|
|
4043
|
-
|
|
4044
|
-
|
|
4045
|
-
|
|
4046
|
-
|
|
4047
|
-
|
|
4048
|
-
|
|
4049
|
-
|
|
4050
|
-
|
|
4051
|
-
|
|
4052
|
-
|
|
4053
|
-
|
|
4054
|
-
|
|
4055
|
-
|
|
4056
|
-
|
|
4057
|
-
|
|
4058
|
-
|
|
4059
|
-
|
|
4060
|
-
|
|
4061
|
-
|
|
4062
|
-
|
|
4063
|
-
|
|
4064
|
-
|
|
4065
|
-
|
|
4066
|
-
|
|
4067
|
-
|
|
4068
|
-
},
|
|
4069
|
-
auto_refresh: {
|
|
4070
|
-
type: "boolean",
|
|
4071
|
-
description: "If true, automatically refreshes the snapshot before searching for the element. Useful after navigation or actions that modify the DOM. Default: false."
|
|
4063
|
+
return {
|
|
4064
|
+
title: document.title,
|
|
4065
|
+
htmlSnippet: document.documentElement.innerHTML.slice(0, 3e4),
|
|
4066
|
+
url: window.location.href,
|
|
4067
|
+
turnstileRect,
|
|
4068
|
+
viewportWidth: window.innerWidth,
|
|
4069
|
+
viewportHeight: window.innerHeight
|
|
4070
|
+
};
|
|
4071
|
+
});
|
|
4072
|
+
const detection = detectChallengeMarkers({
|
|
4073
|
+
title: probe.title,
|
|
4074
|
+
html: probe.htmlSnippet,
|
|
4075
|
+
url: probe.url
|
|
4076
|
+
});
|
|
4077
|
+
return {
|
|
4078
|
+
isChallenge: detection.isChallenge,
|
|
4079
|
+
kind: detection.kind,
|
|
4080
|
+
turnstileRect: probe.turnstileRect,
|
|
4081
|
+
viewportWidth: probe.viewportWidth,
|
|
4082
|
+
viewportHeight: probe.viewportHeight
|
|
4083
|
+
};
|
|
4084
|
+
}
|
|
4085
|
+
async function humanLikeClick(page, inspection, rng) {
|
|
4086
|
+
if (!inspection.turnstileRect) return;
|
|
4087
|
+
const target = pickCheckboxPoint(inspection.turnstileRect, rng);
|
|
4088
|
+
const start = {
|
|
4089
|
+
x: inspection.viewportWidth * (0.3 + rng() * 0.4),
|
|
4090
|
+
y: inspection.viewportHeight * (0.3 + rng() * 0.4)
|
|
4091
|
+
};
|
|
4092
|
+
await performHumanClick(page.mouse, start, target, { rng, waiter: page });
|
|
4093
|
+
}
|
|
4094
|
+
function safeOrigin(url) {
|
|
4095
|
+
try {
|
|
4096
|
+
return new URL(url).origin;
|
|
4097
|
+
} catch {
|
|
4098
|
+
return null;
|
|
4099
|
+
}
|
|
4100
|
+
}
|
|
4101
|
+
async function resolveChallenge(page, targetUrl, options = {}) {
|
|
4102
|
+
const timeoutMs = options.timeoutMs ?? 2e4;
|
|
4103
|
+
const pollIntervalMs = options.pollIntervalMs ?? 2e3;
|
|
4104
|
+
const enableClick = options.enableClick !== false;
|
|
4105
|
+
const warmUp = options.warmUp !== false;
|
|
4106
|
+
const rng = options.rng ?? Math.random;
|
|
4107
|
+
let inspection = await inspectPage(page);
|
|
4108
|
+
if (!inspection.isChallenge) {
|
|
4109
|
+
return { status: "not_detected", attempts: 0 };
|
|
4110
|
+
}
|
|
4111
|
+
console.warn(
|
|
4112
|
+
`[VSL MCP Server] Anti-bot challenge detected (${inspection.kind ?? "generic"}) at ${targetUrl} \u2014 resolving (timeout ${timeoutMs}ms)`
|
|
4113
|
+
);
|
|
4114
|
+
const deadline = Date.now() + timeoutMs;
|
|
4115
|
+
let attempts = 0;
|
|
4116
|
+
let warmedUp = false;
|
|
4117
|
+
let clicked = false;
|
|
4118
|
+
while (Date.now() < deadline) {
|
|
4119
|
+
attempts++;
|
|
4120
|
+
if (warmUp && !warmedUp) {
|
|
4121
|
+
warmedUp = true;
|
|
4122
|
+
const origin = safeOrigin(targetUrl);
|
|
4123
|
+
if (origin && origin !== targetUrl) {
|
|
4124
|
+
try {
|
|
4125
|
+
await page.goto(origin, { timeout: timeoutMs, waitUntil: "domcontentloaded" });
|
|
4126
|
+
await page.waitForTimeout(Math.round(pollIntervalMs / 2));
|
|
4127
|
+
await page.goto(targetUrl, { timeout: timeoutMs, waitUntil: "domcontentloaded" });
|
|
4128
|
+
} catch {
|
|
4072
4129
|
}
|
|
4073
|
-
}
|
|
4074
|
-
required: ["element_id"]
|
|
4130
|
+
}
|
|
4075
4131
|
}
|
|
4076
|
-
|
|
4077
|
-
|
|
4078
|
-
|
|
4079
|
-
description: 'Read web pages. Automatically determines the strategy: static pages are read via HTTP (fast), SPAs are rendered via browser. readable=true filters noise (navigation, footers, cookie banners) for clean content. On repeated calls, returns diff (changes) instead of full content. Parameter detail_level (low/medium/high) filters objects in the snapshot: low \u2014 interactive elements only (buttons, links, inputs), medium \u2014 interactive + containers (default), high \u2014 all objects. Metadata includes vsl_estimated_tokens \u2014 the number of tokens in the VSL snapshot for context estimation. Example: {url:"https://example.com", readable:true, detail_level:"medium"}. Returns snapshot and diff automatically.',
|
|
4080
|
-
inputSchema: {
|
|
4081
|
-
type: "object",
|
|
4082
|
-
properties: {
|
|
4083
|
-
url: {
|
|
4084
|
-
type: "string",
|
|
4085
|
-
description: "Page URL to read"
|
|
4086
|
-
},
|
|
4087
|
-
readable: {
|
|
4088
|
-
type: "boolean",
|
|
4089
|
-
description: "Readable mode: filter noise (nav, footer, cookie banners) for clean content"
|
|
4090
|
-
}
|
|
4091
|
-
},
|
|
4092
|
-
required: ["url"]
|
|
4132
|
+
inspection = await inspectPage(page);
|
|
4133
|
+
if (!inspection.isChallenge) {
|
|
4134
|
+
return { status: clicked ? "clicked" : "auto", attempts };
|
|
4093
4135
|
}
|
|
4094
|
-
|
|
4095
|
-
|
|
4096
|
-
|
|
4097
|
-
description: `Get the full text by txt_ref from lazy text loading (M1.7). When an element's text exceeds 200 characters, only txt_preview (first ~50 characters) and txt_ref (e.g. tb_001) are stored in the VSL JSON. Use this tool to retrieve the full text. Example: {block_id: "tb_001"}. Returns {block_id, text} with the full content.`,
|
|
4098
|
-
inputSchema: {
|
|
4099
|
-
type: "object",
|
|
4100
|
-
properties: {
|
|
4101
|
-
block_id: {
|
|
4102
|
-
type: "string",
|
|
4103
|
-
description: "Text block ID from the txt_ref field of a VSL object (format: tb_xxx)"
|
|
4104
|
-
}
|
|
4105
|
-
},
|
|
4106
|
-
required: ["block_id"]
|
|
4107
|
-
}
|
|
4108
|
-
},
|
|
4109
|
-
{
|
|
4110
|
-
name: "vsl_click_coordinates",
|
|
4111
|
-
description: 'Perform multiple clicks at coordinates relative to a target element. Coordinates (x, y) are specified in pixels from the top-left corner of the element (use bbox from snapshot). Supports delays between clicks. Returns diff + snapshot + screenshot after all clicks. Example: {target_id: "iframe_2", clicks: [{x: 50, y: 50, delay_after_ms: 500}, {x: 150, y: 50}]}.',
|
|
4112
|
-
inputSchema: {
|
|
4113
|
-
type: "object",
|
|
4114
|
-
properties: {
|
|
4115
|
-
target_id: {
|
|
4116
|
-
type: "string",
|
|
4117
|
-
description: "Element ID in VSL JSON (e.g. iframe_2 for reCAPTCHA challenge iframe)"
|
|
4118
|
-
},
|
|
4119
|
-
clicks: {
|
|
4120
|
-
type: "array",
|
|
4121
|
-
description: "Array of clicks. Each click: {x: number, y: number, delay_after_ms?: number}. Coordinates in pixels from the top-left corner of the element.",
|
|
4122
|
-
items: {
|
|
4123
|
-
type: "object",
|
|
4124
|
-
properties: {
|
|
4125
|
-
x: { type: "number", description: "X coordinate (pixels from left edge of element)" },
|
|
4126
|
-
y: { type: "number", description: "Y coordinate (pixels from top edge of element)" },
|
|
4127
|
-
delay_after_ms: { type: "number", description: "Delay after click (ms)" }
|
|
4128
|
-
},
|
|
4129
|
-
required: ["x", "y"]
|
|
4130
|
-
}
|
|
4131
|
-
},
|
|
4132
|
-
return_state: {
|
|
4133
|
-
type: "boolean",
|
|
4134
|
-
description: "If true (default), returns diff + snapshot + screenshot after all clicks."
|
|
4135
|
-
}
|
|
4136
|
-
},
|
|
4137
|
-
required: ["target_id", "clicks"]
|
|
4138
|
-
}
|
|
4139
|
-
}
|
|
4140
|
-
];
|
|
4141
|
-
function registerTools(server, config, sessionManager) {
|
|
4142
|
-
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
4143
|
-
return {
|
|
4144
|
-
tools: VSL_TOOLS
|
|
4145
|
-
};
|
|
4146
|
-
});
|
|
4147
|
-
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
4148
|
-
const { name, arguments: args, _meta } = request.params;
|
|
4149
|
-
const sessionId = _meta?.sessionId ?? sessionManager.getDefaultSessionId();
|
|
4150
|
-
const { session } = sessionManager.getSession(sessionId);
|
|
4151
|
-
const browser = sessionManager.getBrowserManager();
|
|
4152
|
-
try {
|
|
4153
|
-
let result;
|
|
4154
|
-
switch (name) {
|
|
4155
|
-
case "vsl_get_snapshot":
|
|
4156
|
-
result = await handleGetSnapshot(args, browser, session, config, sessionId);
|
|
4157
|
-
break;
|
|
4158
|
-
case "vsl_execute_action":
|
|
4159
|
-
result = await handleExecuteAction(args, browser, session, sessionId);
|
|
4160
|
-
break;
|
|
4161
|
-
case "vsl_navigate":
|
|
4162
|
-
result = await handleNavigate(args, browser, session, sessionId);
|
|
4163
|
-
break;
|
|
4164
|
-
case "vsl_clear_cache":
|
|
4165
|
-
result = await handleClearCache(session);
|
|
4166
|
-
break;
|
|
4167
|
-
case "vsl_get_visual":
|
|
4168
|
-
result = await handleGetVisual(args, browser, session, sessionId);
|
|
4169
|
-
break;
|
|
4170
|
-
case "vsl_read_page":
|
|
4171
|
-
result = await handleReadPage(args, browser, session, config, sessionId);
|
|
4172
|
-
break;
|
|
4173
|
-
case "vsl_get_text_block":
|
|
4174
|
-
result = await handleGetTextBlock(args, session);
|
|
4175
|
-
break;
|
|
4176
|
-
case "vsl_click_coordinates":
|
|
4177
|
-
result = await handleClickCoordinates(args, browser, session, sessionId);
|
|
4178
|
-
break;
|
|
4179
|
-
default:
|
|
4180
|
-
return {
|
|
4181
|
-
content: [
|
|
4182
|
-
{
|
|
4183
|
-
type: "text",
|
|
4184
|
-
text: JSON.stringify({
|
|
4185
|
-
error: `Unknown tool: ${name}`
|
|
4186
|
-
})
|
|
4187
|
-
}
|
|
4188
|
-
],
|
|
4189
|
-
isError: true
|
|
4190
|
-
};
|
|
4191
|
-
}
|
|
4192
|
-
if (result && typeof result === "object" && "content" in result && Array.isArray(result.content)) {
|
|
4193
|
-
return result;
|
|
4194
|
-
}
|
|
4195
|
-
return {
|
|
4196
|
-
content: [
|
|
4197
|
-
{
|
|
4198
|
-
type: "text",
|
|
4199
|
-
text: JSON.stringify(result)
|
|
4200
|
-
}
|
|
4201
|
-
]
|
|
4202
|
-
};
|
|
4203
|
-
} catch (error) {
|
|
4204
|
-
return {
|
|
4205
|
-
content: [
|
|
4206
|
-
{
|
|
4207
|
-
type: "text",
|
|
4208
|
-
text: JSON.stringify({
|
|
4209
|
-
error: `Tool execution failed: ${error instanceof Error ? error.message : String(error)}`
|
|
4210
|
-
})
|
|
4211
|
-
}
|
|
4212
|
-
],
|
|
4213
|
-
isError: true
|
|
4214
|
-
};
|
|
4215
|
-
}
|
|
4216
|
-
});
|
|
4217
|
-
}
|
|
4218
|
-
|
|
4219
|
-
// src/resources/index.ts
|
|
4220
|
-
import {
|
|
4221
|
-
ListResourcesRequestSchema,
|
|
4222
|
-
ReadResourceRequestSchema
|
|
4223
|
-
} from "@modelcontextprotocol/sdk/types.js";
|
|
4224
|
-
var VSL_RESOURCES = [
|
|
4225
|
-
{
|
|
4226
|
-
uri: "vsl://current",
|
|
4227
|
-
name: "Current VSL Snapshot",
|
|
4228
|
-
description: "Current VSL snapshot of the page. Contains the full semantic structure of elements.",
|
|
4229
|
-
mimeType: "application/json"
|
|
4230
|
-
},
|
|
4231
|
-
{
|
|
4232
|
-
uri: "vsl://diff",
|
|
4233
|
-
name: "Latest VSL Diff",
|
|
4234
|
-
description: "Latest VSL diff since the previous snapshot. Contains only changes (added/modified/removed).",
|
|
4235
|
-
mimeType: "application/json"
|
|
4236
|
-
}
|
|
4237
|
-
];
|
|
4238
|
-
function registerResources(server, _config, sessionManager) {
|
|
4239
|
-
server.setRequestHandler(ListResourcesRequestSchema, async () => {
|
|
4240
|
-
return {
|
|
4241
|
-
resources: VSL_RESOURCES
|
|
4242
|
-
};
|
|
4243
|
-
});
|
|
4244
|
-
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
4245
|
-
const { uri } = request.params;
|
|
4246
|
-
const sessionId = request.params._meta?.sessionId ?? sessionManager.getDefaultSessionId();
|
|
4247
|
-
const { session } = sessionManager.getSession(sessionId);
|
|
4248
|
-
ensureSubscribed(sessionId, session);
|
|
4249
|
-
switch (uri) {
|
|
4250
|
-
case "vsl://current":
|
|
4251
|
-
try {
|
|
4252
|
-
const snapshot = session.getSnapshot();
|
|
4253
|
-
return {
|
|
4254
|
-
contents: [
|
|
4255
|
-
{
|
|
4256
|
-
uri,
|
|
4257
|
-
mimeType: "application/json",
|
|
4258
|
-
text: JSON.stringify(snapshot, null, 2)
|
|
4259
|
-
}
|
|
4260
|
-
]
|
|
4261
|
-
};
|
|
4262
|
-
} catch {
|
|
4263
|
-
return {
|
|
4264
|
-
contents: [
|
|
4265
|
-
{
|
|
4266
|
-
uri,
|
|
4267
|
-
mimeType: "application/json",
|
|
4268
|
-
text: JSON.stringify({
|
|
4269
|
-
error: "No snapshot available. Call vsl_get_snapshot first."
|
|
4270
|
-
})
|
|
4271
|
-
}
|
|
4272
|
-
]
|
|
4273
|
-
};
|
|
4274
|
-
}
|
|
4275
|
-
case "vsl://diff":
|
|
4276
|
-
try {
|
|
4277
|
-
const diff = session.getDiff();
|
|
4278
|
-
if (!diff) {
|
|
4279
|
-
return {
|
|
4280
|
-
contents: [
|
|
4281
|
-
{
|
|
4282
|
-
uri,
|
|
4283
|
-
mimeType: "application/json",
|
|
4284
|
-
text: JSON.stringify({
|
|
4285
|
-
error: "No diff available. This is the first snapshot or no changes detected."
|
|
4286
|
-
})
|
|
4287
|
-
}
|
|
4288
|
-
]
|
|
4289
|
-
};
|
|
4290
|
-
}
|
|
4291
|
-
return {
|
|
4292
|
-
contents: [
|
|
4293
|
-
{
|
|
4294
|
-
uri,
|
|
4295
|
-
mimeType: "application/json",
|
|
4296
|
-
text: JSON.stringify(diff, null, 2)
|
|
4297
|
-
}
|
|
4298
|
-
]
|
|
4299
|
-
};
|
|
4300
|
-
} catch {
|
|
4301
|
-
return {
|
|
4302
|
-
contents: [
|
|
4303
|
-
{
|
|
4304
|
-
uri,
|
|
4305
|
-
mimeType: "application/json",
|
|
4306
|
-
text: JSON.stringify({
|
|
4307
|
-
error: "Failed to compute diff."
|
|
4308
|
-
})
|
|
4309
|
-
}
|
|
4310
|
-
]
|
|
4311
|
-
};
|
|
4312
|
-
}
|
|
4313
|
-
default:
|
|
4314
|
-
throw new Error(`Unknown resource: ${uri}`);
|
|
4315
|
-
}
|
|
4316
|
-
});
|
|
4317
|
-
const subscribedSessions = /* @__PURE__ */ new Set();
|
|
4318
|
-
function ensureSubscribed(sessionId, session) {
|
|
4319
|
-
if (subscribedSessions.has(sessionId)) return;
|
|
4320
|
-
subscribedSessions.add(sessionId);
|
|
4321
|
-
session.setOnSnapshotChange(() => {
|
|
4322
|
-
server.sendResourceUpdated({ uri: "vsl://current" }).catch(() => {
|
|
4323
|
-
});
|
|
4324
|
-
if (session.getDiff()) {
|
|
4325
|
-
server.sendResourceUpdated({ uri: "vsl://diff" }).catch(() => {
|
|
4326
|
-
});
|
|
4327
|
-
}
|
|
4328
|
-
});
|
|
4329
|
-
}
|
|
4330
|
-
}
|
|
4331
|
-
|
|
4332
|
-
// src/browser/manager.ts
|
|
4333
|
-
import path2 from "path";
|
|
4334
|
-
import os from "os";
|
|
4335
|
-
|
|
4336
|
-
// src/browser/challengeResolver.ts
|
|
4337
|
-
var ChallengeResolutionError = class extends Error {
|
|
4338
|
-
constructor(url, timeoutMs) {
|
|
4339
|
-
super(
|
|
4340
|
-
`Anti-bot challenge was not resolved within ${timeoutMs}ms for ${url}. The persistent browser profile stores cf_clearance cookies \u2014 retrying later may pass automatically. Alternatives: connect to a real browser via CDP (browser.cdpPort) or configure a proxy (browser.proxy).`
|
|
4341
|
-
);
|
|
4342
|
-
this.name = "ChallengeResolutionError";
|
|
4343
|
-
}
|
|
4344
|
-
};
|
|
4345
|
-
var TITLE_MARKERS = [
|
|
4346
|
-
/just a moment/i,
|
|
4347
|
-
/attention required/i,
|
|
4348
|
-
/checking your browser/i,
|
|
4349
|
-
/verify you are human/i
|
|
4350
|
-
];
|
|
4351
|
-
var PRIMARY_HTML_MARKERS = ["cf-chl", "challenges.cloudflare.com"];
|
|
4352
|
-
var PRIMARY_URL_MARKERS = ["/cdn-cgi/challenge-platform", "challenges.cloudflare.com"];
|
|
4353
|
-
function detectChallengeMarkers(input) {
|
|
4354
|
-
const title = input.title ?? "";
|
|
4355
|
-
const html = (input.html ?? "").toLowerCase();
|
|
4356
|
-
const url = input.url ?? "";
|
|
4357
|
-
const titleHit = TITLE_MARKERS.some((m) => m.test(title));
|
|
4358
|
-
const htmlHit = PRIMARY_HTML_MARKERS.some((m) => html.includes(m));
|
|
4359
|
-
const urlHit = PRIMARY_URL_MARKERS.some((m) => url.includes(m));
|
|
4360
|
-
if (!titleHit && !htmlHit && !urlHit) {
|
|
4361
|
-
return { isChallenge: false, kind: null };
|
|
4362
|
-
}
|
|
4363
|
-
const kind = html.includes("challenges.cloudflare.com") || html.includes("turnstile") ? "turnstile" : "cloudflare";
|
|
4364
|
-
return { isChallenge: true, kind };
|
|
4365
|
-
}
|
|
4366
|
-
function pickCheckboxPoint(rect, rng = Math.random) {
|
|
4367
|
-
const offsetX = Math.min(rect.width * 0.2, 24 + rng() * 8);
|
|
4368
|
-
const offsetY = rect.height / 2 + (rng() - 0.5) * Math.min(6, rect.height * 0.2);
|
|
4369
|
-
return { x: rect.x + offsetX, y: rect.y + offsetY };
|
|
4370
|
-
}
|
|
4371
|
-
async function inspectPage(page) {
|
|
4372
|
-
const probe = await page.evaluate(() => {
|
|
4373
|
-
let turnstileRect = null;
|
|
4374
|
-
const iframes = Array.from(document.querySelectorAll("iframe"));
|
|
4375
|
-
for (const frame of iframes) {
|
|
4376
|
-
const src = frame.getAttribute("src") ?? "";
|
|
4377
|
-
if (src.includes("challenges.cloudflare.com") || src.includes("challenge-platform") || src.includes("turnstile")) {
|
|
4378
|
-
const rect = frame.getBoundingClientRect();
|
|
4379
|
-
if (rect.width > 0 && rect.height > 0) {
|
|
4380
|
-
turnstileRect = { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
|
|
4381
|
-
break;
|
|
4382
|
-
}
|
|
4383
|
-
}
|
|
4384
|
-
}
|
|
4385
|
-
return {
|
|
4386
|
-
title: document.title,
|
|
4387
|
-
htmlSnippet: document.documentElement.innerHTML.slice(0, 3e4),
|
|
4388
|
-
url: window.location.href,
|
|
4389
|
-
turnstileRect,
|
|
4390
|
-
viewportWidth: window.innerWidth,
|
|
4391
|
-
viewportHeight: window.innerHeight
|
|
4392
|
-
};
|
|
4393
|
-
});
|
|
4394
|
-
const detection = detectChallengeMarkers({
|
|
4395
|
-
title: probe.title,
|
|
4396
|
-
html: probe.htmlSnippet,
|
|
4397
|
-
url: probe.url
|
|
4398
|
-
});
|
|
4399
|
-
return {
|
|
4400
|
-
isChallenge: detection.isChallenge,
|
|
4401
|
-
kind: detection.kind,
|
|
4402
|
-
turnstileRect: probe.turnstileRect,
|
|
4403
|
-
viewportWidth: probe.viewportWidth,
|
|
4404
|
-
viewportHeight: probe.viewportHeight
|
|
4405
|
-
};
|
|
4406
|
-
}
|
|
4407
|
-
async function humanLikeClick(page, inspection, rng) {
|
|
4408
|
-
if (!inspection.turnstileRect) return;
|
|
4409
|
-
const target = pickCheckboxPoint(inspection.turnstileRect, rng);
|
|
4410
|
-
const start = {
|
|
4411
|
-
x: inspection.viewportWidth * (0.3 + rng() * 0.4),
|
|
4412
|
-
y: inspection.viewportHeight * (0.3 + rng() * 0.4)
|
|
4413
|
-
};
|
|
4414
|
-
await performHumanClick(page.mouse, start, target, { rng, waiter: page });
|
|
4415
|
-
}
|
|
4416
|
-
function safeOrigin(url) {
|
|
4417
|
-
try {
|
|
4418
|
-
return new URL(url).origin;
|
|
4419
|
-
} catch {
|
|
4420
|
-
return null;
|
|
4421
|
-
}
|
|
4422
|
-
}
|
|
4423
|
-
async function resolveChallenge(page, targetUrl, options = {}) {
|
|
4424
|
-
const timeoutMs = options.timeoutMs ?? 2e4;
|
|
4425
|
-
const pollIntervalMs = options.pollIntervalMs ?? 2e3;
|
|
4426
|
-
const enableClick = options.enableClick !== false;
|
|
4427
|
-
const warmUp = options.warmUp !== false;
|
|
4428
|
-
const rng = options.rng ?? Math.random;
|
|
4429
|
-
let inspection = await inspectPage(page);
|
|
4430
|
-
if (!inspection.isChallenge) {
|
|
4431
|
-
return { status: "not_detected", attempts: 0 };
|
|
4432
|
-
}
|
|
4433
|
-
console.warn(
|
|
4434
|
-
`[VSL MCP Server] Anti-bot challenge detected (${inspection.kind ?? "generic"}) at ${targetUrl} \u2014 resolving (timeout ${timeoutMs}ms)`
|
|
4435
|
-
);
|
|
4436
|
-
const deadline = Date.now() + timeoutMs;
|
|
4437
|
-
let attempts = 0;
|
|
4438
|
-
let warmedUp = false;
|
|
4439
|
-
let clicked = false;
|
|
4440
|
-
while (Date.now() < deadline) {
|
|
4441
|
-
attempts++;
|
|
4442
|
-
if (warmUp && !warmedUp) {
|
|
4443
|
-
warmedUp = true;
|
|
4444
|
-
const origin = safeOrigin(targetUrl);
|
|
4445
|
-
if (origin && origin !== targetUrl) {
|
|
4446
|
-
try {
|
|
4447
|
-
await page.goto(origin, { timeout: timeoutMs, waitUntil: "domcontentloaded" });
|
|
4448
|
-
await page.waitForTimeout(Math.round(pollIntervalMs / 2));
|
|
4449
|
-
await page.goto(targetUrl, { timeout: timeoutMs, waitUntil: "domcontentloaded" });
|
|
4450
|
-
} catch {
|
|
4451
|
-
}
|
|
4452
|
-
}
|
|
4453
|
-
}
|
|
4454
|
-
inspection = await inspectPage(page);
|
|
4455
|
-
if (!inspection.isChallenge) {
|
|
4456
|
-
return { status: clicked ? "clicked" : "auto", attempts };
|
|
4457
|
-
}
|
|
4458
|
-
if (enableClick && !clicked && inspection.turnstileRect) {
|
|
4459
|
-
await humanLikeClick(page, inspection, rng);
|
|
4460
|
-
clicked = true;
|
|
4136
|
+
if (enableClick && !clicked && inspection.turnstileRect) {
|
|
4137
|
+
await humanLikeClick(page, inspection, rng);
|
|
4138
|
+
clicked = true;
|
|
4461
4139
|
}
|
|
4462
4140
|
await page.waitForTimeout(pollIntervalMs);
|
|
4463
4141
|
}
|
|
@@ -4471,6 +4149,17 @@ async function resolveChallenge(page, targetUrl, options = {}) {
|
|
|
4471
4149
|
|
|
4472
4150
|
// src/browser/manager.ts
|
|
4473
4151
|
init_browserBinary();
|
|
4152
|
+
function isHeadlessUserAgent(ua) {
|
|
4153
|
+
return ua.includes("HeadlessChrome");
|
|
4154
|
+
}
|
|
4155
|
+
var HeadlessCdpBrowserError = class extends Error {
|
|
4156
|
+
constructor(cdpPort) {
|
|
4157
|
+
super(
|
|
4158
|
+
`VSL is connected via CDP to a HEADLESS browser on port ${cdpPort ?? 9222}, so a visible window cannot be opened. Retry vsl_manual_login with {action:"open", url:"...", takeover:true} to close that headless browser and reopen it visible (all agent tabs will be closed; cookies and localStorage stay in the profile).`
|
|
4159
|
+
);
|
|
4160
|
+
this.name = "HeadlessCdpBrowserError";
|
|
4161
|
+
}
|
|
4162
|
+
};
|
|
4474
4163
|
var BrowserManager = class {
|
|
4475
4164
|
browser = null;
|
|
4476
4165
|
context = null;
|
|
@@ -4479,6 +4168,8 @@ var BrowserManager = class {
|
|
|
4479
4168
|
config;
|
|
4480
4169
|
/** Флаг: браузер подключён через CDP (не закрывать при close()). */
|
|
4481
4170
|
connectedViaCDP = false;
|
|
4171
|
+
/** Фактический режим окна: true — headless, false — headed, null — неизвестен (CDP). */
|
|
4172
|
+
currentHeadless = null;
|
|
4482
4173
|
/** Активные загрузки: downloadId -> PlaywrightDownload. */
|
|
4483
4174
|
activeDownloads = /* @__PURE__ */ new Map();
|
|
4484
4175
|
constructor(config) {
|
|
@@ -4521,44 +4212,35 @@ var BrowserManager = class {
|
|
|
4521
4212
|
/**
|
|
4522
4213
|
* Запускает браузер (lazy, при первом вызове).
|
|
4523
4214
|
* Логика для множественных агентов:
|
|
4524
|
-
* 1. Если cdpPort задан
|
|
4215
|
+
* 1. Если cdpPort задан и skipCdpConnect !== true → пробуем connectOverCDP
|
|
4525
4216
|
* 2. Если connectOverCDP упал (браузер не запущен) → запускаем launchPersistentContext с --remote-debugging-port
|
|
4526
4217
|
* 3. Если cdpPort НЕ задан → просто launchPersistentContext без CDP
|
|
4218
|
+
* @param options - headless переопределяет режим окна; skipCdpConnect пропускает CDP-connect (headed-перезапуск)
|
|
4527
4219
|
* @throws Error если Playwright не установлен
|
|
4528
4220
|
*/
|
|
4529
|
-
async launch() {
|
|
4530
|
-
if (this.browser || this.context)
|
|
4221
|
+
async launch(options) {
|
|
4222
|
+
if (this.browser || this.context) {
|
|
4223
|
+
const cdpDead = this.connectedViaCDP && this.browser !== null && typeof this.browser.isConnected === "function" && !this.browser.isConnected();
|
|
4224
|
+
if (!cdpDead) return;
|
|
4225
|
+
this.browser = null;
|
|
4226
|
+
this.context = null;
|
|
4227
|
+
this.pages.clear();
|
|
4228
|
+
this.connectedViaCDP = false;
|
|
4229
|
+
this.currentHeadless = null;
|
|
4230
|
+
}
|
|
4531
4231
|
const pw = await this.loadPlaywright();
|
|
4532
4232
|
if (!pw) {
|
|
4533
4233
|
throw new Error(
|
|
4534
4234
|
"Playwright is not installed. Install it with: npm install playwright"
|
|
4535
4235
|
);
|
|
4536
4236
|
}
|
|
4537
|
-
if (this.
|
|
4538
|
-
|
|
4539
|
-
this.browser = await pw.chromium.connectOverCDP({
|
|
4540
|
-
endpointURL: `http://localhost:${this.config.cdpPort}`
|
|
4541
|
-
});
|
|
4542
|
-
this.connectedViaCDP = true;
|
|
4543
|
-
const contexts = this.browser.contexts();
|
|
4544
|
-
if (contexts.length > 0 && contexts[0]) {
|
|
4545
|
-
this.context = contexts[0];
|
|
4546
|
-
} else {
|
|
4547
|
-
const contextOptions = {
|
|
4548
|
-
acceptDownloads: this.config.acceptDownloads ?? true
|
|
4549
|
-
};
|
|
4550
|
-
if (this.config.downloadsPath) {
|
|
4551
|
-
contextOptions.downloadsPath = this.config.downloadsPath;
|
|
4552
|
-
}
|
|
4553
|
-
this.context = await this.browser.newContext(contextOptions);
|
|
4554
|
-
}
|
|
4555
|
-
return;
|
|
4556
|
-
} catch {
|
|
4557
|
-
}
|
|
4237
|
+
if (options?.skipCdpConnect !== true && await this.tryConnectCdp()) {
|
|
4238
|
+
return;
|
|
4558
4239
|
}
|
|
4559
|
-
const userDataDir = this.
|
|
4240
|
+
const userDataDir = this.getProfileDir();
|
|
4241
|
+
const effectiveHeadless = options?.headless ?? this.config.headless;
|
|
4560
4242
|
const persistentOptions = {
|
|
4561
|
-
headless:
|
|
4243
|
+
headless: effectiveHeadless,
|
|
4562
4244
|
acceptDownloads: this.config.acceptDownloads ?? true
|
|
4563
4245
|
};
|
|
4564
4246
|
if (this.config.downloadsPath) {
|
|
@@ -4576,12 +4258,87 @@ var BrowserManager = class {
|
|
|
4576
4258
|
launchArgs.push(`--remote-debugging-port=${this.config.cdpPort}`);
|
|
4577
4259
|
}
|
|
4578
4260
|
persistentOptions.args = launchArgs;
|
|
4579
|
-
|
|
4580
|
-
|
|
4581
|
-
|
|
4582
|
-
|
|
4583
|
-
|
|
4261
|
+
const maxProfileAttempts = 3;
|
|
4262
|
+
for (let attempt = 1; ; attempt++) {
|
|
4263
|
+
try {
|
|
4264
|
+
this.context = await this.launchPersistentContextWithRecovery(
|
|
4265
|
+
pw,
|
|
4266
|
+
userDataDir,
|
|
4267
|
+
persistentOptions
|
|
4268
|
+
);
|
|
4269
|
+
break;
|
|
4270
|
+
} catch (error) {
|
|
4271
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
4272
|
+
if (!/processsingleton/i.test(message)) throw error;
|
|
4273
|
+
if (attempt >= maxProfileAttempts) {
|
|
4274
|
+
throw new Error(
|
|
4275
|
+
`Browser profile ${userDataDir} is locked by another browser process. Close it (or stop the other VSL MCP server) and retry vsl_manual_login.`
|
|
4276
|
+
);
|
|
4277
|
+
}
|
|
4278
|
+
await new Promise((resolve) => setTimeout(resolve, 1e3));
|
|
4279
|
+
}
|
|
4280
|
+
}
|
|
4281
|
+
this.currentHeadless = effectiveHeadless;
|
|
4584
4282
|
this.browser = null;
|
|
4283
|
+
if (this.context) {
|
|
4284
|
+
this.watchContextClose(this.context);
|
|
4285
|
+
}
|
|
4286
|
+
}
|
|
4287
|
+
/**
|
|
4288
|
+
* Пробует подключиться к уже запущенному браузеру по CDP (CDP-first).
|
|
4289
|
+
* Возвращает true, если подключение удалось и контекст получен.
|
|
4290
|
+
* Вынесено из launch(), чтобы ensureHeaded() мог сначала проверить внешний браузер
|
|
4291
|
+
* (например РЕАЛЬНЫЙ Chrome пользователя) и не поднимать второй браузер на том же профиле.
|
|
4292
|
+
*/
|
|
4293
|
+
async tryConnectCdp() {
|
|
4294
|
+
if (!this.config.cdpPort) return false;
|
|
4295
|
+
const pw = await this.loadPlaywright();
|
|
4296
|
+
if (!pw) return false;
|
|
4297
|
+
try {
|
|
4298
|
+
this.browser = await pw.chromium.connectOverCDP({
|
|
4299
|
+
endpointURL: `http://localhost:${this.config.cdpPort}`
|
|
4300
|
+
});
|
|
4301
|
+
this.connectedViaCDP = true;
|
|
4302
|
+
this.currentHeadless = null;
|
|
4303
|
+
const contexts = this.browser.contexts();
|
|
4304
|
+
if (contexts.length > 0 && contexts[0]) {
|
|
4305
|
+
this.context = contexts[0];
|
|
4306
|
+
} else {
|
|
4307
|
+
const contextOptions = {
|
|
4308
|
+
acceptDownloads: this.config.acceptDownloads ?? true
|
|
4309
|
+
};
|
|
4310
|
+
if (this.config.downloadsPath) {
|
|
4311
|
+
contextOptions.downloadsPath = this.config.downloadsPath;
|
|
4312
|
+
}
|
|
4313
|
+
this.context = await this.browser.newContext(contextOptions);
|
|
4314
|
+
}
|
|
4315
|
+
if (this.context) {
|
|
4316
|
+
this.watchContextClose(this.context);
|
|
4317
|
+
}
|
|
4318
|
+
return true;
|
|
4319
|
+
} catch {
|
|
4320
|
+
this.browser = null;
|
|
4321
|
+
this.context = null;
|
|
4322
|
+
this.connectedViaCDP = false;
|
|
4323
|
+
this.currentHeadless = null;
|
|
4324
|
+
return false;
|
|
4325
|
+
}
|
|
4326
|
+
}
|
|
4327
|
+
/**
|
|
4328
|
+
* Сбрасывает состояние менеджера при закрытии контекста/браузера ИЗВНЕ.
|
|
4329
|
+
* Без этого мёртвый persistent-контекст считается живым (ранний выход launch()),
|
|
4330
|
+
* и процесс не переподключается к новому браузеру без перезапуска MCP-сервера.
|
|
4331
|
+
* @param context - контекст, за которым следим
|
|
4332
|
+
*/
|
|
4333
|
+
watchContextClose(context) {
|
|
4334
|
+
context.on("close", () => {
|
|
4335
|
+
if (this.context !== context) return;
|
|
4336
|
+
this.context = null;
|
|
4337
|
+
this.browser = null;
|
|
4338
|
+
this.pages.clear();
|
|
4339
|
+
this.connectedViaCDP = false;
|
|
4340
|
+
this.currentHeadless = null;
|
|
4341
|
+
});
|
|
4585
4342
|
}
|
|
4586
4343
|
/**
|
|
4587
4344
|
* Запускает persistent context с восстановлением отсутствующего бинарника браузера.
|
|
@@ -4615,71 +4372,240 @@ var BrowserManager = class {
|
|
|
4615
4372
|
}
|
|
4616
4373
|
}
|
|
4617
4374
|
/**
|
|
4618
|
-
* Гарантирует наличие бинарника браузера: скачивает его (self-heal) либо бросает
|
|
4619
|
-
* actionable ошибку, если автоустановка отключена конфигурацией или не удалась.
|
|
4375
|
+
* Гарантирует наличие бинарника браузера: скачивает его (self-heal) либо бросает
|
|
4376
|
+
* actionable ошибку, если автоустановка отключена конфигурацией или не удалась.
|
|
4377
|
+
*/
|
|
4378
|
+
async ensureBrowserBinary(missing) {
|
|
4379
|
+
const cliPath = resolvePlaywrightCliPath();
|
|
4380
|
+
if (this.config.autoInstallBrowser === false) {
|
|
4381
|
+
throw new Error(
|
|
4382
|
+
formatMissingBrowserError(missing, { cliPath, autoInstallDisabled: true })
|
|
4383
|
+
);
|
|
4384
|
+
}
|
|
4385
|
+
console.error(
|
|
4386
|
+
`[VSL MCP Server] Playwright browser binary is missing (${missing.revisionDir}) \u2014 downloading "${missing.browser}" automatically...`
|
|
4387
|
+
);
|
|
4388
|
+
const result = await this.installBrowserBinary(missing);
|
|
4389
|
+
if (!result.success) {
|
|
4390
|
+
throw new Error(
|
|
4391
|
+
formatMissingBrowserError(missing, {
|
|
4392
|
+
cliPath,
|
|
4393
|
+
reason: result.error ?? "unknown install error"
|
|
4394
|
+
})
|
|
4395
|
+
);
|
|
4396
|
+
}
|
|
4397
|
+
console.error(`[VSL MCP Server] Browser "${missing.browser}" is ready (self-heal completed).`);
|
|
4398
|
+
}
|
|
4399
|
+
/**
|
|
4400
|
+
* Шов для автоматической загрузки браузера (self-heal).
|
|
4401
|
+
* Юнит-тесты переопределяют его через jest.spyOn, чтобы не скачивать браузеры реально.
|
|
4402
|
+
*/
|
|
4403
|
+
async installBrowserBinary(info) {
|
|
4404
|
+
const cliPath = resolvePlaywrightCliPath();
|
|
4405
|
+
if (!cliPath) {
|
|
4406
|
+
return {
|
|
4407
|
+
success: false,
|
|
4408
|
+
output: "",
|
|
4409
|
+
error: "playwright cli.js not found next to the installed playwright package"
|
|
4410
|
+
};
|
|
4411
|
+
}
|
|
4412
|
+
return installBrowser({
|
|
4413
|
+
browser: info.browser,
|
|
4414
|
+
cliPath,
|
|
4415
|
+
timeoutMs: this.config.browserInstallTimeout ?? DEFAULT_BROWSER_INSTALL_TIMEOUT_MS
|
|
4416
|
+
});
|
|
4417
|
+
}
|
|
4418
|
+
/**
|
|
4419
|
+
* Возвращает страницу для указанной сессии (создаёт новую из context, если нет).
|
|
4420
|
+
* @param sessionId - ID сессии для изоляции страниц
|
|
4421
|
+
* @throws Error если браузер не запущен
|
|
4422
|
+
*/
|
|
4423
|
+
async getPage(sessionId) {
|
|
4424
|
+
if (!this.browser && !this.context) {
|
|
4425
|
+
await this.launch();
|
|
4426
|
+
}
|
|
4427
|
+
if (!this.context) {
|
|
4428
|
+
throw new Error("Browser not available");
|
|
4429
|
+
}
|
|
4430
|
+
let page = this.pages.get(sessionId);
|
|
4431
|
+
if (!page) {
|
|
4432
|
+
page = await this.context.newPage();
|
|
4433
|
+
this.pages.set(sessionId, page);
|
|
4434
|
+
this.context.on("download", (download) => {
|
|
4435
|
+
const downloadId = `download_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
4436
|
+
this.activeDownloads.set(downloadId, download);
|
|
4437
|
+
});
|
|
4438
|
+
}
|
|
4439
|
+
return page;
|
|
4440
|
+
}
|
|
4441
|
+
/**
|
|
4442
|
+
* Возвращает путь persistent-профиля браузера (R5).
|
|
4443
|
+
* Единая точка вычисления пути: второй профиль нигде не создаётся.
|
|
4444
|
+
*/
|
|
4445
|
+
getProfileDir() {
|
|
4446
|
+
return this.config.userDataDir ?? path2.join(os.homedir(), ".vsl", "browser-profile");
|
|
4447
|
+
}
|
|
4448
|
+
/**
|
|
4449
|
+
* Возвращает фактический режим окна браузера (R6).
|
|
4450
|
+
* not_launched — контекста нет; cdp — внешний браузер; headed/headless — свой контекст.
|
|
4451
|
+
*/
|
|
4452
|
+
getBrowserMode() {
|
|
4453
|
+
if (!this.context) return "not_launched";
|
|
4454
|
+
if (this.connectedViaCDP) return "cdp";
|
|
4455
|
+
if (this.currentHeadless === false) return "headed";
|
|
4456
|
+
return "headless";
|
|
4457
|
+
}
|
|
4458
|
+
/**
|
|
4459
|
+
* Возвращает User-Agent браузера (R27).
|
|
4460
|
+
* @param sessionId - ID сессии
|
|
4461
|
+
*/
|
|
4462
|
+
async getBrowserUserAgent(sessionId) {
|
|
4463
|
+
const page = await this.getPage(sessionId);
|
|
4464
|
+
return await page.evaluate(() => navigator.userAgent);
|
|
4465
|
+
}
|
|
4466
|
+
/**
|
|
4467
|
+
* Возвращает АВТОРИТЕТНЫЙ product браузера через CDP Browser.getVersion.
|
|
4468
|
+
* UA страницы (getBrowserUserAgent) подменяется stealth-плагином
|
|
4469
|
+
* (puppeteer-extra-plugin-stealth, evasion user-agent-override) в новых CDP-контекстах
|
|
4470
|
+
* и теряет подстроку 'HeadlessChrome' — для детекции режима окна он не годится.
|
|
4471
|
+
* @param sessionId - ID сессии
|
|
4472
|
+
*/
|
|
4473
|
+
async getBrowserProduct(sessionId) {
|
|
4474
|
+
const page = await this.getPage(sessionId);
|
|
4475
|
+
if (!this.context) {
|
|
4476
|
+
throw new Error("Browser not available");
|
|
4477
|
+
}
|
|
4478
|
+
const cdp = await this.context.newCDPSession(page);
|
|
4479
|
+
try {
|
|
4480
|
+
const info = await cdp.send("Browser.getVersion");
|
|
4481
|
+
return typeof info?.product === "string" ? info.product : "";
|
|
4482
|
+
} finally {
|
|
4483
|
+
try {
|
|
4484
|
+
await cdp.detach();
|
|
4485
|
+
} catch (error) {
|
|
4486
|
+
console.error(
|
|
4487
|
+
"[BrowserManager] CDP session detach failed:",
|
|
4488
|
+
error instanceof Error ? error.message : String(error)
|
|
4489
|
+
);
|
|
4490
|
+
}
|
|
4491
|
+
}
|
|
4492
|
+
}
|
|
4493
|
+
/**
|
|
4494
|
+
* Определяет, headless ли браузер, по авторитетному CDP product (Browser.getVersion).
|
|
4495
|
+
* Фолбэк на UA страницы — только если CDP-команда недоступна.
|
|
4496
|
+
* @param sessionId - ID сессии
|
|
4497
|
+
*/
|
|
4498
|
+
async isHeadlessBrowser(sessionId) {
|
|
4499
|
+
try {
|
|
4500
|
+
const product = await this.getBrowserProduct(sessionId);
|
|
4501
|
+
if (product) return isHeadlessUserAgent(product);
|
|
4502
|
+
} catch (error) {
|
|
4503
|
+
console.error(
|
|
4504
|
+
"[BrowserManager] CDP Browser.getVersion unavailable, falling back to page User-Agent:",
|
|
4505
|
+
error instanceof Error ? error.message : String(error)
|
|
4506
|
+
);
|
|
4507
|
+
}
|
|
4508
|
+
return isHeadlessUserAgent(await this.getBrowserUserAgent(sessionId));
|
|
4509
|
+
}
|
|
4510
|
+
/**
|
|
4511
|
+
* Приводит браузер к ВИДИМОМУ окну на том же профиле (R7).
|
|
4512
|
+
* CDP-first: если на cdpPort уже жив браузер (в том числе РЕАЛЬНЫЙ Chrome пользователя),
|
|
4513
|
+
* подключаемся к нему и НЕ поднимаем второй браузер на том же профиле.
|
|
4514
|
+
* Режим окна внешнего браузера определяется АВТОРИТЕТНО через CDP Browser.getVersion,
|
|
4515
|
+
* а не по UA страницы (его подменяет stealth-плагин).
|
|
4516
|
+
* Свой headless-контекст перезапускается, внешний видимый Chrome не трогается,
|
|
4517
|
+
* headless-браузер VSL по CDP закрывается только при явном takeover:true.
|
|
4518
|
+
* @param sessionId - ID сессии
|
|
4519
|
+
* @param options - takeover: закрыть чужой headless-браузер VSL и переоткрыть видимым
|
|
4520
|
+
*/
|
|
4521
|
+
async ensureHeaded(sessionId, options) {
|
|
4522
|
+
if (!this.context) {
|
|
4523
|
+
const connected = await this.tryConnectCdp();
|
|
4524
|
+
if (!connected) {
|
|
4525
|
+
await this.launch({ headless: false, skipCdpConnect: true });
|
|
4526
|
+
return { restarted: true, mode: "headed" };
|
|
4527
|
+
}
|
|
4528
|
+
}
|
|
4529
|
+
if (this.connectedViaCDP) {
|
|
4530
|
+
if (!await this.isHeadlessBrowser(sessionId)) {
|
|
4531
|
+
return { restarted: false, mode: "cdp" };
|
|
4532
|
+
}
|
|
4533
|
+
if (options?.takeover !== true) {
|
|
4534
|
+
throw new HeadlessCdpBrowserError(this.config.cdpPort);
|
|
4535
|
+
}
|
|
4536
|
+
await this.closeCdpBrowser(sessionId);
|
|
4537
|
+
await this.close();
|
|
4538
|
+
await this.launch({ headless: false, skipCdpConnect: true });
|
|
4539
|
+
return { restarted: true, mode: "headed" };
|
|
4540
|
+
}
|
|
4541
|
+
if (this.currentHeadless === false) {
|
|
4542
|
+
return { restarted: false, mode: "headed" };
|
|
4543
|
+
}
|
|
4544
|
+
await this.close();
|
|
4545
|
+
await this.launch({ headless: false, skipCdpConnect: true });
|
|
4546
|
+
return { restarted: true, mode: "headed" };
|
|
4547
|
+
}
|
|
4548
|
+
/**
|
|
4549
|
+
* Закрывает headless-браузер VSL, подключённый по CDP, командой Browser.close (R29).
|
|
4550
|
+
* Обрыв соединения после закрытия — ожидаемый исход, ошибка только логируется.
|
|
4551
|
+
* @param sessionId - ID сессии
|
|
4552
|
+
*/
|
|
4553
|
+
async closeCdpBrowser(sessionId) {
|
|
4554
|
+
const page = await this.getPage(sessionId);
|
|
4555
|
+
if (!this.context) {
|
|
4556
|
+
throw new Error("Browser not available");
|
|
4557
|
+
}
|
|
4558
|
+
const cdp = await this.context.newCDPSession(page);
|
|
4559
|
+
try {
|
|
4560
|
+
await cdp.send("Browser.close");
|
|
4561
|
+
} catch (error) {
|
|
4562
|
+
console.error(
|
|
4563
|
+
"[BrowserManager] CDP Browser.close ended with a connection error (expected):",
|
|
4564
|
+
error instanceof Error ? error.message : String(error)
|
|
4565
|
+
);
|
|
4566
|
+
} finally {
|
|
4567
|
+
try {
|
|
4568
|
+
await cdp.detach();
|
|
4569
|
+
} catch (error) {
|
|
4570
|
+
console.error(
|
|
4571
|
+
"[BrowserManager] CDP session detach failed:",
|
|
4572
|
+
error instanceof Error ? error.message : String(error)
|
|
4573
|
+
);
|
|
4574
|
+
}
|
|
4575
|
+
}
|
|
4576
|
+
}
|
|
4577
|
+
/**
|
|
4578
|
+
* Возвращает браузер в headless-режим на том же профиле (R8).
|
|
4579
|
+
* При CDP и при уже headless-режиме — no-op.
|
|
4620
4580
|
*/
|
|
4621
|
-
async
|
|
4622
|
-
|
|
4623
|
-
if (this.
|
|
4624
|
-
|
|
4625
|
-
|
|
4626
|
-
|
|
4627
|
-
}
|
|
4628
|
-
console.error(
|
|
4629
|
-
`[VSL MCP Server] Playwright browser binary is missing (${missing.revisionDir}) \u2014 downloading "${missing.browser}" automatically...`
|
|
4630
|
-
);
|
|
4631
|
-
const result = await this.installBrowserBinary(missing);
|
|
4632
|
-
if (!result.success) {
|
|
4633
|
-
throw new Error(
|
|
4634
|
-
formatMissingBrowserError(missing, {
|
|
4635
|
-
cliPath,
|
|
4636
|
-
reason: result.error ?? "unknown install error"
|
|
4637
|
-
})
|
|
4638
|
-
);
|
|
4639
|
-
}
|
|
4640
|
-
console.error(`[VSL MCP Server] Browser "${missing.browser}" is ready (self-heal completed).`);
|
|
4581
|
+
async restoreHeadless() {
|
|
4582
|
+
if (this.connectedViaCDP) return { restarted: false };
|
|
4583
|
+
if (this.currentHeadless === true) return { restarted: false };
|
|
4584
|
+
await this.close();
|
|
4585
|
+
await this.launch({ headless: true, skipCdpConnect: true });
|
|
4586
|
+
return { restarted: true };
|
|
4641
4587
|
}
|
|
4642
4588
|
/**
|
|
4643
|
-
*
|
|
4644
|
-
*
|
|
4589
|
+
* Выводит окно страницы на передний план (R8).
|
|
4590
|
+
* @param sessionId - ID сессии
|
|
4645
4591
|
*/
|
|
4646
|
-
async
|
|
4647
|
-
const
|
|
4648
|
-
|
|
4649
|
-
return {
|
|
4650
|
-
success: false,
|
|
4651
|
-
output: "",
|
|
4652
|
-
error: "playwright cli.js not found next to the installed playwright package"
|
|
4653
|
-
};
|
|
4654
|
-
}
|
|
4655
|
-
return installBrowser({
|
|
4656
|
-
browser: info.browser,
|
|
4657
|
-
cliPath,
|
|
4658
|
-
timeoutMs: this.config.browserInstallTimeout ?? DEFAULT_BROWSER_INSTALL_TIMEOUT_MS
|
|
4659
|
-
});
|
|
4592
|
+
async bringToFront(sessionId) {
|
|
4593
|
+
const page = await this.getPage(sessionId);
|
|
4594
|
+
await page.bringToFront();
|
|
4660
4595
|
}
|
|
4661
4596
|
/**
|
|
4662
|
-
* Возвращает
|
|
4663
|
-
*
|
|
4664
|
-
* @throws Error если браузер не запущен
|
|
4597
|
+
* Возвращает КОЛИЧЕСТВО cookies профиля (R8).
|
|
4598
|
+
* Значения и имена cookies не читаются и не логируются.
|
|
4665
4599
|
*/
|
|
4666
|
-
async
|
|
4667
|
-
if (!this.
|
|
4600
|
+
async getCookieCount() {
|
|
4601
|
+
if (!this.context) {
|
|
4668
4602
|
await this.launch();
|
|
4669
4603
|
}
|
|
4670
4604
|
if (!this.context) {
|
|
4671
4605
|
throw new Error("Browser not available");
|
|
4672
4606
|
}
|
|
4673
|
-
|
|
4674
|
-
|
|
4675
|
-
page = await this.context.newPage();
|
|
4676
|
-
this.pages.set(sessionId, page);
|
|
4677
|
-
this.context.on("download", (download) => {
|
|
4678
|
-
const downloadId = `download_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
4679
|
-
this.activeDownloads.set(downloadId, download);
|
|
4680
|
-
});
|
|
4681
|
-
}
|
|
4682
|
-
return page;
|
|
4607
|
+
const cookies = await this.context.cookies();
|
|
4608
|
+
return cookies.length;
|
|
4683
4609
|
}
|
|
4684
4610
|
/**
|
|
4685
4611
|
* Переходит по URL.
|
|
@@ -4792,153 +4718,749 @@ var BrowserManager = class {
|
|
|
4792
4718
|
path: null
|
|
4793
4719
|
};
|
|
4794
4720
|
}
|
|
4795
|
-
const path3 = await download.path();
|
|
4796
|
-
return {
|
|
4797
|
-
downloadId,
|
|
4798
|
-
filename: download.suggestedFilename(),
|
|
4799
|
-
url: download.url(),
|
|
4800
|
-
status: "completed",
|
|
4801
|
-
path: path3
|
|
4721
|
+
const path3 = await download.path();
|
|
4722
|
+
return {
|
|
4723
|
+
downloadId,
|
|
4724
|
+
filename: download.suggestedFilename(),
|
|
4725
|
+
url: download.url(),
|
|
4726
|
+
status: "completed",
|
|
4727
|
+
path: path3
|
|
4728
|
+
};
|
|
4729
|
+
} catch {
|
|
4730
|
+
return {
|
|
4731
|
+
downloadId,
|
|
4732
|
+
filename: download.suggestedFilename(),
|
|
4733
|
+
url: download.url(),
|
|
4734
|
+
status: "failed",
|
|
4735
|
+
path: null
|
|
4736
|
+
};
|
|
4737
|
+
}
|
|
4738
|
+
}
|
|
4739
|
+
/**
|
|
4740
|
+
* Возвращает список активных загрузок.
|
|
4741
|
+
*/
|
|
4742
|
+
getDownloads() {
|
|
4743
|
+
return Array.from(this.activeDownloads.entries()).map(([downloadId, download]) => ({
|
|
4744
|
+
downloadId,
|
|
4745
|
+
filename: download.suggestedFilename(),
|
|
4746
|
+
url: download.url()
|
|
4747
|
+
}));
|
|
4748
|
+
}
|
|
4749
|
+
/**
|
|
4750
|
+
* Сохраняет загрузку в указанный путь.
|
|
4751
|
+
* @param downloadId - ID загрузки
|
|
4752
|
+
* @param savePath - Путь для сохранения
|
|
4753
|
+
*/
|
|
4754
|
+
async saveDownload(downloadId, savePath) {
|
|
4755
|
+
const download = this.activeDownloads.get(downloadId);
|
|
4756
|
+
if (!download) {
|
|
4757
|
+
throw new Error(`Download not found: ${downloadId}`);
|
|
4758
|
+
}
|
|
4759
|
+
const isAbsolute = savePath.startsWith("/");
|
|
4760
|
+
if (isAbsolute) {
|
|
4761
|
+
await download.saveAs(savePath);
|
|
4762
|
+
} else {
|
|
4763
|
+
const downloadsPath = this.config.downloadsPath ?? os.tmpdir();
|
|
4764
|
+
const resolvedBase = path2.resolve(downloadsPath.replace(/^~/, os.homedir()));
|
|
4765
|
+
const resolvedSave = path2.resolve(resolvedBase, savePath);
|
|
4766
|
+
if (!resolvedSave.startsWith(resolvedBase + path2.sep) && resolvedSave !== resolvedBase) {
|
|
4767
|
+
throw new Error(`Path traversal detected: save_path '${savePath}' escapes downloads directory '${resolvedBase}'`);
|
|
4768
|
+
}
|
|
4769
|
+
await download.saveAs(resolvedSave);
|
|
4770
|
+
}
|
|
4771
|
+
}
|
|
4772
|
+
/**
|
|
4773
|
+
* Отменяет загрузку.
|
|
4774
|
+
* @param downloadId - ID загрузки
|
|
4775
|
+
*/
|
|
4776
|
+
async cancelDownload(downloadId) {
|
|
4777
|
+
const download = this.activeDownloads.get(downloadId);
|
|
4778
|
+
if (!download) {
|
|
4779
|
+
throw new Error(`Download not found: ${downloadId}`);
|
|
4780
|
+
}
|
|
4781
|
+
await download.cancel();
|
|
4782
|
+
this.activeDownloads.delete(downloadId);
|
|
4783
|
+
}
|
|
4784
|
+
/**
|
|
4785
|
+
* Очищает завершённые загрузки из activeDownloads.
|
|
4786
|
+
*/
|
|
4787
|
+
clearDownloads() {
|
|
4788
|
+
this.activeDownloads.clear();
|
|
4789
|
+
}
|
|
4790
|
+
/**
|
|
4791
|
+
* Загружает файлы в <input type="file"> по CSS-селектору.
|
|
4792
|
+
* Использует Playwright page.setInputFiles().
|
|
4793
|
+
* Валидирует пути: абсолютные используются напрямую, относительные разрешаются
|
|
4794
|
+
* относительно CWD с path traversal проверкой.
|
|
4795
|
+
* @param selector - CSS-селектор input[type=file] элемента
|
|
4796
|
+
* @param filePaths - Массив путей к файлам (абсолютные или относительные)
|
|
4797
|
+
* @param sessionId - ID сессии
|
|
4798
|
+
* @throws Error если путь выходит за допустимые границы или файл не существует
|
|
4799
|
+
*/
|
|
4800
|
+
async uploadFile(selector, filePaths, sessionId) {
|
|
4801
|
+
const page = await this.getPage(sessionId);
|
|
4802
|
+
if (filePaths.length === 0) {
|
|
4803
|
+
throw new Error("filePaths must contain at least one file path");
|
|
4804
|
+
}
|
|
4805
|
+
const resolvedPaths = [];
|
|
4806
|
+
for (const filePath of filePaths) {
|
|
4807
|
+
const isAbsolute = path2.isAbsolute(filePath);
|
|
4808
|
+
if (isAbsolute) {
|
|
4809
|
+
resolvedPaths.push(filePath);
|
|
4810
|
+
} else {
|
|
4811
|
+
const resolved = path2.resolve(process.cwd(), filePath);
|
|
4812
|
+
const cwd = path2.resolve(process.cwd());
|
|
4813
|
+
if (!resolved.startsWith(cwd + path2.sep) && resolved !== cwd) {
|
|
4814
|
+
throw new Error(`Path traversal detected: file path '${filePath}' resolves outside working directory '${cwd}'`);
|
|
4815
|
+
}
|
|
4816
|
+
resolvedPaths.push(resolved);
|
|
4817
|
+
}
|
|
4818
|
+
}
|
|
4819
|
+
await page.setInputFiles(selector, resolvedPaths.length === 1 ? resolvedPaths[0] : resolvedPaths);
|
|
4820
|
+
}
|
|
4821
|
+
/**
|
|
4822
|
+
* Ожидает появления file chooser dialog (для кастомных file picker'ов).
|
|
4823
|
+
* Возвращает FileChooser, через который можно установить файлы.
|
|
4824
|
+
* @param sessionId - ID сессии
|
|
4825
|
+
* @param timeout - Таймаут ожидания в мс (по умолчанию из config.downloadTimeout)
|
|
4826
|
+
* @returns PlaywrightFileChooser для установки файлов
|
|
4827
|
+
*/
|
|
4828
|
+
async waitForFileChooser(sessionId, timeout) {
|
|
4829
|
+
const page = await this.getPage(sessionId);
|
|
4830
|
+
const waitTimeout = timeout ?? this.config.downloadTimeout ?? 6e4;
|
|
4831
|
+
const fileChooser = await page.waitForEvent("filechooser", { timeout: waitTimeout });
|
|
4832
|
+
return fileChooser;
|
|
4833
|
+
}
|
|
4834
|
+
/**
|
|
4835
|
+
* Закрывает браузер и очищает ресурсы.
|
|
4836
|
+
* Если браузер подключён через CDP — закрывает только context,
|
|
4837
|
+
* сам браузер не закрывается (сохраняет сессию пользователя).
|
|
4838
|
+
*/
|
|
4839
|
+
async close() {
|
|
4840
|
+
this.activeDownloads.clear();
|
|
4841
|
+
for (const page of this.pages.values()) {
|
|
4842
|
+
try {
|
|
4843
|
+
await page.close();
|
|
4844
|
+
} catch (error) {
|
|
4845
|
+
console.error("[BrowserManager] Error closing page:", error);
|
|
4846
|
+
}
|
|
4847
|
+
}
|
|
4848
|
+
this.pages.clear();
|
|
4849
|
+
try {
|
|
4850
|
+
if (this.context) {
|
|
4851
|
+
await this.context.close();
|
|
4852
|
+
this.context = null;
|
|
4853
|
+
}
|
|
4854
|
+
if (this.browser && !this.connectedViaCDP) {
|
|
4855
|
+
await this.browser.close();
|
|
4856
|
+
this.browser = null;
|
|
4857
|
+
} else if (this.connectedViaCDP) {
|
|
4858
|
+
this.browser = null;
|
|
4859
|
+
}
|
|
4860
|
+
} catch (error) {
|
|
4861
|
+
console.error("[BrowserManager] Error during close():", error);
|
|
4862
|
+
this.context = null;
|
|
4863
|
+
this.browser = null;
|
|
4864
|
+
}
|
|
4865
|
+
this.connectedViaCDP = false;
|
|
4866
|
+
}
|
|
4867
|
+
};
|
|
4868
|
+
|
|
4869
|
+
// src/tools/manualLogin.ts
|
|
4870
|
+
var DEFAULT_TIMEOUT_MS = 18e4;
|
|
4871
|
+
var DEFAULT_POLL_INTERVAL_MS = 2e3;
|
|
4872
|
+
var MIN_TIMEOUT_MS = 1e3;
|
|
4873
|
+
var MAX_TIMEOUT_MS = 6e5;
|
|
4874
|
+
var loginState = /* @__PURE__ */ new Map();
|
|
4875
|
+
function sanitizeUrl(url) {
|
|
4876
|
+
try {
|
|
4877
|
+
const parsed = new URL(url);
|
|
4878
|
+
return parsed.origin + parsed.pathname;
|
|
4879
|
+
} catch {
|
|
4880
|
+
return "";
|
|
4881
|
+
}
|
|
4882
|
+
}
|
|
4883
|
+
function resolveTimeoutMs(value) {
|
|
4884
|
+
if (value === void 0 || !Number.isFinite(value)) return DEFAULT_TIMEOUT_MS;
|
|
4885
|
+
return Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, Math.trunc(value)));
|
|
4886
|
+
}
|
|
4887
|
+
function sleep(ms) {
|
|
4888
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
4889
|
+
}
|
|
4890
|
+
async function computeMatched(browser, sessionId, successSelector, successUrlPattern) {
|
|
4891
|
+
if (!successSelector && !successUrlPattern) return false;
|
|
4892
|
+
if (successSelector) {
|
|
4893
|
+
const found = await browser.evaluate(
|
|
4894
|
+
(sel) => document.querySelector(sel) !== null,
|
|
4895
|
+
sessionId,
|
|
4896
|
+
successSelector
|
|
4897
|
+
);
|
|
4898
|
+
if (found === true) return true;
|
|
4899
|
+
}
|
|
4900
|
+
if (successUrlPattern) {
|
|
4901
|
+
const href = await browser.evaluate(() => window.location.href, sessionId);
|
|
4902
|
+
if (typeof href === "string" && href.includes(successUrlPattern)) return true;
|
|
4903
|
+
}
|
|
4904
|
+
return false;
|
|
4905
|
+
}
|
|
4906
|
+
async function waitForLogin(browser, sessionId, args, deadlineAt, pollIntervalMs) {
|
|
4907
|
+
for (; ; ) {
|
|
4908
|
+
const matched = await computeMatched(browser, sessionId, args.success_selector, args.success_url_pattern);
|
|
4909
|
+
if (matched) return true;
|
|
4910
|
+
const remaining = deadlineAt - Date.now();
|
|
4911
|
+
if (remaining <= 0) return false;
|
|
4912
|
+
await sleep(Math.min(pollIntervalMs, remaining));
|
|
4913
|
+
}
|
|
4914
|
+
}
|
|
4915
|
+
async function handleManualLogin(args, browser, _session, sessionManager, config, sessionId) {
|
|
4916
|
+
const startTime = Date.now();
|
|
4917
|
+
const action = args.action ?? "open";
|
|
4918
|
+
try {
|
|
4919
|
+
if (action === "open") {
|
|
4920
|
+
if (!args.url || typeof args.url !== "string") {
|
|
4921
|
+
return { status: "error", error: "URL is required" };
|
|
4922
|
+
}
|
|
4923
|
+
let parsed;
|
|
4924
|
+
try {
|
|
4925
|
+
parsed = new URL(args.url);
|
|
4926
|
+
} catch {
|
|
4927
|
+
return { status: "error", error: `Invalid URL: ${args.url}` };
|
|
4928
|
+
}
|
|
4929
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
4930
|
+
return { status: "error", error: "Only http and https URLs are supported" };
|
|
4931
|
+
}
|
|
4932
|
+
const isAvailable = await browser.isAvailable();
|
|
4933
|
+
if (!isAvailable) {
|
|
4934
|
+
return {
|
|
4935
|
+
status: "error",
|
|
4936
|
+
error: "Playwright is not installed. Install it with: npm install playwright"
|
|
4937
|
+
};
|
|
4938
|
+
}
|
|
4939
|
+
const { restarted, mode } = await browser.ensureHeaded(sessionId, { takeover: args.takeover === true });
|
|
4940
|
+
let challengeWarning;
|
|
4941
|
+
try {
|
|
4942
|
+
await browser.navigate(args.url, sessionId);
|
|
4943
|
+
} catch (error) {
|
|
4944
|
+
if (!(error instanceof ChallengeResolutionError)) throw error;
|
|
4945
|
+
challengeWarning = 'Visible window is open \u2014 log in manually (captcha/2FA), then call vsl_manual_login with {action:"status"} and {action:"finish"}.';
|
|
4946
|
+
console.error("[vsl_manual_login] anti-bot challenge on", sanitizeUrl(args.url));
|
|
4947
|
+
}
|
|
4948
|
+
await browser.bringToFront(sessionId);
|
|
4949
|
+
sessionManager.clearAllSessionCaches();
|
|
4950
|
+
const timeoutMs = resolveTimeoutMs(args.timeout_ms ?? config.browser.manualLogin?.timeoutMs);
|
|
4951
|
+
const pollIntervalMs = config.browser.manualLogin?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
4952
|
+
const deadlineAt = Date.now() + timeoutMs;
|
|
4953
|
+
loginState.set(sessionId, { loginUrl: args.url, deadlineAt });
|
|
4954
|
+
const loginUrl = sanitizeUrl(args.url);
|
|
4955
|
+
const data = {
|
|
4956
|
+
action: "open",
|
|
4957
|
+
browser_mode: mode,
|
|
4958
|
+
profile_dir: browser.getProfileDir(),
|
|
4959
|
+
restarted,
|
|
4960
|
+
login_url: loginUrl,
|
|
4961
|
+
current_url: loginUrl,
|
|
4962
|
+
cookie_count: await browser.getCookieCount(),
|
|
4963
|
+
matched: false,
|
|
4964
|
+
waiting: true,
|
|
4965
|
+
deadline_at: new Date(deadlineAt).toISOString(),
|
|
4966
|
+
instructions: `Open ${loginUrl} in the visible browser window and sign in manually (captcha and 2FA are done by you). Then call vsl_manual_login with {action:"status"} to check the sign-in and {action:"finish"} to save the result.`
|
|
4967
|
+
};
|
|
4968
|
+
let warning = challengeWarning;
|
|
4969
|
+
if (args.wait === true) {
|
|
4970
|
+
const matched = await waitForLogin(browser, sessionId, args, deadlineAt, pollIntervalMs);
|
|
4971
|
+
data.matched = matched;
|
|
4972
|
+
data.waiting = !matched;
|
|
4973
|
+
if (!matched) {
|
|
4974
|
+
warning = `Manual login was not confirmed within ${timeoutMs}ms. The window stays open \u2014 call vsl_manual_login with {action:"status"} later.`;
|
|
4975
|
+
}
|
|
4976
|
+
}
|
|
4977
|
+
const result = {
|
|
4978
|
+
status: "success",
|
|
4979
|
+
data,
|
|
4980
|
+
metadata: computeToolMetrics(data, startTime)
|
|
4981
|
+
};
|
|
4982
|
+
if (warning) result.warning = warning;
|
|
4983
|
+
return result;
|
|
4984
|
+
}
|
|
4985
|
+
if (action === "status") {
|
|
4986
|
+
const mode = browser.getBrowserMode();
|
|
4987
|
+
if (mode === "not_launched") {
|
|
4988
|
+
return {
|
|
4989
|
+
status: "error",
|
|
4990
|
+
error: 'Browser is not launched. Call vsl_manual_login with {action:"open", url:"..."} first.'
|
|
4991
|
+
};
|
|
4992
|
+
}
|
|
4993
|
+
const href = await browser.evaluate(() => window.location.href, sessionId);
|
|
4994
|
+
const state = loginState.get(sessionId);
|
|
4995
|
+
const data = {
|
|
4996
|
+
action: "status",
|
|
4997
|
+
browser_mode: mode,
|
|
4998
|
+
profile_dir: browser.getProfileDir(),
|
|
4999
|
+
restarted: false,
|
|
5000
|
+
current_url: sanitizeUrl(typeof href === "string" ? href : ""),
|
|
5001
|
+
cookie_count: await browser.getCookieCount(),
|
|
5002
|
+
matched: await computeMatched(browser, sessionId, args.success_selector, args.success_url_pattern),
|
|
5003
|
+
waiting: state !== void 0 && state.deadlineAt > Date.now()
|
|
5004
|
+
};
|
|
5005
|
+
return { status: "success", data, metadata: computeToolMetrics(data, startTime) };
|
|
5006
|
+
}
|
|
5007
|
+
if (action === "finish") {
|
|
5008
|
+
const href = await browser.evaluate(() => window.location.href, sessionId);
|
|
5009
|
+
const currentUrl = sanitizeUrl(typeof href === "string" ? href : "");
|
|
5010
|
+
const cookieCount = await browser.getCookieCount();
|
|
5011
|
+
const matched = await computeMatched(browser, sessionId, args.success_selector, args.success_url_pattern);
|
|
5012
|
+
const restore = args.restore_headless ?? config.browser.manualLogin?.restoreHeadless ?? false;
|
|
5013
|
+
let restarted = false;
|
|
5014
|
+
let browserMode;
|
|
5015
|
+
if (restore) {
|
|
5016
|
+
const restored = await browser.restoreHeadless();
|
|
5017
|
+
restarted = restored.restarted;
|
|
5018
|
+
browserMode = "headless";
|
|
5019
|
+
} else {
|
|
5020
|
+
const mode = browser.getBrowserMode();
|
|
5021
|
+
browserMode = mode === "not_launched" ? "headless" : mode;
|
|
5022
|
+
}
|
|
5023
|
+
sessionManager.clearAllSessionCaches();
|
|
5024
|
+
loginState.delete(sessionId);
|
|
5025
|
+
const data = {
|
|
5026
|
+
action: "finish",
|
|
5027
|
+
browser_mode: browserMode,
|
|
5028
|
+
profile_dir: browser.getProfileDir(),
|
|
5029
|
+
restarted,
|
|
5030
|
+
current_url: currentUrl,
|
|
5031
|
+
cookie_count: cookieCount,
|
|
5032
|
+
matched,
|
|
5033
|
+
waiting: false,
|
|
5034
|
+
instructions: "Manual login finished. Cookies and localStorage are stored in the VSL browser profile, so all subsequent VSL tools and sessions are already signed in."
|
|
4802
5035
|
};
|
|
4803
|
-
|
|
4804
|
-
|
|
4805
|
-
|
|
4806
|
-
|
|
4807
|
-
url: download.url(),
|
|
4808
|
-
status: "failed",
|
|
4809
|
-
path: null
|
|
5036
|
+
const result = {
|
|
5037
|
+
status: "success",
|
|
5038
|
+
data,
|
|
5039
|
+
metadata: computeToolMetrics(data, startTime)
|
|
4810
5040
|
};
|
|
5041
|
+
if (restore) {
|
|
5042
|
+
result.warning = "Headless restart closes the login tab: sessionStorage and session-only cookies may be lost.";
|
|
5043
|
+
}
|
|
5044
|
+
return result;
|
|
4811
5045
|
}
|
|
4812
|
-
|
|
4813
|
-
|
|
4814
|
-
|
|
4815
|
-
|
|
4816
|
-
getDownloads() {
|
|
4817
|
-
return Array.from(this.activeDownloads.entries()).map(([downloadId, download]) => ({
|
|
4818
|
-
downloadId,
|
|
4819
|
-
filename: download.suggestedFilename(),
|
|
4820
|
-
url: download.url()
|
|
4821
|
-
}));
|
|
4822
|
-
}
|
|
4823
|
-
/**
|
|
4824
|
-
* Сохраняет загрузку в указанный путь.
|
|
4825
|
-
* @param downloadId - ID загрузки
|
|
4826
|
-
* @param savePath - Путь для сохранения
|
|
4827
|
-
*/
|
|
4828
|
-
async saveDownload(downloadId, savePath) {
|
|
4829
|
-
const download = this.activeDownloads.get(downloadId);
|
|
4830
|
-
if (!download) {
|
|
4831
|
-
throw new Error(`Download not found: ${downloadId}`);
|
|
5046
|
+
return { status: "error", error: `Unknown action: ${String(action)}` };
|
|
5047
|
+
} catch (error) {
|
|
5048
|
+
if (error instanceof HeadlessCdpBrowserError) {
|
|
5049
|
+
return { status: "error", error: error.message };
|
|
4832
5050
|
}
|
|
4833
|
-
|
|
4834
|
-
|
|
4835
|
-
|
|
4836
|
-
|
|
4837
|
-
|
|
4838
|
-
|
|
4839
|
-
|
|
4840
|
-
|
|
4841
|
-
|
|
5051
|
+
console.error(
|
|
5052
|
+
"[vsl_manual_login] failed:",
|
|
5053
|
+
error instanceof Error ? error.name : "Error",
|
|
5054
|
+
sanitizeUrl(typeof args.url === "string" ? args.url : "")
|
|
5055
|
+
);
|
|
5056
|
+
return {
|
|
5057
|
+
status: "error",
|
|
5058
|
+
error: `vsl_manual_login failed: ${error instanceof Error ? error.message : String(error)}`
|
|
5059
|
+
};
|
|
5060
|
+
}
|
|
5061
|
+
}
|
|
5062
|
+
|
|
5063
|
+
// src/tools/index.ts
|
|
5064
|
+
var VSL_TOOLS = [
|
|
5065
|
+
{
|
|
5066
|
+
name: "vsl_get_snapshot",
|
|
5067
|
+
description: "Get the current VSL snapshot of the page. Returns a VSL JSON with the semantic structure of elements. VSL (Visual Scene Language) is a JSON representation of the page where each element has: id (unique identifier, e.g. btn_123), type (button/input/link/text/image), text (text content), bbox ([x,y,width,height]), children (nested elements). Example: { viewport:{width:1920,height:1080}, objects:[{id:btn_1,type:button,text:Sign in,bbox:[100,200,80,30]},{id:inp_2,type:input,text:,bbox:[100,250,200,30]}] }. Usage: get the snapshot, find the desired element by id, then use vsl_execute_action to interact. Lazy text loading (DEC-026): texts longer than 200 characters are automatically replaced with txt_preview (first ~50 characters) + txt_ref (reference like tb_001). Full texts are stored in the text_blocks map. Use vsl_get_text_block to retrieve the full text. Parameters: detail_level (low/medium/high) for object filtering, ttl (ms) for caching.",
|
|
5068
|
+
inputSchema: {
|
|
5069
|
+
type: "object",
|
|
5070
|
+
properties: {
|
|
5071
|
+
url: {
|
|
5072
|
+
type: "string",
|
|
5073
|
+
description: "Page URL (optional, if not specified \u2014 uses the current page)"
|
|
5074
|
+
},
|
|
5075
|
+
detail_level: {
|
|
5076
|
+
type: "string",
|
|
5077
|
+
enum: ["low", "medium", "high"],
|
|
5078
|
+
description: "Snapshot detail level. 'low': interactive elements only (buttons, links, inputs). 'medium': interactive + containers (default). 'high': all objects (full DOM). Default: 'medium'."
|
|
5079
|
+
},
|
|
5080
|
+
ttl: {
|
|
5081
|
+
type: "number",
|
|
5082
|
+
description: "Cache TTL in milliseconds (default: 5000 = 5s). Set to 0 to disable caching."
|
|
5083
|
+
},
|
|
5084
|
+
full: {
|
|
5085
|
+
type: "boolean",
|
|
5086
|
+
description: "Full mode: returns the entire document without filters (replacement for the removed full snapshot tool)"
|
|
5087
|
+
}
|
|
4842
5088
|
}
|
|
4843
|
-
await download.saveAs(resolvedSave);
|
|
4844
5089
|
}
|
|
4845
|
-
}
|
|
4846
|
-
|
|
4847
|
-
|
|
4848
|
-
|
|
4849
|
-
|
|
4850
|
-
|
|
4851
|
-
|
|
4852
|
-
|
|
4853
|
-
|
|
5090
|
+
},
|
|
5091
|
+
{
|
|
5092
|
+
name: "vsl_execute_action",
|
|
5093
|
+
description: 'Execute an action on a VSL element. Find the element by id in the snapshot (vsl_get_snapshot), then call this action. Supported actions: click (click on element), type (enter text, requires value), fill (alias for type, enter text, requires value), scroll (scroll, format: "up", "down", "left", "right" or "dir:amount", e.g. "down:300"), select (select option, requires value), hover, focus, blur, check, uncheck, press (press a keyboard key, requires value \u2014 key name, e.g. "Enter", "Tab", "Escape", "ArrowDown", "ArrowUp", "Space", "Backspace". Used for submitting forms via Enter, navigating via Tab, closing modals via Escape, etc.), upload (file upload, requires value \u2014 file path or comma-separated list of paths). Example: {action:click, target_id:btn_1} or {action:type, target_id:inp_2, value:hello@mail.com} or {action:fill, target_id:inp_2, value:hello@mail.com} or {action:press, target_id:inp_1, value:Enter} or {action:upload, target_id:file_input_0, value:/path/to/file.pdf}. Parameter return_state=true returns diff and snapshot after the action.',
|
|
5094
|
+
inputSchema: {
|
|
5095
|
+
type: "object",
|
|
5096
|
+
properties: {
|
|
5097
|
+
action: {
|
|
5098
|
+
type: "string",
|
|
5099
|
+
description: "Action name (click, type, fill, scroll, select, etc.)"
|
|
5100
|
+
},
|
|
5101
|
+
target_id: {
|
|
5102
|
+
type: "string",
|
|
5103
|
+
description: "Target element ID in VSL JSON"
|
|
5104
|
+
},
|
|
5105
|
+
value: {
|
|
5106
|
+
type: "string",
|
|
5107
|
+
description: "Value for the action (e.g. text for type/fill, option for select)"
|
|
5108
|
+
},
|
|
5109
|
+
return_state: {
|
|
5110
|
+
type: "boolean",
|
|
5111
|
+
description: "If true, returns diff and snapshot after the action. Useful for tracking DOM changes without an extra snapshot call. Default: true \u2014 always return state to save agent steps. Set to false to disable."
|
|
5112
|
+
},
|
|
5113
|
+
timeout: {
|
|
5114
|
+
type: "number",
|
|
5115
|
+
description: "Download completion timeout in ms (only for download action)"
|
|
5116
|
+
},
|
|
5117
|
+
save_path: {
|
|
5118
|
+
type: "string",
|
|
5119
|
+
description: "Path to save the downloaded file (only for download action)"
|
|
5120
|
+
}
|
|
5121
|
+
},
|
|
5122
|
+
required: ["action", "target_id"]
|
|
4854
5123
|
}
|
|
4855
|
-
|
|
4856
|
-
|
|
4857
|
-
|
|
4858
|
-
|
|
4859
|
-
|
|
4860
|
-
|
|
4861
|
-
|
|
4862
|
-
|
|
4863
|
-
|
|
4864
|
-
|
|
4865
|
-
|
|
4866
|
-
|
|
4867
|
-
|
|
4868
|
-
* относительно CWD с path traversal проверкой.
|
|
4869
|
-
* @param selector - CSS-селектор input[type=file] элемента
|
|
4870
|
-
* @param filePaths - Массив путей к файлам (абсолютные или относительные)
|
|
4871
|
-
* @param sessionId - ID сессии
|
|
4872
|
-
* @throws Error если путь выходит за допустимые границы или файл не существует
|
|
4873
|
-
*/
|
|
4874
|
-
async uploadFile(selector, filePaths, sessionId) {
|
|
4875
|
-
const page = await this.getPage(sessionId);
|
|
4876
|
-
if (filePaths.length === 0) {
|
|
4877
|
-
throw new Error("filePaths must contain at least one file path");
|
|
5124
|
+
},
|
|
5125
|
+
{
|
|
5126
|
+
name: "vsl_navigate",
|
|
5127
|
+
description: 'Navigate to a URL in the browser. Use this to open a new page before getting a snapshot. Example: {url:"https://example.com"}. Returns {status:"success"} or {status:"error", message:"..."}. After navigation, call vsl_get_snapshot to get the page structure.',
|
|
5128
|
+
inputSchema: {
|
|
5129
|
+
type: "object",
|
|
5130
|
+
properties: {
|
|
5131
|
+
url: {
|
|
5132
|
+
type: "string",
|
|
5133
|
+
description: "URL to navigate to"
|
|
5134
|
+
}
|
|
5135
|
+
},
|
|
5136
|
+
required: ["url"]
|
|
4878
5137
|
}
|
|
4879
|
-
|
|
4880
|
-
|
|
4881
|
-
|
|
4882
|
-
|
|
4883
|
-
|
|
4884
|
-
|
|
4885
|
-
|
|
4886
|
-
|
|
4887
|
-
|
|
4888
|
-
|
|
5138
|
+
},
|
|
5139
|
+
{
|
|
5140
|
+
name: "vsl_clear_cache",
|
|
5141
|
+
description: "Clear the VSL snapshot cache. Use when you need a fresh snapshot from scratch (e.g. after significant page changes or when switching to a different site). Example: {}. The next vsl_get_snapshot call will create a new snapshot.",
|
|
5142
|
+
inputSchema: {
|
|
5143
|
+
type: "object",
|
|
5144
|
+
properties: {}
|
|
5145
|
+
}
|
|
5146
|
+
},
|
|
5147
|
+
{
|
|
5148
|
+
name: "vsl_get_visual",
|
|
5149
|
+
description: "Get a visual fragment (screenshot) of an element in base64 WebP format. Use for elements that are hard to classify by text alone (icons, charts, custom widgets). Returns {mediaType:image/webp, data:base64data}. Example: {element_id: img_5}. Supports iframe elements: use composite ID format iframe_N:element_Y (e.g. iframe_0:btn_1) to screenshot elements inside iframes. Parameter auto_refresh=true automatically refreshes the snapshot before searching for the element. IMPORTANT: works only with IDs from vsl_get_snapshot (browser DOM). Does NOT work with IDs from vsl_read_page (semantic IDs) \u2014 use vsl_get_snapshot to get compatible IDs.",
|
|
5150
|
+
inputSchema: {
|
|
5151
|
+
type: "object",
|
|
5152
|
+
properties: {
|
|
5153
|
+
element_id: {
|
|
5154
|
+
type: "string",
|
|
5155
|
+
description: "Element ID in VSL JSON"
|
|
5156
|
+
},
|
|
5157
|
+
auto_refresh: {
|
|
5158
|
+
type: "boolean",
|
|
5159
|
+
description: "If true, automatically refreshes the snapshot before searching for the element. Useful after navigation or actions that modify the DOM. Default: false."
|
|
5160
|
+
}
|
|
5161
|
+
},
|
|
5162
|
+
required: ["element_id"]
|
|
5163
|
+
}
|
|
5164
|
+
},
|
|
5165
|
+
{
|
|
5166
|
+
name: "vsl_read_page",
|
|
5167
|
+
description: 'Read web pages. Automatically determines the strategy: static pages are read via HTTP (fast), SPAs are rendered via browser. readable=true filters noise (navigation, footers, cookie banners) for clean content. On repeated calls, returns diff (changes) instead of full content. Parameter detail_level (low/medium/high) filters objects in the snapshot: low \u2014 interactive elements only (buttons, links, inputs), medium \u2014 interactive + containers (default), high \u2014 all objects. Metadata includes vsl_estimated_tokens \u2014 the number of tokens in the VSL snapshot for context estimation. Example: {url:"https://example.com", readable:true, detail_level:"medium"}. Returns snapshot and diff automatically.',
|
|
5168
|
+
inputSchema: {
|
|
5169
|
+
type: "object",
|
|
5170
|
+
properties: {
|
|
5171
|
+
url: {
|
|
5172
|
+
type: "string",
|
|
5173
|
+
description: "Page URL to read"
|
|
5174
|
+
},
|
|
5175
|
+
readable: {
|
|
5176
|
+
type: "boolean",
|
|
5177
|
+
description: "Readable mode: filter noise (nav, footer, cookie banners) for clean content"
|
|
5178
|
+
}
|
|
5179
|
+
},
|
|
5180
|
+
required: ["url"]
|
|
5181
|
+
}
|
|
5182
|
+
},
|
|
5183
|
+
{
|
|
5184
|
+
name: "vsl_get_text_block",
|
|
5185
|
+
description: `Get the full text by txt_ref from lazy text loading (M1.7). When an element's text exceeds 200 characters, only txt_preview (first ~50 characters) and txt_ref (e.g. tb_001) are stored in the VSL JSON. Use this tool to retrieve the full text. Example: {block_id: "tb_001"}. Returns {block_id, text} with the full content.`,
|
|
5186
|
+
inputSchema: {
|
|
5187
|
+
type: "object",
|
|
5188
|
+
properties: {
|
|
5189
|
+
block_id: {
|
|
5190
|
+
type: "string",
|
|
5191
|
+
description: "Text block ID from the txt_ref field of a VSL object (format: tb_xxx)"
|
|
5192
|
+
}
|
|
5193
|
+
},
|
|
5194
|
+
required: ["block_id"]
|
|
5195
|
+
}
|
|
5196
|
+
},
|
|
5197
|
+
{
|
|
5198
|
+
name: "vsl_click_coordinates",
|
|
5199
|
+
description: 'Perform multiple clicks at coordinates relative to a target element. Coordinates (x, y) are specified in pixels from the top-left corner of the element (use bbox from snapshot). Supports delays between clicks. Returns diff + snapshot + screenshot after all clicks. Example: {target_id: "iframe_2", clicks: [{x: 50, y: 50, delay_after_ms: 500}, {x: 150, y: 50}]}.',
|
|
5200
|
+
inputSchema: {
|
|
5201
|
+
type: "object",
|
|
5202
|
+
properties: {
|
|
5203
|
+
target_id: {
|
|
5204
|
+
type: "string",
|
|
5205
|
+
description: "Element ID in VSL JSON (e.g. iframe_2 for reCAPTCHA challenge iframe)"
|
|
5206
|
+
},
|
|
5207
|
+
clicks: {
|
|
5208
|
+
type: "array",
|
|
5209
|
+
description: "Array of clicks. Each click: {x: number, y: number, delay_after_ms?: number}. Coordinates in pixels from the top-left corner of the element.",
|
|
5210
|
+
items: {
|
|
5211
|
+
type: "object",
|
|
5212
|
+
properties: {
|
|
5213
|
+
x: { type: "number", description: "X coordinate (pixels from left edge of element)" },
|
|
5214
|
+
y: { type: "number", description: "Y coordinate (pixels from top edge of element)" },
|
|
5215
|
+
delay_after_ms: { type: "number", description: "Delay after click (ms)" }
|
|
5216
|
+
},
|
|
5217
|
+
required: ["x", "y"]
|
|
5218
|
+
}
|
|
5219
|
+
},
|
|
5220
|
+
return_state: {
|
|
5221
|
+
type: "boolean",
|
|
5222
|
+
description: "If true (default), returns diff + snapshot + screenshot after all clicks."
|
|
5223
|
+
}
|
|
5224
|
+
},
|
|
5225
|
+
required: ["target_id", "clicks"]
|
|
5226
|
+
}
|
|
5227
|
+
},
|
|
5228
|
+
{
|
|
5229
|
+
name: "vsl_manual_login",
|
|
5230
|
+
description: 'Open a VISIBLE window of the SAME VSL browser profile (~/.vsl/browser-profile) so the user can sign in MANUALLY. Captcha, 2FA and anti-bot challenges are solved by the human \u2014 no automatic captcha bypass. Actions: open (open the login page in a visible window and return the link to the user; url is required for this action), status (check the sign-in signal without exposing secrets), finish (save the result and invalidate snapshot caches of all sessions). Cookies and localStorage stay in the shared profile, so all subsequent VSL tools and sessions are already signed in. Example: {action: "open", url: "https://example.com/login"}.',
|
|
5231
|
+
inputSchema: {
|
|
5232
|
+
type: "object",
|
|
5233
|
+
properties: {
|
|
5234
|
+
action: {
|
|
5235
|
+
type: "string",
|
|
5236
|
+
enum: ["open", "status", "finish"],
|
|
5237
|
+
description: "Action to perform (default: open). open \u2014 visible login window + link for the user; status \u2014 check the sign-in; finish \u2014 save the result."
|
|
5238
|
+
},
|
|
5239
|
+
url: {
|
|
5240
|
+
type: "string",
|
|
5241
|
+
description: "Login page URL (required for action=open, http/https only). Returned to the user without query and hash."
|
|
5242
|
+
},
|
|
5243
|
+
wait: {
|
|
5244
|
+
type: "boolean",
|
|
5245
|
+
description: "Only for open: block until the sign-in signal is found or the timeout expires (default false \u2014 non-blocking)."
|
|
5246
|
+
},
|
|
5247
|
+
timeout_ms: {
|
|
5248
|
+
type: "number",
|
|
5249
|
+
description: "Manual login timeout in ms (default 180000 from browser.manualLogin.timeoutMs, clamped to 1000..600000)."
|
|
5250
|
+
},
|
|
5251
|
+
success_selector: {
|
|
5252
|
+
type: "string",
|
|
5253
|
+
description: "CSS selector that proves the user is signed in (e.g. [data-testid=avatar]). No cookie or storage values are read."
|
|
5254
|
+
},
|
|
5255
|
+
success_url_pattern: {
|
|
5256
|
+
type: "string",
|
|
5257
|
+
description: "Substring of the page URL that proves the user is signed in (e.g. /dashboard)."
|
|
5258
|
+
},
|
|
5259
|
+
restore_headless: {
|
|
5260
|
+
type: "boolean",
|
|
5261
|
+
description: "Only for finish: return the browser to headless (default false \u2014 the visible window stays alive, so sessionStorage and session-only cookies survive)."
|
|
5262
|
+
},
|
|
5263
|
+
takeover: {
|
|
5264
|
+
type: "boolean",
|
|
5265
|
+
description: "Only for open (default false): if VSL is connected via CDP to a HEADLESS VSL browser, close it and reopen it visible on the same profile. Without it the tool returns an error with instructions. A real visible Chrome of the user is never closed."
|
|
4889
5266
|
}
|
|
4890
|
-
resolvedPaths.push(resolved);
|
|
4891
5267
|
}
|
|
4892
5268
|
}
|
|
4893
|
-
await page.setInputFiles(selector, resolvedPaths.length === 1 ? resolvedPaths[0] : resolvedPaths);
|
|
4894
|
-
}
|
|
4895
|
-
/**
|
|
4896
|
-
* Ожидает появления file chooser dialog (для кастомных file picker'ов).
|
|
4897
|
-
* Возвращает FileChooser, через который можно установить файлы.
|
|
4898
|
-
* @param sessionId - ID сессии
|
|
4899
|
-
* @param timeout - Таймаут ожидания в мс (по умолчанию из config.downloadTimeout)
|
|
4900
|
-
* @returns PlaywrightFileChooser для установки файлов
|
|
4901
|
-
*/
|
|
4902
|
-
async waitForFileChooser(sessionId, timeout) {
|
|
4903
|
-
const page = await this.getPage(sessionId);
|
|
4904
|
-
const waitTimeout = timeout ?? this.config.downloadTimeout ?? 6e4;
|
|
4905
|
-
const fileChooser = await page.waitForEvent("filechooser", { timeout: waitTimeout });
|
|
4906
|
-
return fileChooser;
|
|
4907
5269
|
}
|
|
4908
|
-
|
|
4909
|
-
|
|
4910
|
-
|
|
4911
|
-
|
|
4912
|
-
|
|
4913
|
-
|
|
4914
|
-
|
|
4915
|
-
|
|
4916
|
-
|
|
4917
|
-
|
|
4918
|
-
|
|
4919
|
-
|
|
4920
|
-
}
|
|
4921
|
-
}
|
|
4922
|
-
this.pages.clear();
|
|
5270
|
+
];
|
|
5271
|
+
function registerTools(server, config, sessionManager) {
|
|
5272
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
5273
|
+
return {
|
|
5274
|
+
tools: VSL_TOOLS
|
|
5275
|
+
};
|
|
5276
|
+
});
|
|
5277
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
5278
|
+
const { name, arguments: args, _meta } = request.params;
|
|
5279
|
+
const sessionId = _meta?.sessionId ?? sessionManager.getDefaultSessionId();
|
|
5280
|
+
const { session } = sessionManager.getSession(sessionId);
|
|
5281
|
+
const browser = sessionManager.getBrowserManager();
|
|
4923
5282
|
try {
|
|
4924
|
-
|
|
4925
|
-
|
|
4926
|
-
|
|
5283
|
+
let result;
|
|
5284
|
+
switch (name) {
|
|
5285
|
+
case "vsl_get_snapshot":
|
|
5286
|
+
result = await handleGetSnapshot(args, browser, session, config, sessionId);
|
|
5287
|
+
break;
|
|
5288
|
+
case "vsl_execute_action":
|
|
5289
|
+
result = await handleExecuteAction(args, browser, session, sessionId);
|
|
5290
|
+
break;
|
|
5291
|
+
case "vsl_navigate":
|
|
5292
|
+
result = await handleNavigate(args, browser, session, sessionId);
|
|
5293
|
+
break;
|
|
5294
|
+
case "vsl_clear_cache":
|
|
5295
|
+
result = await handleClearCache(session);
|
|
5296
|
+
break;
|
|
5297
|
+
case "vsl_get_visual":
|
|
5298
|
+
result = await handleGetVisual(args, browser, session, sessionId);
|
|
5299
|
+
break;
|
|
5300
|
+
case "vsl_read_page":
|
|
5301
|
+
result = await handleReadPage(args, browser, session, config, sessionId);
|
|
5302
|
+
break;
|
|
5303
|
+
case "vsl_get_text_block":
|
|
5304
|
+
result = await handleGetTextBlock(args, session);
|
|
5305
|
+
break;
|
|
5306
|
+
case "vsl_click_coordinates":
|
|
5307
|
+
result = await handleClickCoordinates(args, browser, session, sessionId);
|
|
5308
|
+
break;
|
|
5309
|
+
case "vsl_manual_login":
|
|
5310
|
+
result = await handleManualLogin(args, browser, session, sessionManager, config, sessionId);
|
|
5311
|
+
break;
|
|
5312
|
+
default:
|
|
5313
|
+
return {
|
|
5314
|
+
content: [
|
|
5315
|
+
{
|
|
5316
|
+
type: "text",
|
|
5317
|
+
text: JSON.stringify({
|
|
5318
|
+
error: `Unknown tool: ${name}`
|
|
5319
|
+
})
|
|
5320
|
+
}
|
|
5321
|
+
],
|
|
5322
|
+
isError: true
|
|
5323
|
+
};
|
|
4927
5324
|
}
|
|
4928
|
-
if (
|
|
4929
|
-
|
|
4930
|
-
this.browser = null;
|
|
4931
|
-
} else if (this.connectedViaCDP) {
|
|
4932
|
-
this.browser = null;
|
|
5325
|
+
if (result && typeof result === "object" && "content" in result && Array.isArray(result.content)) {
|
|
5326
|
+
return result;
|
|
4933
5327
|
}
|
|
5328
|
+
return {
|
|
5329
|
+
content: [
|
|
5330
|
+
{
|
|
5331
|
+
type: "text",
|
|
5332
|
+
text: JSON.stringify(result)
|
|
5333
|
+
}
|
|
5334
|
+
]
|
|
5335
|
+
};
|
|
4934
5336
|
} catch (error) {
|
|
4935
|
-
|
|
4936
|
-
|
|
4937
|
-
|
|
5337
|
+
return {
|
|
5338
|
+
content: [
|
|
5339
|
+
{
|
|
5340
|
+
type: "text",
|
|
5341
|
+
text: JSON.stringify({
|
|
5342
|
+
error: `Tool execution failed: ${error instanceof Error ? error.message : String(error)}`
|
|
5343
|
+
})
|
|
5344
|
+
}
|
|
5345
|
+
],
|
|
5346
|
+
isError: true
|
|
5347
|
+
};
|
|
4938
5348
|
}
|
|
4939
|
-
|
|
5349
|
+
});
|
|
5350
|
+
}
|
|
5351
|
+
|
|
5352
|
+
// src/resources/index.ts
|
|
5353
|
+
import {
|
|
5354
|
+
ListResourcesRequestSchema,
|
|
5355
|
+
ReadResourceRequestSchema
|
|
5356
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
5357
|
+
var VSL_RESOURCES = [
|
|
5358
|
+
{
|
|
5359
|
+
uri: "vsl://current",
|
|
5360
|
+
name: "Current VSL Snapshot",
|
|
5361
|
+
description: "Current VSL snapshot of the page. Contains the full semantic structure of elements.",
|
|
5362
|
+
mimeType: "application/json"
|
|
5363
|
+
},
|
|
5364
|
+
{
|
|
5365
|
+
uri: "vsl://diff",
|
|
5366
|
+
name: "Latest VSL Diff",
|
|
5367
|
+
description: "Latest VSL diff since the previous snapshot. Contains only changes (added/modified/removed).",
|
|
5368
|
+
mimeType: "application/json"
|
|
4940
5369
|
}
|
|
4941
|
-
|
|
5370
|
+
];
|
|
5371
|
+
function registerResources(server, _config, sessionManager) {
|
|
5372
|
+
server.setRequestHandler(ListResourcesRequestSchema, async () => {
|
|
5373
|
+
return {
|
|
5374
|
+
resources: VSL_RESOURCES
|
|
5375
|
+
};
|
|
5376
|
+
});
|
|
5377
|
+
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
5378
|
+
const { uri } = request.params;
|
|
5379
|
+
const sessionId = request.params._meta?.sessionId ?? sessionManager.getDefaultSessionId();
|
|
5380
|
+
const { session } = sessionManager.getSession(sessionId);
|
|
5381
|
+
ensureSubscribed(sessionId, session);
|
|
5382
|
+
switch (uri) {
|
|
5383
|
+
case "vsl://current":
|
|
5384
|
+
try {
|
|
5385
|
+
const snapshot = session.getSnapshot();
|
|
5386
|
+
return {
|
|
5387
|
+
contents: [
|
|
5388
|
+
{
|
|
5389
|
+
uri,
|
|
5390
|
+
mimeType: "application/json",
|
|
5391
|
+
text: JSON.stringify(snapshot, null, 2)
|
|
5392
|
+
}
|
|
5393
|
+
]
|
|
5394
|
+
};
|
|
5395
|
+
} catch {
|
|
5396
|
+
return {
|
|
5397
|
+
contents: [
|
|
5398
|
+
{
|
|
5399
|
+
uri,
|
|
5400
|
+
mimeType: "application/json",
|
|
5401
|
+
text: JSON.stringify({
|
|
5402
|
+
error: "No snapshot available. Call vsl_get_snapshot first."
|
|
5403
|
+
})
|
|
5404
|
+
}
|
|
5405
|
+
]
|
|
5406
|
+
};
|
|
5407
|
+
}
|
|
5408
|
+
case "vsl://diff":
|
|
5409
|
+
try {
|
|
5410
|
+
const diff = session.getDiff();
|
|
5411
|
+
if (!diff) {
|
|
5412
|
+
return {
|
|
5413
|
+
contents: [
|
|
5414
|
+
{
|
|
5415
|
+
uri,
|
|
5416
|
+
mimeType: "application/json",
|
|
5417
|
+
text: JSON.stringify({
|
|
5418
|
+
error: "No diff available. This is the first snapshot or no changes detected."
|
|
5419
|
+
})
|
|
5420
|
+
}
|
|
5421
|
+
]
|
|
5422
|
+
};
|
|
5423
|
+
}
|
|
5424
|
+
return {
|
|
5425
|
+
contents: [
|
|
5426
|
+
{
|
|
5427
|
+
uri,
|
|
5428
|
+
mimeType: "application/json",
|
|
5429
|
+
text: JSON.stringify(diff, null, 2)
|
|
5430
|
+
}
|
|
5431
|
+
]
|
|
5432
|
+
};
|
|
5433
|
+
} catch {
|
|
5434
|
+
return {
|
|
5435
|
+
contents: [
|
|
5436
|
+
{
|
|
5437
|
+
uri,
|
|
5438
|
+
mimeType: "application/json",
|
|
5439
|
+
text: JSON.stringify({
|
|
5440
|
+
error: "Failed to compute diff."
|
|
5441
|
+
})
|
|
5442
|
+
}
|
|
5443
|
+
]
|
|
5444
|
+
};
|
|
5445
|
+
}
|
|
5446
|
+
default:
|
|
5447
|
+
throw new Error(`Unknown resource: ${uri}`);
|
|
5448
|
+
}
|
|
5449
|
+
});
|
|
5450
|
+
const subscribedSessions = /* @__PURE__ */ new Set();
|
|
5451
|
+
function ensureSubscribed(sessionId, session) {
|
|
5452
|
+
if (subscribedSessions.has(sessionId)) return;
|
|
5453
|
+
subscribedSessions.add(sessionId);
|
|
5454
|
+
session.setOnSnapshotChange(() => {
|
|
5455
|
+
server.sendResourceUpdated({ uri: "vsl://current" }).catch(() => {
|
|
5456
|
+
});
|
|
5457
|
+
if (session.getDiff()) {
|
|
5458
|
+
server.sendResourceUpdated({ uri: "vsl://diff" }).catch(() => {
|
|
5459
|
+
});
|
|
5460
|
+
}
|
|
5461
|
+
});
|
|
5462
|
+
}
|
|
5463
|
+
}
|
|
4942
5464
|
|
|
4943
5465
|
// src/session/serverSession.ts
|
|
4944
5466
|
import { diffVslDocuments, segmentTree, buildVslDocument } from "@thinkingos/vsl-sdk";
|
|
@@ -5196,6 +5718,16 @@ var SessionManager = class {
|
|
|
5196
5718
|
context.lastAccessedAt = Date.now();
|
|
5197
5719
|
return context;
|
|
5198
5720
|
}
|
|
5721
|
+
/**
|
|
5722
|
+
* Сбрасывает кэши снапшотов всех сессий. Возвращает число очищенных сессий.
|
|
5723
|
+
* Нужен после перезапуска браузера (vsl_manual_login): старые VSL ID невалидны.
|
|
5724
|
+
*/
|
|
5725
|
+
clearAllSessionCaches() {
|
|
5726
|
+
for (const context of this.sessions.values()) {
|
|
5727
|
+
context.session.clear();
|
|
5728
|
+
}
|
|
5729
|
+
return this.sessions.size;
|
|
5730
|
+
}
|
|
5199
5731
|
/**
|
|
5200
5732
|
* Проверяет, существует ли сессия.
|
|
5201
5733
|
*/
|
|
@@ -5284,7 +5816,7 @@ var SessionManager = class {
|
|
|
5284
5816
|
};
|
|
5285
5817
|
|
|
5286
5818
|
// src/version.ts
|
|
5287
|
-
var VSL_MCP_SERVER_VERSION = "1.4.
|
|
5819
|
+
var VSL_MCP_SERVER_VERSION = "1.4.6";
|
|
5288
5820
|
|
|
5289
5821
|
// src/index.ts
|
|
5290
5822
|
async function main() {
|