@thinkingos/vsl-mcp-server 1.4.3 → 1.4.4

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,126 @@ 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
222
  loadConfig: () => loadConfig
109
223
  });
110
- import { readFileSync, existsSync } from "fs";
224
+ import { readFileSync, existsSync as existsSync2 } from "fs";
111
225
  import { homedir } from "os";
112
226
  import { join } from "path";
113
227
  function loadConfig() {
@@ -129,6 +243,8 @@ function loadConfig() {
129
243
  acceptDownloads: process.env.VSL_ACCEPT_DOWNLOADS ? process.env.VSL_ACCEPT_DOWNLOADS === "true" : fileConfig.browser?.acceptDownloads ?? DEFAULT_BROWSER_CONFIG.acceptDownloads,
130
244
  userDataDir: process.env.VSL_USER_DATA_DIR || fileConfig.browser?.userDataDir || DEFAULT_BROWSER_CONFIG.userDataDir,
131
245
  cdpPort: process.env.VSL_CDP_PORT ? parseInt(process.env.VSL_CDP_PORT, 10) : fileConfig.browser?.cdpPort ?? DEFAULT_BROWSER_CONFIG.cdpPort,
246
+ autoInstallBrowser: process.env.VSL_BROWSER_AUTO_INSTALL ? process.env.VSL_BROWSER_AUTO_INSTALL === "true" : fileConfig.browser?.autoInstallBrowser ?? DEFAULT_BROWSER_CONFIG.autoInstallBrowser,
247
+ browserInstallTimeout: process.env.VSL_BROWSER_INSTALL_TIMEOUT ? parseInt(process.env.VSL_BROWSER_INSTALL_TIMEOUT, 10) : fileConfig.browser?.browserInstallTimeout ?? DEFAULT_BROWSER_CONFIG.browserInstallTimeout,
132
248
  proxy: parseProxyConfig(fileConfig)
133
249
  };
134
250
  const humanization = parseHumanizationConfig(fileConfig);
@@ -175,7 +291,7 @@ function parseDomStabilizationConfig(fileConfig) {
175
291
  return { enabled, timeout, stablePeriod, pollInterval, waitForNetworkIdle, networkIdleTimeout };
176
292
  }
177
293
  function loadConfigFile() {
178
- if (!existsSync(DEFAULT_CONFIG_PATH)) {
294
+ if (!existsSync2(DEFAULT_CONFIG_PATH)) {
179
295
  return {};
180
296
  }
181
297
  try {
@@ -191,6 +307,7 @@ var init_loader = __esm({
191
307
  "src/config/loader.ts"() {
192
308
  "use strict";
193
309
  init_domStabilization();
310
+ init_browserBinary();
194
311
  DEFAULT_CONFIG_PATH = join(homedir(), ".vsl", "config.json");
195
312
  DEFAULT_VISION_MODELS = {
196
313
  openai: "gpt-6-luna",
@@ -207,8 +324,11 @@ var init_loader = __esm({
207
324
  acceptDownloads: true,
208
325
  userDataDir: void 0,
209
326
  // Дефолт ~/.vsl/browser-profile применяется в manager.ts
210
- cdpPort: 9222
327
+ cdpPort: 9222,
211
328
  // Дефолтный CDP port для подключения множественных агентов
329
+ autoInstallBrowser: true,
330
+ // Self-heal: скачивать браузер, если кэш Playwright очищен
331
+ browserInstallTimeout: DEFAULT_BROWSER_INSTALL_TIMEOUT_MS
212
332
  };
213
333
  DEFAULT_HUMANIZATION_CONFIG = {
214
334
  enabled: true,
@@ -832,14 +952,14 @@ function extractDomTreeInBrowser() {
832
952
  function collectVisibleChildren(parent, parentPath) {
833
953
  const result = [];
834
954
  Array.from(parent.children).forEach((child, index) => {
835
- const path2 = [...parentPath, index];
955
+ const path3 = [...parentPath, index];
836
956
  const tag = child.tagName.toLowerCase();
837
957
  if (NON_RENDERABLE_TAGS.has(tag) || isDisplayNone(child)) {
838
958
  return;
839
959
  }
840
960
  const rect = toRect(child.getBoundingClientRect());
841
961
  if (isVisibilityHidden(child) || hasZeroBox(rect)) {
842
- result.push(...collectVisibleChildren(child, path2));
962
+ result.push(...collectVisibleChildren(child, path3));
843
963
  return;
844
964
  }
845
965
  const attributes = extractAttributes(child);
@@ -850,12 +970,12 @@ function extractDomTreeInBrowser() {
850
970
  if (css.opacity === "0" && css.pointerEvents === "none") {
851
971
  return;
852
972
  }
853
- const children = collectVisibleChildren(child, path2);
854
- const vslId = `${tag}_${path2.join("_")}`;
973
+ const children = collectVisibleChildren(child, path3);
974
+ const vslId = `${tag}_${path3.join("_")}`;
855
975
  child.setAttribute("data-vsl-id", vslId);
856
976
  result.push({
857
977
  tag,
858
- indexPath: path2,
978
+ indexPath: path3,
859
979
  rect,
860
980
  text: ownText(child) || null,
861
981
  attributes,
@@ -4210,7 +4330,7 @@ function registerResources(server, _config, sessionManager) {
4210
4330
  }
4211
4331
 
4212
4332
  // src/browser/manager.ts
4213
- import path from "path";
4333
+ import path2 from "path";
4214
4334
  import os from "os";
4215
4335
 
4216
4336
  // src/browser/challengeResolver.ts
@@ -4350,6 +4470,7 @@ async function resolveChallenge(page, targetUrl, options = {}) {
4350
4470
  }
4351
4471
 
4352
4472
  // src/browser/manager.ts
4473
+ init_browserBinary();
4353
4474
  var BrowserManager = class {
4354
4475
  browser = null;
4355
4476
  context = null;
@@ -4435,7 +4556,7 @@ var BrowserManager = class {
4435
4556
  } catch {
4436
4557
  }
4437
4558
  }
4438
- const userDataDir = this.config.userDataDir ?? path.join(os.homedir(), ".vsl", "browser-profile");
4559
+ const userDataDir = this.config.userDataDir ?? path2.join(os.homedir(), ".vsl", "browser-profile");
4439
4560
  const persistentOptions = {
4440
4561
  headless: this.config.headless,
4441
4562
  acceptDownloads: this.config.acceptDownloads ?? true
@@ -4455,12 +4576,88 @@ var BrowserManager = class {
4455
4576
  launchArgs.push(`--remote-debugging-port=${this.config.cdpPort}`);
4456
4577
  }
4457
4578
  persistentOptions.args = launchArgs;
4458
- this.context = await pw.chromium.launchPersistentContext(
4579
+ this.context = await this.launchPersistentContextWithRecovery(
4580
+ pw,
4459
4581
  userDataDir,
4460
4582
  persistentOptions
4461
4583
  );
4462
4584
  this.browser = null;
4463
4585
  }
4586
+ /**
4587
+ * Запускает persistent context с восстановлением отсутствующего бинарника браузера.
4588
+ *
4589
+ * Playwright сам решает, какой артефакт использовать (chromium или chromium-headless-shell
4590
+ * для headless), поэтому наличие бинарника не проверяется заранее по угаданному пути:
4591
+ * авторитетный путь берётся из ошибки Playwright, затем браузер скачивается и запуск
4592
+ * повторяется ровно один раз.
4593
+ *
4594
+ * @throws Error с короткой инструкцией, если восстановление отключено или не помогло
4595
+ */
4596
+ async launchPersistentContextWithRecovery(pw, userDataDir, options) {
4597
+ try {
4598
+ return await pw.chromium.launchPersistentContext(userDataDir, options);
4599
+ } catch (error) {
4600
+ const missing = parseMissingBrowserError(error);
4601
+ if (!missing) throw error;
4602
+ await this.ensureBrowserBinary(missing);
4603
+ try {
4604
+ return await pw.chromium.launchPersistentContext(userDataDir, options);
4605
+ } catch (retryError) {
4606
+ const stillMissing = parseMissingBrowserError(retryError);
4607
+ if (!stillMissing) throw retryError;
4608
+ throw new Error(
4609
+ formatMissingBrowserError(stillMissing, {
4610
+ cliPath: resolvePlaywrightCliPath(),
4611
+ reason: "the binary is still missing after a successful download"
4612
+ })
4613
+ );
4614
+ }
4615
+ }
4616
+ }
4617
+ /**
4618
+ * Гарантирует наличие бинарника браузера: скачивает его (self-heal) либо бросает
4619
+ * actionable ошибку, если автоустановка отключена конфигурацией или не удалась.
4620
+ */
4621
+ async ensureBrowserBinary(missing) {
4622
+ const cliPath = resolvePlaywrightCliPath();
4623
+ if (this.config.autoInstallBrowser === false) {
4624
+ throw new Error(
4625
+ formatMissingBrowserError(missing, { cliPath, autoInstallDisabled: true })
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).`);
4641
+ }
4642
+ /**
4643
+ * Шов для автоматической загрузки браузера (self-heal).
4644
+ * Юнит-тесты переопределяют его через jest.spyOn, чтобы не скачивать браузеры реально.
4645
+ */
4646
+ async installBrowserBinary(info) {
4647
+ const cliPath = resolvePlaywrightCliPath();
4648
+ if (!cliPath) {
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
+ });
4660
+ }
4464
4661
  /**
4465
4662
  * Возвращает страницу для указанной сессии (создаёт новую из context, если нет).
4466
4663
  * @param sessionId - ID сессии для изоляции страниц
@@ -4595,13 +4792,13 @@ var BrowserManager = class {
4595
4792
  path: null
4596
4793
  };
4597
4794
  }
4598
- const path2 = await download.path();
4795
+ const path3 = await download.path();
4599
4796
  return {
4600
4797
  downloadId,
4601
4798
  filename: download.suggestedFilename(),
4602
4799
  url: download.url(),
4603
4800
  status: "completed",
4604
- path: path2
4801
+ path: path3
4605
4802
  };
4606
4803
  } catch {
4607
4804
  return {
@@ -4638,9 +4835,9 @@ var BrowserManager = class {
4638
4835
  await download.saveAs(savePath);
4639
4836
  } else {
4640
4837
  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) {
4838
+ const resolvedBase = path2.resolve(downloadsPath.replace(/^~/, os.homedir()));
4839
+ const resolvedSave = path2.resolve(resolvedBase, savePath);
4840
+ if (!resolvedSave.startsWith(resolvedBase + path2.sep) && resolvedSave !== resolvedBase) {
4644
4841
  throw new Error(`Path traversal detected: save_path '${savePath}' escapes downloads directory '${resolvedBase}'`);
4645
4842
  }
4646
4843
  await download.saveAs(resolvedSave);
@@ -4681,13 +4878,13 @@ var BrowserManager = class {
4681
4878
  }
4682
4879
  const resolvedPaths = [];
4683
4880
  for (const filePath of filePaths) {
4684
- const isAbsolute = path.isAbsolute(filePath);
4881
+ const isAbsolute = path2.isAbsolute(filePath);
4685
4882
  if (isAbsolute) {
4686
4883
  resolvedPaths.push(filePath);
4687
4884
  } 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) {
4885
+ const resolved = path2.resolve(process.cwd(), filePath);
4886
+ const cwd = path2.resolve(process.cwd());
4887
+ if (!resolved.startsWith(cwd + path2.sep) && resolved !== cwd) {
4691
4888
  throw new Error(`Path traversal detected: file path '${filePath}' resolves outside working directory '${cwd}'`);
4692
4889
  }
4693
4890
  resolvedPaths.push(resolved);
@@ -5087,7 +5284,7 @@ var SessionManager = class {
5087
5284
  };
5088
5285
 
5089
5286
  // src/version.ts
5090
- var VSL_MCP_SERVER_VERSION = "1.4.3";
5287
+ var VSL_MCP_SERVER_VERSION = "1.4.4";
5091
5288
 
5092
5289
  // src/index.ts
5093
5290
  async function main() {