@thinkingos/vsl-mcp-server 1.4.3 → 1.4.5

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 CHANGED
@@ -102,12 +102,127 @@ var init_domStabilization = __esm({
102
102
  }
103
103
  });
104
104
 
105
+ // src/browser/browserBinary.ts
106
+ import { spawn } from "child_process";
107
+ import { existsSync } from "fs";
108
+ import { createRequire } from "module";
109
+ import path from "path";
110
+ function parseMissingBrowserError(error) {
111
+ const message = error instanceof Error ? error.message : typeof error === "string" ? error : "";
112
+ const match = EXECUTABLE_MISSING_RE.exec(message);
113
+ const rawPath = match?.[1];
114
+ if (!rawPath) return null;
115
+ const executablePath = rawPath.trim();
116
+ for (const segment of executablePath.split(/[\\/]/)) {
117
+ const revisionMatch = REVISION_DIR_RE.exec(segment);
118
+ const artifact = revisionMatch?.[1];
119
+ if (!artifact) continue;
120
+ const browser = ARTIFACT_TO_BROWSER[artifact];
121
+ if (!browser) continue;
122
+ return { executablePath, browser, revisionDir: segment };
123
+ }
124
+ return null;
125
+ }
126
+ function resolvePlaywrightCliPath() {
127
+ const resolveFromHere = createRequire(import.meta.url);
128
+ for (const pkg of ["playwright", "playwright-core"]) {
129
+ try {
130
+ const entry = resolveFromHere.resolve(pkg);
131
+ const cliPath = path.join(path.dirname(entry), "cli.js");
132
+ if (existsSync(cliPath)) return cliPath;
133
+ } catch {
134
+ }
135
+ }
136
+ return null;
137
+ }
138
+ function formatMissingBrowserError(info, options = {}) {
139
+ const command = options.cliPath ? `node "${options.cliPath}" install ${info.browser}` : `npx playwright install ${info.browser}`;
140
+ const lines = [
141
+ `Playwright browser binary is missing: ${info.executablePath}`,
142
+ `Required revision: ${info.revisionDir}. The shared Playwright browser cache was cleared (OS cache cleanup / manual removal) or Playwright was updated.`
143
+ ];
144
+ if (options.autoInstallDisabled) {
145
+ lines.push(
146
+ "Automatic download is disabled (browser.autoInstallBrowser=false / VSL_BROWSER_AUTO_INSTALL=false)."
147
+ );
148
+ }
149
+ if (options.reason) {
150
+ lines.push(`Automatic download did not help: ${options.reason}`);
151
+ }
152
+ lines.push(`Fix: ${command}`);
153
+ return lines.join("\n");
154
+ }
155
+ async function installBrowser(options) {
156
+ const { browser, cliPath, timeoutMs } = options;
157
+ const key = `${cliPath}::${browser}`;
158
+ const inFlight = inFlightInstalls.get(key);
159
+ if (inFlight) return inFlight;
160
+ const promise = runInstall(cliPath, browser, timeoutMs).finally(() => {
161
+ inFlightInstalls.delete(key);
162
+ });
163
+ inFlightInstalls.set(key, promise);
164
+ return promise;
165
+ }
166
+ function runInstall(cliPath, browser, timeoutMs) {
167
+ return new Promise((resolve) => {
168
+ const child = spawn(process.execPath, [cliPath, "install", browser], {
169
+ stdio: ["ignore", "pipe", "pipe"]
170
+ });
171
+ let output = "";
172
+ let timedOut = false;
173
+ const collect = (chunk) => {
174
+ output += chunk.toString();
175
+ if (output.length > MAX_INSTALL_OUTPUT) {
176
+ output = output.slice(-MAX_INSTALL_OUTPUT);
177
+ }
178
+ };
179
+ const timer = setTimeout(() => {
180
+ timedOut = true;
181
+ child.kill("SIGTERM");
182
+ }, timeoutMs);
183
+ child.stdout?.on("data", collect);
184
+ child.stderr?.on("data", collect);
185
+ child.on("error", (error) => {
186
+ clearTimeout(timer);
187
+ resolve({ success: false, output, error: error.message });
188
+ });
189
+ child.on("close", (code) => {
190
+ clearTimeout(timer);
191
+ if (timedOut) {
192
+ resolve({ success: false, output, error: `timed out after ${timeoutMs}ms` });
193
+ } else if (code === 0) {
194
+ resolve({ success: true, output });
195
+ } else {
196
+ resolve({ success: false, output, error: `install exited with code ${code}` });
197
+ }
198
+ });
199
+ });
200
+ }
201
+ var DEFAULT_BROWSER_INSTALL_TIMEOUT_MS, MAX_INSTALL_OUTPUT, EXECUTABLE_MISSING_RE, REVISION_DIR_RE, ARTIFACT_TO_BROWSER, inFlightInstalls;
202
+ var init_browserBinary = __esm({
203
+ "src/browser/browserBinary.ts"() {
204
+ "use strict";
205
+ DEFAULT_BROWSER_INSTALL_TIMEOUT_MS = 3e5;
206
+ MAX_INSTALL_OUTPUT = 8e3;
207
+ EXECUTABLE_MISSING_RE = /Executable doesn't exist at\s+(.+)/;
208
+ REVISION_DIR_RE = /^([a-z_]+)-(\d+)$/;
209
+ ARTIFACT_TO_BROWSER = {
210
+ chromium: "chromium",
211
+ chromium_headless_shell: "chromium",
212
+ firefox: "firefox",
213
+ webkit: "webkit"
214
+ };
215
+ inFlightInstalls = /* @__PURE__ */ new Map();
216
+ }
217
+ });
218
+
105
219
  // src/config/loader.ts
106
220
  var loader_exports = {};
107
221
  __export(loader_exports, {
108
- loadConfig: () => loadConfig
222
+ loadConfig: () => loadConfig,
223
+ parseManualLoginConfig: () => parseManualLoginConfig
109
224
  });
110
- import { readFileSync, existsSync } from "fs";
225
+ import { readFileSync, existsSync as existsSync2 } from "fs";
111
226
  import { homedir } from "os";
112
227
  import { join } from "path";
113
228
  function loadConfig() {
@@ -129,7 +244,10 @@ function loadConfig() {
129
244
  acceptDownloads: process.env.VSL_ACCEPT_DOWNLOADS ? process.env.VSL_ACCEPT_DOWNLOADS === "true" : fileConfig.browser?.acceptDownloads ?? DEFAULT_BROWSER_CONFIG.acceptDownloads,
130
245
  userDataDir: process.env.VSL_USER_DATA_DIR || fileConfig.browser?.userDataDir || DEFAULT_BROWSER_CONFIG.userDataDir,
131
246
  cdpPort: process.env.VSL_CDP_PORT ? parseInt(process.env.VSL_CDP_PORT, 10) : fileConfig.browser?.cdpPort ?? DEFAULT_BROWSER_CONFIG.cdpPort,
132
- proxy: parseProxyConfig(fileConfig)
247
+ autoInstallBrowser: process.env.VSL_BROWSER_AUTO_INSTALL ? process.env.VSL_BROWSER_AUTO_INSTALL === "true" : fileConfig.browser?.autoInstallBrowser ?? DEFAULT_BROWSER_CONFIG.autoInstallBrowser,
248
+ browserInstallTimeout: process.env.VSL_BROWSER_INSTALL_TIMEOUT ? parseInt(process.env.VSL_BROWSER_INSTALL_TIMEOUT, 10) : fileConfig.browser?.browserInstallTimeout ?? DEFAULT_BROWSER_CONFIG.browserInstallTimeout,
249
+ proxy: parseProxyConfig(fileConfig),
250
+ manualLogin: parseManualLoginConfig(fileConfig)
133
251
  };
134
252
  const humanization = parseHumanizationConfig(fileConfig);
135
253
  const domStabilization = parseDomStabilizationConfig(fileConfig);
@@ -174,8 +292,32 @@ function parseDomStabilizationConfig(fileConfig) {
174
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;
175
293
  return { enabled, timeout, stablePeriod, pollInterval, waitForNetworkIdle, networkIdleTimeout };
176
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
+ }
177
319
  function loadConfigFile() {
178
- if (!existsSync(DEFAULT_CONFIG_PATH)) {
320
+ if (!existsSync2(DEFAULT_CONFIG_PATH)) {
179
321
  return {};
180
322
  }
181
323
  try {
@@ -186,11 +328,12 @@ function loadConfigFile() {
186
328
  return {};
187
329
  }
188
330
  }
189
- 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;
190
332
  var init_loader = __esm({
191
333
  "src/config/loader.ts"() {
192
334
  "use strict";
193
335
  init_domStabilization();
336
+ init_browserBinary();
194
337
  DEFAULT_CONFIG_PATH = join(homedir(), ".vsl", "config.json");
195
338
  DEFAULT_VISION_MODELS = {
196
339
  openai: "gpt-6-luna",
@@ -198,6 +341,14 @@ var init_loader = __esm({
198
341
  custom: ""
199
342
  // Пользователь должен указать модель для custom провайдера
200
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
+ };
201
352
  DEFAULT_BROWSER_CONFIG = {
202
353
  headless: true,
203
354
  navigationTimeout: 3e4,
@@ -207,8 +358,12 @@ var init_loader = __esm({
207
358
  acceptDownloads: true,
208
359
  userDataDir: void 0,
209
360
  // Дефолт ~/.vsl/browser-profile применяется в manager.ts
210
- cdpPort: 9222
361
+ cdpPort: 9222,
211
362
  // Дефолтный CDP port для подключения множественных агентов
363
+ autoInstallBrowser: true,
364
+ // Self-heal: скачивать браузер, если кэш Playwright очищен
365
+ browserInstallTimeout: DEFAULT_BROWSER_INSTALL_TIMEOUT_MS,
366
+ manualLogin: DEFAULT_MANUAL_LOGIN_CONFIG
212
367
  };
213
368
  DEFAULT_HUMANIZATION_CONFIG = {
214
369
  enabled: true,
@@ -832,14 +987,14 @@ function extractDomTreeInBrowser() {
832
987
  function collectVisibleChildren(parent, parentPath) {
833
988
  const result = [];
834
989
  Array.from(parent.children).forEach((child, index) => {
835
- const path2 = [...parentPath, index];
990
+ const path3 = [...parentPath, index];
836
991
  const tag = child.tagName.toLowerCase();
837
992
  if (NON_RENDERABLE_TAGS.has(tag) || isDisplayNone(child)) {
838
993
  return;
839
994
  }
840
995
  const rect = toRect(child.getBoundingClientRect());
841
996
  if (isVisibilityHidden(child) || hasZeroBox(rect)) {
842
- result.push(...collectVisibleChildren(child, path2));
997
+ result.push(...collectVisibleChildren(child, path3));
843
998
  return;
844
999
  }
845
1000
  const attributes = extractAttributes(child);
@@ -850,12 +1005,12 @@ function extractDomTreeInBrowser() {
850
1005
  if (css.opacity === "0" && css.pointerEvents === "none") {
851
1006
  return;
852
1007
  }
853
- const children = collectVisibleChildren(child, path2);
854
- const vslId = `${tag}_${path2.join("_")}`;
1008
+ const children = collectVisibleChildren(child, path3);
1009
+ const vslId = `${tag}_${path3.join("_")}`;
855
1010
  child.setAttribute("data-vsl-id", vslId);
856
1011
  result.push({
857
1012
  tag,
858
- indexPath: path2,
1013
+ indexPath: path3,
859
1014
  rect,
860
1015
  text: ownText(child) || null,
861
1016
  attributes,
@@ -3852,492 +4007,135 @@ async function handleClickCoordinates(args, browser, session, sessionId) {
3852
4007
  }
3853
4008
  }
3854
4009
 
3855
- // src/tools/index.ts
3856
- var VSL_TOOLS = [
3857
- {
3858
- name: "vsl_get_snapshot",
3859
- 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.",
3860
- inputSchema: {
3861
- type: "object",
3862
- properties: {
3863
- url: {
3864
- type: "string",
3865
- description: "Page URL (optional, if not specified \u2014 uses the current page)"
3866
- },
3867
- detail_level: {
3868
- type: "string",
3869
- enum: ["low", "medium", "high"],
3870
- description: "Snapshot detail level. 'low': interactive elements only (buttons, links, inputs). 'medium': interactive + containers (default). 'high': all objects (full DOM). Default: 'medium'."
3871
- },
3872
- ttl: {
3873
- type: "number",
3874
- description: "Cache TTL in milliseconds (default: 5000 = 5s). Set to 0 to disable caching."
3875
- },
3876
- full: {
3877
- type: "boolean",
3878
- description: "Full mode: returns the entire document without filters (replacement for the removed full snapshot tool)"
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;
3879
4060
  }
3880
4061
  }
3881
4062
  }
3882
- },
3883
- {
3884
- name: "vsl_execute_action",
3885
- 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.',
3886
- inputSchema: {
3887
- type: "object",
3888
- properties: {
3889
- action: {
3890
- type: "string",
3891
- description: "Action name (click, type, fill, scroll, select, etc.)"
3892
- },
3893
- target_id: {
3894
- type: "string",
3895
- description: "Target element ID in VSL JSON"
3896
- },
3897
- value: {
3898
- type: "string",
3899
- description: "Value for the action (e.g. text for type/fill, option for select)"
3900
- },
3901
- return_state: {
3902
- type: "boolean",
3903
- description: "If true, returns diff and snapshot after the action. Useful for tracking DOM changes without an additional vsl_get_diff call. Default: true \u2014 always return state to save agent steps. Set to false to disable."
3904
- },
3905
- timeout: {
3906
- type: "number",
3907
- description: "Download completion timeout in ms (only for download action)"
3908
- },
3909
- save_path: {
3910
- type: "string",
3911
- description: "Path to save the downloaded file (only for download action)"
3912
- }
3913
- },
3914
- required: ["action", "target_id"]
3915
- }
3916
- },
3917
- {
3918
- name: "vsl_navigate",
3919
- 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.',
3920
- inputSchema: {
3921
- type: "object",
3922
- properties: {
3923
- url: {
3924
- type: "string",
3925
- description: "URL to navigate to"
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 {
3926
4129
  }
3927
- },
3928
- required: ["url"]
4130
+ }
3929
4131
  }
3930
- },
3931
- {
3932
- name: "vsl_clear_cache",
3933
- 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.",
3934
- inputSchema: {
3935
- type: "object",
3936
- properties: {}
4132
+ inspection = await inspectPage(page);
4133
+ if (!inspection.isChallenge) {
4134
+ return { status: clicked ? "clicked" : "auto", attempts };
3937
4135
  }
3938
- },
3939
- {
3940
- name: "vsl_get_visual",
3941
- 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.",
3942
- inputSchema: {
3943
- type: "object",
3944
- properties: {
3945
- element_id: {
3946
- type: "string",
3947
- description: "Element ID in VSL JSON"
3948
- },
3949
- auto_refresh: {
3950
- type: "boolean",
3951
- description: "If true, automatically refreshes the snapshot before searching for the element. Useful after navigation or actions that modify the DOM. Default: false."
3952
- }
3953
- },
3954
- required: ["element_id"]
3955
- }
3956
- },
3957
- {
3958
- name: "vsl_read_page",
3959
- 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.',
3960
- inputSchema: {
3961
- type: "object",
3962
- properties: {
3963
- url: {
3964
- type: "string",
3965
- description: "Page URL to read"
3966
- },
3967
- readable: {
3968
- type: "boolean",
3969
- description: "Readable mode: filter noise (nav, footer, cookie banners) for clean content"
3970
- }
3971
- },
3972
- required: ["url"]
3973
- }
3974
- },
3975
- {
3976
- name: "vsl_get_text_block",
3977
- 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.`,
3978
- inputSchema: {
3979
- type: "object",
3980
- properties: {
3981
- block_id: {
3982
- type: "string",
3983
- description: "Text block ID from the txt_ref field of a VSL object (format: tb_xxx)"
3984
- }
3985
- },
3986
- required: ["block_id"]
3987
- }
3988
- },
3989
- {
3990
- name: "vsl_click_coordinates",
3991
- 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}]}.',
3992
- inputSchema: {
3993
- type: "object",
3994
- properties: {
3995
- target_id: {
3996
- type: "string",
3997
- description: "Element ID in VSL JSON (e.g. iframe_2 for reCAPTCHA challenge iframe)"
3998
- },
3999
- clicks: {
4000
- type: "array",
4001
- 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.",
4002
- items: {
4003
- type: "object",
4004
- properties: {
4005
- x: { type: "number", description: "X coordinate (pixels from left edge of element)" },
4006
- y: { type: "number", description: "Y coordinate (pixels from top edge of element)" },
4007
- delay_after_ms: { type: "number", description: "Delay after click (ms)" }
4008
- },
4009
- required: ["x", "y"]
4010
- }
4011
- },
4012
- return_state: {
4013
- type: "boolean",
4014
- description: "If true (default), returns diff + snapshot + screenshot after all clicks."
4015
- }
4016
- },
4017
- required: ["target_id", "clicks"]
4018
- }
4019
- }
4020
- ];
4021
- function registerTools(server, config, sessionManager) {
4022
- server.setRequestHandler(ListToolsRequestSchema, async () => {
4023
- return {
4024
- tools: VSL_TOOLS
4025
- };
4026
- });
4027
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
4028
- const { name, arguments: args, _meta } = request.params;
4029
- const sessionId = _meta?.sessionId ?? sessionManager.getDefaultSessionId();
4030
- const { session } = sessionManager.getSession(sessionId);
4031
- const browser = sessionManager.getBrowserManager();
4032
- try {
4033
- let result;
4034
- switch (name) {
4035
- case "vsl_get_snapshot":
4036
- result = await handleGetSnapshot(args, browser, session, config, sessionId);
4037
- break;
4038
- case "vsl_execute_action":
4039
- result = await handleExecuteAction(args, browser, session, sessionId);
4040
- break;
4041
- case "vsl_navigate":
4042
- result = await handleNavigate(args, browser, session, sessionId);
4043
- break;
4044
- case "vsl_clear_cache":
4045
- result = await handleClearCache(session);
4046
- break;
4047
- case "vsl_get_visual":
4048
- result = await handleGetVisual(args, browser, session, sessionId);
4049
- break;
4050
- case "vsl_read_page":
4051
- result = await handleReadPage(args, browser, session, config, sessionId);
4052
- break;
4053
- case "vsl_get_text_block":
4054
- result = await handleGetTextBlock(args, session);
4055
- break;
4056
- case "vsl_click_coordinates":
4057
- result = await handleClickCoordinates(args, browser, session, sessionId);
4058
- break;
4059
- default:
4060
- return {
4061
- content: [
4062
- {
4063
- type: "text",
4064
- text: JSON.stringify({
4065
- error: `Unknown tool: ${name}`
4066
- })
4067
- }
4068
- ],
4069
- isError: true
4070
- };
4071
- }
4072
- if (result && typeof result === "object" && "content" in result && Array.isArray(result.content)) {
4073
- return result;
4074
- }
4075
- return {
4076
- content: [
4077
- {
4078
- type: "text",
4079
- text: JSON.stringify(result)
4080
- }
4081
- ]
4082
- };
4083
- } catch (error) {
4084
- return {
4085
- content: [
4086
- {
4087
- type: "text",
4088
- text: JSON.stringify({
4089
- error: `Tool execution failed: ${error instanceof Error ? error.message : String(error)}`
4090
- })
4091
- }
4092
- ],
4093
- isError: true
4094
- };
4095
- }
4096
- });
4097
- }
4098
-
4099
- // src/resources/index.ts
4100
- import {
4101
- ListResourcesRequestSchema,
4102
- ReadResourceRequestSchema
4103
- } from "@modelcontextprotocol/sdk/types.js";
4104
- var VSL_RESOURCES = [
4105
- {
4106
- uri: "vsl://current",
4107
- name: "Current VSL Snapshot",
4108
- description: "Current VSL snapshot of the page. Contains the full semantic structure of elements.",
4109
- mimeType: "application/json"
4110
- },
4111
- {
4112
- uri: "vsl://diff",
4113
- name: "Latest VSL Diff",
4114
- description: "Latest VSL diff since the previous snapshot. Contains only changes (added/modified/removed).",
4115
- mimeType: "application/json"
4116
- }
4117
- ];
4118
- function registerResources(server, _config, sessionManager) {
4119
- server.setRequestHandler(ListResourcesRequestSchema, async () => {
4120
- return {
4121
- resources: VSL_RESOURCES
4122
- };
4123
- });
4124
- server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
4125
- const { uri } = request.params;
4126
- const sessionId = request.params._meta?.sessionId ?? sessionManager.getDefaultSessionId();
4127
- const { session } = sessionManager.getSession(sessionId);
4128
- ensureSubscribed(sessionId, session);
4129
- switch (uri) {
4130
- case "vsl://current":
4131
- try {
4132
- const snapshot = session.getSnapshot();
4133
- return {
4134
- contents: [
4135
- {
4136
- uri,
4137
- mimeType: "application/json",
4138
- text: JSON.stringify(snapshot, null, 2)
4139
- }
4140
- ]
4141
- };
4142
- } catch {
4143
- return {
4144
- contents: [
4145
- {
4146
- uri,
4147
- mimeType: "application/json",
4148
- text: JSON.stringify({
4149
- error: "No snapshot available. Call vsl_get_snapshot first."
4150
- })
4151
- }
4152
- ]
4153
- };
4154
- }
4155
- case "vsl://diff":
4156
- try {
4157
- const diff = session.getDiff();
4158
- if (!diff) {
4159
- return {
4160
- contents: [
4161
- {
4162
- uri,
4163
- mimeType: "application/json",
4164
- text: JSON.stringify({
4165
- error: "No diff available. This is the first snapshot or no changes detected."
4166
- })
4167
- }
4168
- ]
4169
- };
4170
- }
4171
- return {
4172
- contents: [
4173
- {
4174
- uri,
4175
- mimeType: "application/json",
4176
- text: JSON.stringify(diff, null, 2)
4177
- }
4178
- ]
4179
- };
4180
- } catch {
4181
- return {
4182
- contents: [
4183
- {
4184
- uri,
4185
- mimeType: "application/json",
4186
- text: JSON.stringify({
4187
- error: "Failed to compute diff."
4188
- })
4189
- }
4190
- ]
4191
- };
4192
- }
4193
- default:
4194
- throw new Error(`Unknown resource: ${uri}`);
4195
- }
4196
- });
4197
- const subscribedSessions = /* @__PURE__ */ new Set();
4198
- function ensureSubscribed(sessionId, session) {
4199
- if (subscribedSessions.has(sessionId)) return;
4200
- subscribedSessions.add(sessionId);
4201
- session.setOnSnapshotChange(() => {
4202
- server.sendResourceUpdated({ uri: "vsl://current" }).catch(() => {
4203
- });
4204
- if (session.getDiff()) {
4205
- server.sendResourceUpdated({ uri: "vsl://diff" }).catch(() => {
4206
- });
4207
- }
4208
- });
4209
- }
4210
- }
4211
-
4212
- // src/browser/manager.ts
4213
- import path from "path";
4214
- import os from "os";
4215
-
4216
- // src/browser/challengeResolver.ts
4217
- var ChallengeResolutionError = class extends Error {
4218
- constructor(url, timeoutMs) {
4219
- super(
4220
- `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).`
4221
- );
4222
- this.name = "ChallengeResolutionError";
4223
- }
4224
- };
4225
- var TITLE_MARKERS = [
4226
- /just a moment/i,
4227
- /attention required/i,
4228
- /checking your browser/i,
4229
- /verify you are human/i
4230
- ];
4231
- var PRIMARY_HTML_MARKERS = ["cf-chl", "challenges.cloudflare.com"];
4232
- var PRIMARY_URL_MARKERS = ["/cdn-cgi/challenge-platform", "challenges.cloudflare.com"];
4233
- function detectChallengeMarkers(input) {
4234
- const title = input.title ?? "";
4235
- const html = (input.html ?? "").toLowerCase();
4236
- const url = input.url ?? "";
4237
- const titleHit = TITLE_MARKERS.some((m) => m.test(title));
4238
- const htmlHit = PRIMARY_HTML_MARKERS.some((m) => html.includes(m));
4239
- const urlHit = PRIMARY_URL_MARKERS.some((m) => url.includes(m));
4240
- if (!titleHit && !htmlHit && !urlHit) {
4241
- return { isChallenge: false, kind: null };
4242
- }
4243
- const kind = html.includes("challenges.cloudflare.com") || html.includes("turnstile") ? "turnstile" : "cloudflare";
4244
- return { isChallenge: true, kind };
4245
- }
4246
- function pickCheckboxPoint(rect, rng = Math.random) {
4247
- const offsetX = Math.min(rect.width * 0.2, 24 + rng() * 8);
4248
- const offsetY = rect.height / 2 + (rng() - 0.5) * Math.min(6, rect.height * 0.2);
4249
- return { x: rect.x + offsetX, y: rect.y + offsetY };
4250
- }
4251
- async function inspectPage(page) {
4252
- const probe = await page.evaluate(() => {
4253
- let turnstileRect = null;
4254
- const iframes = Array.from(document.querySelectorAll("iframe"));
4255
- for (const frame of iframes) {
4256
- const src = frame.getAttribute("src") ?? "";
4257
- if (src.includes("challenges.cloudflare.com") || src.includes("challenge-platform") || src.includes("turnstile")) {
4258
- const rect = frame.getBoundingClientRect();
4259
- if (rect.width > 0 && rect.height > 0) {
4260
- turnstileRect = { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
4261
- break;
4262
- }
4263
- }
4264
- }
4265
- return {
4266
- title: document.title,
4267
- htmlSnippet: document.documentElement.innerHTML.slice(0, 3e4),
4268
- url: window.location.href,
4269
- turnstileRect,
4270
- viewportWidth: window.innerWidth,
4271
- viewportHeight: window.innerHeight
4272
- };
4273
- });
4274
- const detection = detectChallengeMarkers({
4275
- title: probe.title,
4276
- html: probe.htmlSnippet,
4277
- url: probe.url
4278
- });
4279
- return {
4280
- isChallenge: detection.isChallenge,
4281
- kind: detection.kind,
4282
- turnstileRect: probe.turnstileRect,
4283
- viewportWidth: probe.viewportWidth,
4284
- viewportHeight: probe.viewportHeight
4285
- };
4286
- }
4287
- async function humanLikeClick(page, inspection, rng) {
4288
- if (!inspection.turnstileRect) return;
4289
- const target = pickCheckboxPoint(inspection.turnstileRect, rng);
4290
- const start = {
4291
- x: inspection.viewportWidth * (0.3 + rng() * 0.4),
4292
- y: inspection.viewportHeight * (0.3 + rng() * 0.4)
4293
- };
4294
- await performHumanClick(page.mouse, start, target, { rng, waiter: page });
4295
- }
4296
- function safeOrigin(url) {
4297
- try {
4298
- return new URL(url).origin;
4299
- } catch {
4300
- return null;
4301
- }
4302
- }
4303
- async function resolveChallenge(page, targetUrl, options = {}) {
4304
- const timeoutMs = options.timeoutMs ?? 2e4;
4305
- const pollIntervalMs = options.pollIntervalMs ?? 2e3;
4306
- const enableClick = options.enableClick !== false;
4307
- const warmUp = options.warmUp !== false;
4308
- const rng = options.rng ?? Math.random;
4309
- let inspection = await inspectPage(page);
4310
- if (!inspection.isChallenge) {
4311
- return { status: "not_detected", attempts: 0 };
4312
- }
4313
- console.warn(
4314
- `[VSL MCP Server] Anti-bot challenge detected (${inspection.kind ?? "generic"}) at ${targetUrl} \u2014 resolving (timeout ${timeoutMs}ms)`
4315
- );
4316
- const deadline = Date.now() + timeoutMs;
4317
- let attempts = 0;
4318
- let warmedUp = false;
4319
- let clicked = false;
4320
- while (Date.now() < deadline) {
4321
- attempts++;
4322
- if (warmUp && !warmedUp) {
4323
- warmedUp = true;
4324
- const origin = safeOrigin(targetUrl);
4325
- if (origin && origin !== targetUrl) {
4326
- try {
4327
- await page.goto(origin, { timeout: timeoutMs, waitUntil: "domcontentloaded" });
4328
- await page.waitForTimeout(Math.round(pollIntervalMs / 2));
4329
- await page.goto(targetUrl, { timeout: timeoutMs, waitUntil: "domcontentloaded" });
4330
- } catch {
4331
- }
4332
- }
4333
- }
4334
- inspection = await inspectPage(page);
4335
- if (!inspection.isChallenge) {
4336
- return { status: clicked ? "clicked" : "auto", attempts };
4337
- }
4338
- if (enableClick && !clicked && inspection.turnstileRect) {
4339
- await humanLikeClick(page, inspection, rng);
4340
- clicked = true;
4136
+ if (enableClick && !clicked && inspection.turnstileRect) {
4137
+ await humanLikeClick(page, inspection, rng);
4138
+ clicked = true;
4341
4139
  }
4342
4140
  await page.waitForTimeout(pollIntervalMs);
4343
4141
  }
@@ -4350,6 +4148,18 @@ async function resolveChallenge(page, targetUrl, options = {}) {
4350
4148
  }
4351
4149
 
4352
4150
  // src/browser/manager.ts
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
+ };
4353
4163
  var BrowserManager = class {
4354
4164
  browser = null;
4355
4165
  context = null;
@@ -4358,6 +4168,8 @@ var BrowserManager = class {
4358
4168
  config;
4359
4169
  /** Флаг: браузер подключён через CDP (не закрывать при close()). */
4360
4170
  connectedViaCDP = false;
4171
+ /** Фактический режим окна: true — headless, false — headed, null — неизвестен (CDP). */
4172
+ currentHeadless = null;
4361
4173
  /** Активные загрузки: downloadId -> PlaywrightDownload. */
4362
4174
  activeDownloads = /* @__PURE__ */ new Map();
4363
4175
  constructor(config) {
@@ -4400,25 +4212,35 @@ var BrowserManager = class {
4400
4212
  /**
4401
4213
  * Запускает браузер (lazy, при первом вызове).
4402
4214
  * Логика для множественных агентов:
4403
- * 1. Если cdpPort задан → пробуем connectOverCDP (подключиться к уже запущенному браузеру)
4215
+ * 1. Если cdpPort задан и skipCdpConnect !== true → пробуем connectOverCDP
4404
4216
  * 2. Если connectOverCDP упал (браузер не запущен) → запускаем launchPersistentContext с --remote-debugging-port
4405
4217
  * 3. Если cdpPort НЕ задан → просто launchPersistentContext без CDP
4218
+ * @param options - headless переопределяет режим окна; skipCdpConnect пропускает CDP-connect (headed-перезапуск)
4406
4219
  * @throws Error если Playwright не установлен
4407
4220
  */
4408
- async launch() {
4409
- if (this.browser || this.context) return;
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
+ }
4410
4231
  const pw = await this.loadPlaywright();
4411
4232
  if (!pw) {
4412
4233
  throw new Error(
4413
4234
  "Playwright is not installed. Install it with: npm install playwright"
4414
4235
  );
4415
4236
  }
4416
- if (this.config.cdpPort) {
4237
+ if (this.config.cdpPort && options?.skipCdpConnect !== true) {
4417
4238
  try {
4418
4239
  this.browser = await pw.chromium.connectOverCDP({
4419
4240
  endpointURL: `http://localhost:${this.config.cdpPort}`
4420
4241
  });
4421
4242
  this.connectedViaCDP = true;
4243
+ this.currentHeadless = null;
4422
4244
  const contexts = this.browser.contexts();
4423
4245
  if (contexts.length > 0 && contexts[0]) {
4424
4246
  this.context = contexts[0];
@@ -4435,31 +4257,124 @@ var BrowserManager = class {
4435
4257
  } catch {
4436
4258
  }
4437
4259
  }
4438
- const userDataDir = this.config.userDataDir ?? path.join(os.homedir(), ".vsl", "browser-profile");
4260
+ const userDataDir = this.getProfileDir();
4261
+ const effectiveHeadless = options?.headless ?? this.config.headless;
4439
4262
  const persistentOptions = {
4440
- headless: this.config.headless,
4263
+ headless: effectiveHeadless,
4441
4264
  acceptDownloads: this.config.acceptDownloads ?? true
4442
4265
  };
4443
4266
  if (this.config.downloadsPath) {
4444
4267
  persistentOptions.downloadsPath = this.config.downloadsPath;
4445
4268
  }
4446
- if (this.config.proxy) {
4447
- persistentOptions.proxy = {
4448
- server: this.config.proxy.server,
4449
- ...this.config.proxy.username ? { username: this.config.proxy.username } : {},
4450
- ...this.config.proxy.password ? { password: this.config.proxy.password } : {}
4269
+ if (this.config.proxy) {
4270
+ persistentOptions.proxy = {
4271
+ server: this.config.proxy.server,
4272
+ ...this.config.proxy.username ? { username: this.config.proxy.username } : {},
4273
+ ...this.config.proxy.password ? { password: this.config.proxy.password } : {}
4274
+ };
4275
+ }
4276
+ const launchArgs = ["--disable-blink-features=AutomationControlled"];
4277
+ if (this.config.cdpPort) {
4278
+ launchArgs.push(`--remote-debugging-port=${this.config.cdpPort}`);
4279
+ }
4280
+ persistentOptions.args = launchArgs;
4281
+ const maxProfileAttempts = 3;
4282
+ for (let attempt = 1; ; attempt++) {
4283
+ try {
4284
+ this.context = await this.launchPersistentContextWithRecovery(
4285
+ pw,
4286
+ userDataDir,
4287
+ persistentOptions
4288
+ );
4289
+ break;
4290
+ } catch (error) {
4291
+ const message = error instanceof Error ? error.message : String(error);
4292
+ if (!/processsingleton/i.test(message)) throw error;
4293
+ if (attempt >= maxProfileAttempts) {
4294
+ throw new Error(
4295
+ `Browser profile ${userDataDir} is locked by another browser process. Close it (or stop the other VSL MCP server) and retry vsl_manual_login.`
4296
+ );
4297
+ }
4298
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
4299
+ }
4300
+ }
4301
+ this.currentHeadless = effectiveHeadless;
4302
+ this.browser = null;
4303
+ }
4304
+ /**
4305
+ * Запускает persistent context с восстановлением отсутствующего бинарника браузера.
4306
+ *
4307
+ * Playwright сам решает, какой артефакт использовать (chromium или chromium-headless-shell
4308
+ * для headless), поэтому наличие бинарника не проверяется заранее по угаданному пути:
4309
+ * авторитетный путь берётся из ошибки Playwright, затем браузер скачивается и запуск
4310
+ * повторяется ровно один раз.
4311
+ *
4312
+ * @throws Error с короткой инструкцией, если восстановление отключено или не помогло
4313
+ */
4314
+ async launchPersistentContextWithRecovery(pw, userDataDir, options) {
4315
+ try {
4316
+ return await pw.chromium.launchPersistentContext(userDataDir, options);
4317
+ } catch (error) {
4318
+ const missing = parseMissingBrowserError(error);
4319
+ if (!missing) throw error;
4320
+ await this.ensureBrowserBinary(missing);
4321
+ try {
4322
+ return await pw.chromium.launchPersistentContext(userDataDir, options);
4323
+ } catch (retryError) {
4324
+ const stillMissing = parseMissingBrowserError(retryError);
4325
+ if (!stillMissing) throw retryError;
4326
+ throw new Error(
4327
+ formatMissingBrowserError(stillMissing, {
4328
+ cliPath: resolvePlaywrightCliPath(),
4329
+ reason: "the binary is still missing after a successful download"
4330
+ })
4331
+ );
4332
+ }
4333
+ }
4334
+ }
4335
+ /**
4336
+ * Гарантирует наличие бинарника браузера: скачивает его (self-heal) либо бросает
4337
+ * actionable ошибку, если автоустановка отключена конфигурацией или не удалась.
4338
+ */
4339
+ async ensureBrowserBinary(missing) {
4340
+ const cliPath = resolvePlaywrightCliPath();
4341
+ if (this.config.autoInstallBrowser === false) {
4342
+ throw new Error(
4343
+ formatMissingBrowserError(missing, { cliPath, autoInstallDisabled: true })
4344
+ );
4345
+ }
4346
+ console.error(
4347
+ `[VSL MCP Server] Playwright browser binary is missing (${missing.revisionDir}) \u2014 downloading "${missing.browser}" automatically...`
4348
+ );
4349
+ const result = await this.installBrowserBinary(missing);
4350
+ if (!result.success) {
4351
+ throw new Error(
4352
+ formatMissingBrowserError(missing, {
4353
+ cliPath,
4354
+ reason: result.error ?? "unknown install error"
4355
+ })
4356
+ );
4357
+ }
4358
+ console.error(`[VSL MCP Server] Browser "${missing.browser}" is ready (self-heal completed).`);
4359
+ }
4360
+ /**
4361
+ * Шов для автоматической загрузки браузера (self-heal).
4362
+ * Юнит-тесты переопределяют его через jest.spyOn, чтобы не скачивать браузеры реально.
4363
+ */
4364
+ async installBrowserBinary(info) {
4365
+ const cliPath = resolvePlaywrightCliPath();
4366
+ if (!cliPath) {
4367
+ return {
4368
+ success: false,
4369
+ output: "",
4370
+ error: "playwright cli.js not found next to the installed playwright package"
4451
4371
  };
4452
4372
  }
4453
- const launchArgs = ["--disable-blink-features=AutomationControlled"];
4454
- if (this.config.cdpPort) {
4455
- launchArgs.push(`--remote-debugging-port=${this.config.cdpPort}`);
4456
- }
4457
- persistentOptions.args = launchArgs;
4458
- this.context = await pw.chromium.launchPersistentContext(
4459
- userDataDir,
4460
- persistentOptions
4461
- );
4462
- this.browser = null;
4373
+ return installBrowser({
4374
+ browser: info.browser,
4375
+ cliPath,
4376
+ timeoutMs: this.config.browserInstallTimeout ?? DEFAULT_BROWSER_INSTALL_TIMEOUT_MS
4377
+ });
4463
4378
  }
4464
4379
  /**
4465
4380
  * Возвращает страницу для указанной сессии (создаёт новую из context, если нет).
@@ -4484,6 +4399,125 @@ var BrowserManager = class {
4484
4399
  }
4485
4400
  return page;
4486
4401
  }
4402
+ /**
4403
+ * Возвращает путь persistent-профиля браузера (R5).
4404
+ * Единая точка вычисления пути: второй профиль нигде не создаётся.
4405
+ */
4406
+ getProfileDir() {
4407
+ return this.config.userDataDir ?? path2.join(os.homedir(), ".vsl", "browser-profile");
4408
+ }
4409
+ /**
4410
+ * Возвращает фактический режим окна браузера (R6).
4411
+ * not_launched — контекста нет; cdp — внешний браузер; headed/headless — свой контекст.
4412
+ */
4413
+ getBrowserMode() {
4414
+ if (!this.context) return "not_launched";
4415
+ if (this.connectedViaCDP) return "cdp";
4416
+ if (this.currentHeadless === false) return "headed";
4417
+ return "headless";
4418
+ }
4419
+ /**
4420
+ * Возвращает User-Agent браузера (R27).
4421
+ * @param sessionId - ID сессии
4422
+ */
4423
+ async getBrowserUserAgent(sessionId) {
4424
+ const page = await this.getPage(sessionId);
4425
+ return await page.evaluate(() => navigator.userAgent);
4426
+ }
4427
+ /**
4428
+ * Приводит браузер к ВИДИМОМУ окну на том же профиле (R7).
4429
+ * Свой headless-контекст перезапускается, внешний видимый Chrome не трогается,
4430
+ * headless-браузер VSL по CDP закрывается только при явном takeover:true.
4431
+ * @param sessionId - ID сессии
4432
+ * @param options - takeover: закрыть чужой headless-браузер VSL и переоткрыть видимым
4433
+ */
4434
+ async ensureHeaded(sessionId, options) {
4435
+ if (!this.context) {
4436
+ await this.launch({ headless: false, skipCdpConnect: true });
4437
+ return { restarted: true, mode: "headed" };
4438
+ }
4439
+ if (this.connectedViaCDP) {
4440
+ const ua = await this.getBrowserUserAgent(sessionId);
4441
+ if (!isHeadlessUserAgent(ua)) {
4442
+ return { restarted: false, mode: "cdp" };
4443
+ }
4444
+ if (options?.takeover !== true) {
4445
+ throw new HeadlessCdpBrowserError(this.config.cdpPort);
4446
+ }
4447
+ await this.closeCdpBrowser(sessionId);
4448
+ await this.close();
4449
+ await this.launch({ headless: false, skipCdpConnect: true });
4450
+ return { restarted: true, mode: "headed" };
4451
+ }
4452
+ if (this.currentHeadless === false) {
4453
+ return { restarted: false, mode: "headed" };
4454
+ }
4455
+ await this.close();
4456
+ await this.launch({ headless: false, skipCdpConnect: true });
4457
+ return { restarted: true, mode: "headed" };
4458
+ }
4459
+ /**
4460
+ * Закрывает headless-браузер VSL, подключённый по CDP, командой Browser.close (R29).
4461
+ * Обрыв соединения после закрытия — ожидаемый исход, ошибка только логируется.
4462
+ * @param sessionId - ID сессии
4463
+ */
4464
+ async closeCdpBrowser(sessionId) {
4465
+ const page = await this.getPage(sessionId);
4466
+ if (!this.context) {
4467
+ throw new Error("Browser not available");
4468
+ }
4469
+ const cdp = await this.context.newCDPSession(page);
4470
+ try {
4471
+ await cdp.send("Browser.close");
4472
+ } catch (error) {
4473
+ console.error(
4474
+ "[BrowserManager] CDP Browser.close ended with a connection error (expected):",
4475
+ error instanceof Error ? error.message : String(error)
4476
+ );
4477
+ } finally {
4478
+ try {
4479
+ await cdp.detach();
4480
+ } catch (error) {
4481
+ console.error(
4482
+ "[BrowserManager] CDP session detach failed:",
4483
+ error instanceof Error ? error.message : String(error)
4484
+ );
4485
+ }
4486
+ }
4487
+ }
4488
+ /**
4489
+ * Возвращает браузер в headless-режим на том же профиле (R8).
4490
+ * При CDP и при уже headless-режиме — no-op.
4491
+ */
4492
+ async restoreHeadless() {
4493
+ if (this.connectedViaCDP) return { restarted: false };
4494
+ if (this.currentHeadless === true) return { restarted: false };
4495
+ await this.close();
4496
+ await this.launch({ headless: true, skipCdpConnect: true });
4497
+ return { restarted: true };
4498
+ }
4499
+ /**
4500
+ * Выводит окно страницы на передний план (R8).
4501
+ * @param sessionId - ID сессии
4502
+ */
4503
+ async bringToFront(sessionId) {
4504
+ const page = await this.getPage(sessionId);
4505
+ await page.bringToFront();
4506
+ }
4507
+ /**
4508
+ * Возвращает КОЛИЧЕСТВО cookies профиля (R8).
4509
+ * Значения и имена cookies не читаются и не логируются.
4510
+ */
4511
+ async getCookieCount() {
4512
+ if (!this.context) {
4513
+ await this.launch();
4514
+ }
4515
+ if (!this.context) {
4516
+ throw new Error("Browser not available");
4517
+ }
4518
+ const cookies = await this.context.cookies();
4519
+ return cookies.length;
4520
+ }
4487
4521
  /**
4488
4522
  * Переходит по URL.
4489
4523
  * @param url - URL для навигации
@@ -4588,160 +4622,756 @@ var BrowserManager = class {
4588
4622
  const failure = await download.failure();
4589
4623
  if (failure) {
4590
4624
  return {
4591
- downloadId,
4592
- filename: download.suggestedFilename(),
4593
- url: download.url(),
4594
- status: "failed",
4595
- path: null
4625
+ downloadId,
4626
+ filename: download.suggestedFilename(),
4627
+ url: download.url(),
4628
+ status: "failed",
4629
+ path: null
4630
+ };
4631
+ }
4632
+ const path3 = await download.path();
4633
+ return {
4634
+ downloadId,
4635
+ filename: download.suggestedFilename(),
4636
+ url: download.url(),
4637
+ status: "completed",
4638
+ path: path3
4639
+ };
4640
+ } catch {
4641
+ return {
4642
+ downloadId,
4643
+ filename: download.suggestedFilename(),
4644
+ url: download.url(),
4645
+ status: "failed",
4646
+ path: null
4647
+ };
4648
+ }
4649
+ }
4650
+ /**
4651
+ * Возвращает список активных загрузок.
4652
+ */
4653
+ getDownloads() {
4654
+ return Array.from(this.activeDownloads.entries()).map(([downloadId, download]) => ({
4655
+ downloadId,
4656
+ filename: download.suggestedFilename(),
4657
+ url: download.url()
4658
+ }));
4659
+ }
4660
+ /**
4661
+ * Сохраняет загрузку в указанный путь.
4662
+ * @param downloadId - ID загрузки
4663
+ * @param savePath - Путь для сохранения
4664
+ */
4665
+ async saveDownload(downloadId, savePath) {
4666
+ const download = this.activeDownloads.get(downloadId);
4667
+ if (!download) {
4668
+ throw new Error(`Download not found: ${downloadId}`);
4669
+ }
4670
+ const isAbsolute = savePath.startsWith("/");
4671
+ if (isAbsolute) {
4672
+ await download.saveAs(savePath);
4673
+ } else {
4674
+ const downloadsPath = this.config.downloadsPath ?? os.tmpdir();
4675
+ const resolvedBase = path2.resolve(downloadsPath.replace(/^~/, os.homedir()));
4676
+ const resolvedSave = path2.resolve(resolvedBase, savePath);
4677
+ if (!resolvedSave.startsWith(resolvedBase + path2.sep) && resolvedSave !== resolvedBase) {
4678
+ throw new Error(`Path traversal detected: save_path '${savePath}' escapes downloads directory '${resolvedBase}'`);
4679
+ }
4680
+ await download.saveAs(resolvedSave);
4681
+ }
4682
+ }
4683
+ /**
4684
+ * Отменяет загрузку.
4685
+ * @param downloadId - ID загрузки
4686
+ */
4687
+ async cancelDownload(downloadId) {
4688
+ const download = this.activeDownloads.get(downloadId);
4689
+ if (!download) {
4690
+ throw new Error(`Download not found: ${downloadId}`);
4691
+ }
4692
+ await download.cancel();
4693
+ this.activeDownloads.delete(downloadId);
4694
+ }
4695
+ /**
4696
+ * Очищает завершённые загрузки из activeDownloads.
4697
+ */
4698
+ clearDownloads() {
4699
+ this.activeDownloads.clear();
4700
+ }
4701
+ /**
4702
+ * Загружает файлы в <input type="file"> по CSS-селектору.
4703
+ * Использует Playwright page.setInputFiles().
4704
+ * Валидирует пути: абсолютные используются напрямую, относительные разрешаются
4705
+ * относительно CWD с path traversal проверкой.
4706
+ * @param selector - CSS-селектор input[type=file] элемента
4707
+ * @param filePaths - Массив путей к файлам (абсолютные или относительные)
4708
+ * @param sessionId - ID сессии
4709
+ * @throws Error если путь выходит за допустимые границы или файл не существует
4710
+ */
4711
+ async uploadFile(selector, filePaths, sessionId) {
4712
+ const page = await this.getPage(sessionId);
4713
+ if (filePaths.length === 0) {
4714
+ throw new Error("filePaths must contain at least one file path");
4715
+ }
4716
+ const resolvedPaths = [];
4717
+ for (const filePath of filePaths) {
4718
+ const isAbsolute = path2.isAbsolute(filePath);
4719
+ if (isAbsolute) {
4720
+ resolvedPaths.push(filePath);
4721
+ } else {
4722
+ const resolved = path2.resolve(process.cwd(), filePath);
4723
+ const cwd = path2.resolve(process.cwd());
4724
+ if (!resolved.startsWith(cwd + path2.sep) && resolved !== cwd) {
4725
+ throw new Error(`Path traversal detected: file path '${filePath}' resolves outside working directory '${cwd}'`);
4726
+ }
4727
+ resolvedPaths.push(resolved);
4728
+ }
4729
+ }
4730
+ await page.setInputFiles(selector, resolvedPaths.length === 1 ? resolvedPaths[0] : resolvedPaths);
4731
+ }
4732
+ /**
4733
+ * Ожидает появления file chooser dialog (для кастомных file picker'ов).
4734
+ * Возвращает FileChooser, через который можно установить файлы.
4735
+ * @param sessionId - ID сессии
4736
+ * @param timeout - Таймаут ожидания в мс (по умолчанию из config.downloadTimeout)
4737
+ * @returns PlaywrightFileChooser для установки файлов
4738
+ */
4739
+ async waitForFileChooser(sessionId, timeout) {
4740
+ const page = await this.getPage(sessionId);
4741
+ const waitTimeout = timeout ?? this.config.downloadTimeout ?? 6e4;
4742
+ const fileChooser = await page.waitForEvent("filechooser", { timeout: waitTimeout });
4743
+ return fileChooser;
4744
+ }
4745
+ /**
4746
+ * Закрывает браузер и очищает ресурсы.
4747
+ * Если браузер подключён через CDP — закрывает только context,
4748
+ * сам браузер не закрывается (сохраняет сессию пользователя).
4749
+ */
4750
+ async close() {
4751
+ this.activeDownloads.clear();
4752
+ for (const page of this.pages.values()) {
4753
+ try {
4754
+ await page.close();
4755
+ } catch (error) {
4756
+ console.error("[BrowserManager] Error closing page:", error);
4757
+ }
4758
+ }
4759
+ this.pages.clear();
4760
+ try {
4761
+ if (this.context) {
4762
+ await this.context.close();
4763
+ this.context = null;
4764
+ }
4765
+ if (this.browser && !this.connectedViaCDP) {
4766
+ await this.browser.close();
4767
+ this.browser = null;
4768
+ } else if (this.connectedViaCDP) {
4769
+ this.browser = null;
4770
+ }
4771
+ } catch (error) {
4772
+ console.error("[BrowserManager] Error during close():", error);
4773
+ this.context = null;
4774
+ this.browser = null;
4775
+ }
4776
+ this.connectedViaCDP = false;
4777
+ }
4778
+ };
4779
+
4780
+ // src/tools/manualLogin.ts
4781
+ var DEFAULT_TIMEOUT_MS = 18e4;
4782
+ var DEFAULT_POLL_INTERVAL_MS = 2e3;
4783
+ var MIN_TIMEOUT_MS = 1e3;
4784
+ var MAX_TIMEOUT_MS = 6e5;
4785
+ var loginState = /* @__PURE__ */ new Map();
4786
+ function sanitizeUrl(url) {
4787
+ try {
4788
+ const parsed = new URL(url);
4789
+ return parsed.origin + parsed.pathname;
4790
+ } catch {
4791
+ return "";
4792
+ }
4793
+ }
4794
+ function resolveTimeoutMs(value) {
4795
+ if (value === void 0 || !Number.isFinite(value)) return DEFAULT_TIMEOUT_MS;
4796
+ return Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, Math.trunc(value)));
4797
+ }
4798
+ function sleep(ms) {
4799
+ return new Promise((resolve) => setTimeout(resolve, ms));
4800
+ }
4801
+ async function computeMatched(browser, sessionId, successSelector, successUrlPattern) {
4802
+ if (!successSelector && !successUrlPattern) return false;
4803
+ if (successSelector) {
4804
+ const found = await browser.evaluate(
4805
+ (sel) => document.querySelector(sel) !== null,
4806
+ sessionId,
4807
+ successSelector
4808
+ );
4809
+ if (found === true) return true;
4810
+ }
4811
+ if (successUrlPattern) {
4812
+ const href = await browser.evaluate(() => window.location.href, sessionId);
4813
+ if (typeof href === "string" && href.includes(successUrlPattern)) return true;
4814
+ }
4815
+ return false;
4816
+ }
4817
+ async function waitForLogin(browser, sessionId, args, deadlineAt, pollIntervalMs) {
4818
+ for (; ; ) {
4819
+ const matched = await computeMatched(browser, sessionId, args.success_selector, args.success_url_pattern);
4820
+ if (matched) return true;
4821
+ const remaining = deadlineAt - Date.now();
4822
+ if (remaining <= 0) return false;
4823
+ await sleep(Math.min(pollIntervalMs, remaining));
4824
+ }
4825
+ }
4826
+ async function handleManualLogin(args, browser, _session, sessionManager, config, sessionId) {
4827
+ const startTime = Date.now();
4828
+ const action = args.action ?? "open";
4829
+ try {
4830
+ if (action === "open") {
4831
+ if (!args.url || typeof args.url !== "string") {
4832
+ return { status: "error", error: "URL is required" };
4833
+ }
4834
+ let parsed;
4835
+ try {
4836
+ parsed = new URL(args.url);
4837
+ } catch {
4838
+ return { status: "error", error: `Invalid URL: ${args.url}` };
4839
+ }
4840
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
4841
+ return { status: "error", error: "Only http and https URLs are supported" };
4842
+ }
4843
+ const isAvailable = await browser.isAvailable();
4844
+ if (!isAvailable) {
4845
+ return {
4846
+ status: "error",
4847
+ error: "Playwright is not installed. Install it with: npm install playwright"
4848
+ };
4849
+ }
4850
+ const { restarted, mode } = await browser.ensureHeaded(sessionId, { takeover: args.takeover === true });
4851
+ let challengeWarning;
4852
+ try {
4853
+ await browser.navigate(args.url, sessionId);
4854
+ } catch (error) {
4855
+ if (!(error instanceof ChallengeResolutionError)) throw error;
4856
+ challengeWarning = 'Visible window is open \u2014 log in manually (captcha/2FA), then call vsl_manual_login with {action:"status"} and {action:"finish"}.';
4857
+ console.error("[vsl_manual_login] anti-bot challenge on", sanitizeUrl(args.url));
4858
+ }
4859
+ await browser.bringToFront(sessionId);
4860
+ sessionManager.clearAllSessionCaches();
4861
+ const timeoutMs = resolveTimeoutMs(args.timeout_ms ?? config.browser.manualLogin?.timeoutMs);
4862
+ const pollIntervalMs = config.browser.manualLogin?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
4863
+ const deadlineAt = Date.now() + timeoutMs;
4864
+ loginState.set(sessionId, { loginUrl: args.url, deadlineAt });
4865
+ const loginUrl = sanitizeUrl(args.url);
4866
+ const data = {
4867
+ action: "open",
4868
+ browser_mode: mode,
4869
+ profile_dir: browser.getProfileDir(),
4870
+ restarted,
4871
+ login_url: loginUrl,
4872
+ current_url: loginUrl,
4873
+ cookie_count: await browser.getCookieCount(),
4874
+ matched: false,
4875
+ waiting: true,
4876
+ deadline_at: new Date(deadlineAt).toISOString(),
4877
+ 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.`
4878
+ };
4879
+ let warning = challengeWarning;
4880
+ if (args.wait === true) {
4881
+ const matched = await waitForLogin(browser, sessionId, args, deadlineAt, pollIntervalMs);
4882
+ data.matched = matched;
4883
+ data.waiting = !matched;
4884
+ if (!matched) {
4885
+ warning = `Manual login was not confirmed within ${timeoutMs}ms. The window stays open \u2014 call vsl_manual_login with {action:"status"} later.`;
4886
+ }
4887
+ }
4888
+ const result = {
4889
+ status: "success",
4890
+ data,
4891
+ metadata: computeToolMetrics(data, startTime)
4892
+ };
4893
+ if (warning) result.warning = warning;
4894
+ return result;
4895
+ }
4896
+ if (action === "status") {
4897
+ const mode = browser.getBrowserMode();
4898
+ if (mode === "not_launched") {
4899
+ return {
4900
+ status: "error",
4901
+ error: 'Browser is not launched. Call vsl_manual_login with {action:"open", url:"..."} first.'
4596
4902
  };
4597
4903
  }
4598
- const path2 = await download.path();
4599
- return {
4600
- downloadId,
4601
- filename: download.suggestedFilename(),
4602
- url: download.url(),
4603
- status: "completed",
4604
- path: path2
4904
+ const href = await browser.evaluate(() => window.location.href, sessionId);
4905
+ const state = loginState.get(sessionId);
4906
+ const data = {
4907
+ action: "status",
4908
+ browser_mode: mode,
4909
+ profile_dir: browser.getProfileDir(),
4910
+ restarted: false,
4911
+ current_url: sanitizeUrl(typeof href === "string" ? href : ""),
4912
+ cookie_count: await browser.getCookieCount(),
4913
+ matched: await computeMatched(browser, sessionId, args.success_selector, args.success_url_pattern),
4914
+ waiting: state !== void 0 && state.deadlineAt > Date.now()
4605
4915
  };
4606
- } catch {
4607
- return {
4608
- downloadId,
4609
- filename: download.suggestedFilename(),
4610
- url: download.url(),
4611
- status: "failed",
4612
- path: null
4916
+ return { status: "success", data, metadata: computeToolMetrics(data, startTime) };
4917
+ }
4918
+ if (action === "finish") {
4919
+ const href = await browser.evaluate(() => window.location.href, sessionId);
4920
+ const currentUrl = sanitizeUrl(typeof href === "string" ? href : "");
4921
+ const cookieCount = await browser.getCookieCount();
4922
+ const matched = await computeMatched(browser, sessionId, args.success_selector, args.success_url_pattern);
4923
+ const restore = args.restore_headless ?? config.browser.manualLogin?.restoreHeadless ?? false;
4924
+ let restarted = false;
4925
+ let browserMode;
4926
+ if (restore) {
4927
+ const restored = await browser.restoreHeadless();
4928
+ restarted = restored.restarted;
4929
+ browserMode = "headless";
4930
+ } else {
4931
+ const mode = browser.getBrowserMode();
4932
+ browserMode = mode === "not_launched" ? "headless" : mode;
4933
+ }
4934
+ sessionManager.clearAllSessionCaches();
4935
+ loginState.delete(sessionId);
4936
+ const data = {
4937
+ action: "finish",
4938
+ browser_mode: browserMode,
4939
+ profile_dir: browser.getProfileDir(),
4940
+ restarted,
4941
+ current_url: currentUrl,
4942
+ cookie_count: cookieCount,
4943
+ matched,
4944
+ waiting: false,
4945
+ 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."
4613
4946
  };
4947
+ const result = {
4948
+ status: "success",
4949
+ data,
4950
+ metadata: computeToolMetrics(data, startTime)
4951
+ };
4952
+ if (restore) {
4953
+ result.warning = "Headless restart closes the login tab: sessionStorage and session-only cookies may be lost.";
4954
+ }
4955
+ return result;
4614
4956
  }
4615
- }
4616
- /**
4617
- * Возвращает список активных загрузок.
4618
- */
4619
- getDownloads() {
4620
- return Array.from(this.activeDownloads.entries()).map(([downloadId, download]) => ({
4621
- downloadId,
4622
- filename: download.suggestedFilename(),
4623
- url: download.url()
4624
- }));
4625
- }
4626
- /**
4627
- * Сохраняет загрузку в указанный путь.
4628
- * @param downloadId - ID загрузки
4629
- * @param savePath - Путь для сохранения
4630
- */
4631
- async saveDownload(downloadId, savePath) {
4632
- const download = this.activeDownloads.get(downloadId);
4633
- if (!download) {
4634
- throw new Error(`Download not found: ${downloadId}`);
4957
+ return { status: "error", error: `Unknown action: ${String(action)}` };
4958
+ } catch (error) {
4959
+ if (error instanceof HeadlessCdpBrowserError) {
4960
+ return { status: "error", error: error.message };
4635
4961
  }
4636
- const isAbsolute = savePath.startsWith("/");
4637
- if (isAbsolute) {
4638
- await download.saveAs(savePath);
4639
- } else {
4640
- const downloadsPath = this.config.downloadsPath ?? os.tmpdir();
4641
- const resolvedBase = path.resolve(downloadsPath.replace(/^~/, os.homedir()));
4642
- const resolvedSave = path.resolve(resolvedBase, savePath);
4643
- if (!resolvedSave.startsWith(resolvedBase + path.sep) && resolvedSave !== resolvedBase) {
4644
- throw new Error(`Path traversal detected: save_path '${savePath}' escapes downloads directory '${resolvedBase}'`);
4962
+ console.error(
4963
+ "[vsl_manual_login] failed:",
4964
+ error instanceof Error ? error.name : "Error",
4965
+ sanitizeUrl(typeof args.url === "string" ? args.url : "")
4966
+ );
4967
+ return {
4968
+ status: "error",
4969
+ error: `vsl_manual_login failed: ${error instanceof Error ? error.message : String(error)}`
4970
+ };
4971
+ }
4972
+ }
4973
+
4974
+ // src/tools/index.ts
4975
+ var VSL_TOOLS = [
4976
+ {
4977
+ name: "vsl_get_snapshot",
4978
+ 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.",
4979
+ inputSchema: {
4980
+ type: "object",
4981
+ properties: {
4982
+ url: {
4983
+ type: "string",
4984
+ description: "Page URL (optional, if not specified \u2014 uses the current page)"
4985
+ },
4986
+ detail_level: {
4987
+ type: "string",
4988
+ enum: ["low", "medium", "high"],
4989
+ description: "Snapshot detail level. 'low': interactive elements only (buttons, links, inputs). 'medium': interactive + containers (default). 'high': all objects (full DOM). Default: 'medium'."
4990
+ },
4991
+ ttl: {
4992
+ type: "number",
4993
+ description: "Cache TTL in milliseconds (default: 5000 = 5s). Set to 0 to disable caching."
4994
+ },
4995
+ full: {
4996
+ type: "boolean",
4997
+ description: "Full mode: returns the entire document without filters (replacement for the removed full snapshot tool)"
4998
+ }
4645
4999
  }
4646
- await download.saveAs(resolvedSave);
4647
5000
  }
4648
- }
4649
- /**
4650
- * Отменяет загрузку.
4651
- * @param downloadId - ID загрузки
4652
- */
4653
- async cancelDownload(downloadId) {
4654
- const download = this.activeDownloads.get(downloadId);
4655
- if (!download) {
4656
- throw new Error(`Download not found: ${downloadId}`);
5001
+ },
5002
+ {
5003
+ name: "vsl_execute_action",
5004
+ 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.',
5005
+ inputSchema: {
5006
+ type: "object",
5007
+ properties: {
5008
+ action: {
5009
+ type: "string",
5010
+ description: "Action name (click, type, fill, scroll, select, etc.)"
5011
+ },
5012
+ target_id: {
5013
+ type: "string",
5014
+ description: "Target element ID in VSL JSON"
5015
+ },
5016
+ value: {
5017
+ type: "string",
5018
+ description: "Value for the action (e.g. text for type/fill, option for select)"
5019
+ },
5020
+ return_state: {
5021
+ type: "boolean",
5022
+ description: "If true, returns diff and snapshot after the action. Useful for tracking DOM changes without an additional vsl_get_diff call. Default: true \u2014 always return state to save agent steps. Set to false to disable."
5023
+ },
5024
+ timeout: {
5025
+ type: "number",
5026
+ description: "Download completion timeout in ms (only for download action)"
5027
+ },
5028
+ save_path: {
5029
+ type: "string",
5030
+ description: "Path to save the downloaded file (only for download action)"
5031
+ }
5032
+ },
5033
+ required: ["action", "target_id"]
4657
5034
  }
4658
- await download.cancel();
4659
- this.activeDownloads.delete(downloadId);
4660
- }
4661
- /**
4662
- * Очищает завершённые загрузки из activeDownloads.
4663
- */
4664
- clearDownloads() {
4665
- this.activeDownloads.clear();
4666
- }
4667
- /**
4668
- * Загружает файлы в <input type="file"> по CSS-селектору.
4669
- * Использует Playwright page.setInputFiles().
4670
- * Валидирует пути: абсолютные используются напрямую, относительные разрешаются
4671
- * относительно CWD с path traversal проверкой.
4672
- * @param selector - CSS-селектор input[type=file] элемента
4673
- * @param filePaths - Массив путей к файлам (абсолютные или относительные)
4674
- * @param sessionId - ID сессии
4675
- * @throws Error если путь выходит за допустимые границы или файл не существует
4676
- */
4677
- async uploadFile(selector, filePaths, sessionId) {
4678
- const page = await this.getPage(sessionId);
4679
- if (filePaths.length === 0) {
4680
- throw new Error("filePaths must contain at least one file path");
5035
+ },
5036
+ {
5037
+ name: "vsl_navigate",
5038
+ 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.',
5039
+ inputSchema: {
5040
+ type: "object",
5041
+ properties: {
5042
+ url: {
5043
+ type: "string",
5044
+ description: "URL to navigate to"
5045
+ }
5046
+ },
5047
+ required: ["url"]
4681
5048
  }
4682
- const resolvedPaths = [];
4683
- for (const filePath of filePaths) {
4684
- const isAbsolute = path.isAbsolute(filePath);
4685
- if (isAbsolute) {
4686
- resolvedPaths.push(filePath);
4687
- } else {
4688
- const resolved = path.resolve(process.cwd(), filePath);
4689
- const cwd = path.resolve(process.cwd());
4690
- if (!resolved.startsWith(cwd + path.sep) && resolved !== cwd) {
4691
- throw new Error(`Path traversal detected: file path '${filePath}' resolves outside working directory '${cwd}'`);
5049
+ },
5050
+ {
5051
+ name: "vsl_clear_cache",
5052
+ 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.",
5053
+ inputSchema: {
5054
+ type: "object",
5055
+ properties: {}
5056
+ }
5057
+ },
5058
+ {
5059
+ name: "vsl_get_visual",
5060
+ 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.",
5061
+ inputSchema: {
5062
+ type: "object",
5063
+ properties: {
5064
+ element_id: {
5065
+ type: "string",
5066
+ description: "Element ID in VSL JSON"
5067
+ },
5068
+ auto_refresh: {
5069
+ type: "boolean",
5070
+ description: "If true, automatically refreshes the snapshot before searching for the element. Useful after navigation or actions that modify the DOM. Default: false."
5071
+ }
5072
+ },
5073
+ required: ["element_id"]
5074
+ }
5075
+ },
5076
+ {
5077
+ name: "vsl_read_page",
5078
+ 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.',
5079
+ inputSchema: {
5080
+ type: "object",
5081
+ properties: {
5082
+ url: {
5083
+ type: "string",
5084
+ description: "Page URL to read"
5085
+ },
5086
+ readable: {
5087
+ type: "boolean",
5088
+ description: "Readable mode: filter noise (nav, footer, cookie banners) for clean content"
5089
+ }
5090
+ },
5091
+ required: ["url"]
5092
+ }
5093
+ },
5094
+ {
5095
+ name: "vsl_get_text_block",
5096
+ 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.`,
5097
+ inputSchema: {
5098
+ type: "object",
5099
+ properties: {
5100
+ block_id: {
5101
+ type: "string",
5102
+ description: "Text block ID from the txt_ref field of a VSL object (format: tb_xxx)"
5103
+ }
5104
+ },
5105
+ required: ["block_id"]
5106
+ }
5107
+ },
5108
+ {
5109
+ name: "vsl_click_coordinates",
5110
+ 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}]}.',
5111
+ inputSchema: {
5112
+ type: "object",
5113
+ properties: {
5114
+ target_id: {
5115
+ type: "string",
5116
+ description: "Element ID in VSL JSON (e.g. iframe_2 for reCAPTCHA challenge iframe)"
5117
+ },
5118
+ clicks: {
5119
+ type: "array",
5120
+ 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.",
5121
+ items: {
5122
+ type: "object",
5123
+ properties: {
5124
+ x: { type: "number", description: "X coordinate (pixels from left edge of element)" },
5125
+ y: { type: "number", description: "Y coordinate (pixels from top edge of element)" },
5126
+ delay_after_ms: { type: "number", description: "Delay after click (ms)" }
5127
+ },
5128
+ required: ["x", "y"]
5129
+ }
5130
+ },
5131
+ return_state: {
5132
+ type: "boolean",
5133
+ description: "If true (default), returns diff + snapshot + screenshot after all clicks."
5134
+ }
5135
+ },
5136
+ required: ["target_id", "clicks"]
5137
+ }
5138
+ },
5139
+ {
5140
+ name: "vsl_manual_login",
5141
+ 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"}.',
5142
+ inputSchema: {
5143
+ type: "object",
5144
+ properties: {
5145
+ action: {
5146
+ type: "string",
5147
+ enum: ["open", "status", "finish"],
5148
+ 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."
5149
+ },
5150
+ url: {
5151
+ type: "string",
5152
+ description: "Login page URL (required for action=open, http/https only). Returned to the user without query and hash."
5153
+ },
5154
+ wait: {
5155
+ type: "boolean",
5156
+ description: "Only for open: block until the sign-in signal is found or the timeout expires (default false \u2014 non-blocking)."
5157
+ },
5158
+ timeout_ms: {
5159
+ type: "number",
5160
+ description: "Manual login timeout in ms (default 180000 from browser.manualLogin.timeoutMs, clamped to 1000..600000)."
5161
+ },
5162
+ success_selector: {
5163
+ type: "string",
5164
+ description: "CSS selector that proves the user is signed in (e.g. [data-testid=avatar]). No cookie or storage values are read."
5165
+ },
5166
+ success_url_pattern: {
5167
+ type: "string",
5168
+ description: "Substring of the page URL that proves the user is signed in (e.g. /dashboard)."
5169
+ },
5170
+ restore_headless: {
5171
+ type: "boolean",
5172
+ description: "Only for finish: return the browser to headless (default false \u2014 the visible window stays alive, so sessionStorage and session-only cookies survive)."
5173
+ },
5174
+ takeover: {
5175
+ type: "boolean",
5176
+ 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."
4692
5177
  }
4693
- resolvedPaths.push(resolved);
4694
5178
  }
4695
5179
  }
4696
- await page.setInputFiles(selector, resolvedPaths.length === 1 ? resolvedPaths[0] : resolvedPaths);
4697
- }
4698
- /**
4699
- * Ожидает появления file chooser dialog (для кастомных file picker'ов).
4700
- * Возвращает FileChooser, через который можно установить файлы.
4701
- * @param sessionId - ID сессии
4702
- * @param timeout - Таймаут ожидания в мс (по умолчанию из config.downloadTimeout)
4703
- * @returns PlaywrightFileChooser для установки файлов
4704
- */
4705
- async waitForFileChooser(sessionId, timeout) {
4706
- const page = await this.getPage(sessionId);
4707
- const waitTimeout = timeout ?? this.config.downloadTimeout ?? 6e4;
4708
- const fileChooser = await page.waitForEvent("filechooser", { timeout: waitTimeout });
4709
- return fileChooser;
4710
5180
  }
4711
- /**
4712
- * Закрывает браузер и очищает ресурсы.
4713
- * Если браузер подключён через CDP — закрывает только context,
4714
- * сам браузер не закрывается (сохраняет сессию пользователя).
4715
- */
4716
- async close() {
4717
- this.activeDownloads.clear();
4718
- for (const page of this.pages.values()) {
4719
- try {
4720
- await page.close();
4721
- } catch (error) {
4722
- console.error("[BrowserManager] Error closing page:", error);
4723
- }
4724
- }
4725
- this.pages.clear();
5181
+ ];
5182
+ function registerTools(server, config, sessionManager) {
5183
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
5184
+ return {
5185
+ tools: VSL_TOOLS
5186
+ };
5187
+ });
5188
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
5189
+ const { name, arguments: args, _meta } = request.params;
5190
+ const sessionId = _meta?.sessionId ?? sessionManager.getDefaultSessionId();
5191
+ const { session } = sessionManager.getSession(sessionId);
5192
+ const browser = sessionManager.getBrowserManager();
4726
5193
  try {
4727
- if (this.context) {
4728
- await this.context.close();
4729
- this.context = null;
5194
+ let result;
5195
+ switch (name) {
5196
+ case "vsl_get_snapshot":
5197
+ result = await handleGetSnapshot(args, browser, session, config, sessionId);
5198
+ break;
5199
+ case "vsl_execute_action":
5200
+ result = await handleExecuteAction(args, browser, session, sessionId);
5201
+ break;
5202
+ case "vsl_navigate":
5203
+ result = await handleNavigate(args, browser, session, sessionId);
5204
+ break;
5205
+ case "vsl_clear_cache":
5206
+ result = await handleClearCache(session);
5207
+ break;
5208
+ case "vsl_get_visual":
5209
+ result = await handleGetVisual(args, browser, session, sessionId);
5210
+ break;
5211
+ case "vsl_read_page":
5212
+ result = await handleReadPage(args, browser, session, config, sessionId);
5213
+ break;
5214
+ case "vsl_get_text_block":
5215
+ result = await handleGetTextBlock(args, session);
5216
+ break;
5217
+ case "vsl_click_coordinates":
5218
+ result = await handleClickCoordinates(args, browser, session, sessionId);
5219
+ break;
5220
+ case "vsl_manual_login":
5221
+ result = await handleManualLogin(args, browser, session, sessionManager, config, sessionId);
5222
+ break;
5223
+ default:
5224
+ return {
5225
+ content: [
5226
+ {
5227
+ type: "text",
5228
+ text: JSON.stringify({
5229
+ error: `Unknown tool: ${name}`
5230
+ })
5231
+ }
5232
+ ],
5233
+ isError: true
5234
+ };
4730
5235
  }
4731
- if (this.browser && !this.connectedViaCDP) {
4732
- await this.browser.close();
4733
- this.browser = null;
4734
- } else if (this.connectedViaCDP) {
4735
- this.browser = null;
5236
+ if (result && typeof result === "object" && "content" in result && Array.isArray(result.content)) {
5237
+ return result;
4736
5238
  }
5239
+ return {
5240
+ content: [
5241
+ {
5242
+ type: "text",
5243
+ text: JSON.stringify(result)
5244
+ }
5245
+ ]
5246
+ };
4737
5247
  } catch (error) {
4738
- console.error("[BrowserManager] Error during close():", error);
4739
- this.context = null;
4740
- this.browser = null;
5248
+ return {
5249
+ content: [
5250
+ {
5251
+ type: "text",
5252
+ text: JSON.stringify({
5253
+ error: `Tool execution failed: ${error instanceof Error ? error.message : String(error)}`
5254
+ })
5255
+ }
5256
+ ],
5257
+ isError: true
5258
+ };
4741
5259
  }
4742
- this.connectedViaCDP = false;
5260
+ });
5261
+ }
5262
+
5263
+ // src/resources/index.ts
5264
+ import {
5265
+ ListResourcesRequestSchema,
5266
+ ReadResourceRequestSchema
5267
+ } from "@modelcontextprotocol/sdk/types.js";
5268
+ var VSL_RESOURCES = [
5269
+ {
5270
+ uri: "vsl://current",
5271
+ name: "Current VSL Snapshot",
5272
+ description: "Current VSL snapshot of the page. Contains the full semantic structure of elements.",
5273
+ mimeType: "application/json"
5274
+ },
5275
+ {
5276
+ uri: "vsl://diff",
5277
+ name: "Latest VSL Diff",
5278
+ description: "Latest VSL diff since the previous snapshot. Contains only changes (added/modified/removed).",
5279
+ mimeType: "application/json"
4743
5280
  }
4744
- };
5281
+ ];
5282
+ function registerResources(server, _config, sessionManager) {
5283
+ server.setRequestHandler(ListResourcesRequestSchema, async () => {
5284
+ return {
5285
+ resources: VSL_RESOURCES
5286
+ };
5287
+ });
5288
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
5289
+ const { uri } = request.params;
5290
+ const sessionId = request.params._meta?.sessionId ?? sessionManager.getDefaultSessionId();
5291
+ const { session } = sessionManager.getSession(sessionId);
5292
+ ensureSubscribed(sessionId, session);
5293
+ switch (uri) {
5294
+ case "vsl://current":
5295
+ try {
5296
+ const snapshot = session.getSnapshot();
5297
+ return {
5298
+ contents: [
5299
+ {
5300
+ uri,
5301
+ mimeType: "application/json",
5302
+ text: JSON.stringify(snapshot, null, 2)
5303
+ }
5304
+ ]
5305
+ };
5306
+ } catch {
5307
+ return {
5308
+ contents: [
5309
+ {
5310
+ uri,
5311
+ mimeType: "application/json",
5312
+ text: JSON.stringify({
5313
+ error: "No snapshot available. Call vsl_get_snapshot first."
5314
+ })
5315
+ }
5316
+ ]
5317
+ };
5318
+ }
5319
+ case "vsl://diff":
5320
+ try {
5321
+ const diff = session.getDiff();
5322
+ if (!diff) {
5323
+ return {
5324
+ contents: [
5325
+ {
5326
+ uri,
5327
+ mimeType: "application/json",
5328
+ text: JSON.stringify({
5329
+ error: "No diff available. This is the first snapshot or no changes detected."
5330
+ })
5331
+ }
5332
+ ]
5333
+ };
5334
+ }
5335
+ return {
5336
+ contents: [
5337
+ {
5338
+ uri,
5339
+ mimeType: "application/json",
5340
+ text: JSON.stringify(diff, null, 2)
5341
+ }
5342
+ ]
5343
+ };
5344
+ } catch {
5345
+ return {
5346
+ contents: [
5347
+ {
5348
+ uri,
5349
+ mimeType: "application/json",
5350
+ text: JSON.stringify({
5351
+ error: "Failed to compute diff."
5352
+ })
5353
+ }
5354
+ ]
5355
+ };
5356
+ }
5357
+ default:
5358
+ throw new Error(`Unknown resource: ${uri}`);
5359
+ }
5360
+ });
5361
+ const subscribedSessions = /* @__PURE__ */ new Set();
5362
+ function ensureSubscribed(sessionId, session) {
5363
+ if (subscribedSessions.has(sessionId)) return;
5364
+ subscribedSessions.add(sessionId);
5365
+ session.setOnSnapshotChange(() => {
5366
+ server.sendResourceUpdated({ uri: "vsl://current" }).catch(() => {
5367
+ });
5368
+ if (session.getDiff()) {
5369
+ server.sendResourceUpdated({ uri: "vsl://diff" }).catch(() => {
5370
+ });
5371
+ }
5372
+ });
5373
+ }
5374
+ }
4745
5375
 
4746
5376
  // src/session/serverSession.ts
4747
5377
  import { diffVslDocuments, segmentTree, buildVslDocument } from "@thinkingos/vsl-sdk";
@@ -4999,6 +5629,16 @@ var SessionManager = class {
4999
5629
  context.lastAccessedAt = Date.now();
5000
5630
  return context;
5001
5631
  }
5632
+ /**
5633
+ * Сбрасывает кэши снапшотов всех сессий. Возвращает число очищенных сессий.
5634
+ * Нужен после перезапуска браузера (vsl_manual_login): старые VSL ID невалидны.
5635
+ */
5636
+ clearAllSessionCaches() {
5637
+ for (const context of this.sessions.values()) {
5638
+ context.session.clear();
5639
+ }
5640
+ return this.sessions.size;
5641
+ }
5002
5642
  /**
5003
5643
  * Проверяет, существует ли сессия.
5004
5644
  */
@@ -5087,7 +5727,7 @@ var SessionManager = class {
5087
5727
  };
5088
5728
 
5089
5729
  // src/version.ts
5090
- var VSL_MCP_SERVER_VERSION = "1.4.3";
5730
+ var VSL_MCP_SERVER_VERSION = "1.4.5";
5091
5731
 
5092
5732
  // src/index.ts
5093
5733
  async function main() {