@thinkingos/vsl-mcp-server 1.4.5 → 1.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -4234,28 +4234,8 @@ var BrowserManager = class {
4234
4234
  "Playwright is not installed. Install it with: npm install playwright"
4235
4235
  );
4236
4236
  }
4237
- if (this.config.cdpPort && options?.skipCdpConnect !== true) {
4238
- try {
4239
- this.browser = await pw.chromium.connectOverCDP({
4240
- endpointURL: `http://localhost:${this.config.cdpPort}`
4241
- });
4242
- this.connectedViaCDP = true;
4243
- this.currentHeadless = null;
4244
- const contexts = this.browser.contexts();
4245
- if (contexts.length > 0 && contexts[0]) {
4246
- this.context = contexts[0];
4247
- } else {
4248
- const contextOptions = {
4249
- acceptDownloads: this.config.acceptDownloads ?? true
4250
- };
4251
- if (this.config.downloadsPath) {
4252
- contextOptions.downloadsPath = this.config.downloadsPath;
4253
- }
4254
- this.context = await this.browser.newContext(contextOptions);
4255
- }
4256
- return;
4257
- } catch {
4258
- }
4237
+ if (options?.skipCdpConnect !== true && await this.tryConnectCdp()) {
4238
+ return;
4259
4239
  }
4260
4240
  const userDataDir = this.getProfileDir();
4261
4241
  const effectiveHeadless = options?.headless ?? this.config.headless;
@@ -4300,6 +4280,65 @@ var BrowserManager = class {
4300
4280
  }
4301
4281
  this.currentHeadless = effectiveHeadless;
4302
4282
  this.browser = null;
4283
+ if (this.context) {
4284
+ this.watchContextClose(this.context);
4285
+ }
4286
+ }
4287
+ /**
4288
+ * Пробует подключиться к уже запущенному браузеру по CDP (CDP-first).
4289
+ * Возвращает true, если подключение удалось и контекст получен.
4290
+ * Вынесено из launch(), чтобы ensureHeaded() мог сначала проверить внешний браузер
4291
+ * (например РЕАЛЬНЫЙ Chrome пользователя) и не поднимать второй браузер на том же профиле.
4292
+ */
4293
+ async tryConnectCdp() {
4294
+ if (!this.config.cdpPort) return false;
4295
+ const pw = await this.loadPlaywright();
4296
+ if (!pw) return false;
4297
+ try {
4298
+ this.browser = await pw.chromium.connectOverCDP({
4299
+ endpointURL: `http://localhost:${this.config.cdpPort}`
4300
+ });
4301
+ this.connectedViaCDP = true;
4302
+ this.currentHeadless = null;
4303
+ const contexts = this.browser.contexts();
4304
+ if (contexts.length > 0 && contexts[0]) {
4305
+ this.context = contexts[0];
4306
+ } else {
4307
+ const contextOptions = {
4308
+ acceptDownloads: this.config.acceptDownloads ?? true
4309
+ };
4310
+ if (this.config.downloadsPath) {
4311
+ contextOptions.downloadsPath = this.config.downloadsPath;
4312
+ }
4313
+ this.context = await this.browser.newContext(contextOptions);
4314
+ }
4315
+ if (this.context) {
4316
+ this.watchContextClose(this.context);
4317
+ }
4318
+ return true;
4319
+ } catch {
4320
+ this.browser = null;
4321
+ this.context = null;
4322
+ this.connectedViaCDP = false;
4323
+ this.currentHeadless = null;
4324
+ return false;
4325
+ }
4326
+ }
4327
+ /**
4328
+ * Сбрасывает состояние менеджера при закрытии контекста/браузера ИЗВНЕ.
4329
+ * Без этого мёртвый persistent-контекст считается живым (ранний выход launch()),
4330
+ * и процесс не переподключается к новому браузеру без перезапуска MCP-сервера.
4331
+ * @param context - контекст, за которым следим
4332
+ */
4333
+ watchContextClose(context) {
4334
+ context.on("close", () => {
4335
+ if (this.context !== context) return;
4336
+ this.context = null;
4337
+ this.browser = null;
4338
+ this.pages.clear();
4339
+ this.connectedViaCDP = false;
4340
+ this.currentHeadless = null;
4341
+ });
4303
4342
  }
4304
4343
  /**
4305
4344
  * Запускает persistent context с восстановлением отсутствующего бинарника браузера.
@@ -4424,8 +4463,56 @@ var BrowserManager = class {
4424
4463
  const page = await this.getPage(sessionId);
4425
4464
  return await page.evaluate(() => navigator.userAgent);
4426
4465
  }
4466
+ /**
4467
+ * Возвращает АВТОРИТЕТНЫЙ product браузера через CDP Browser.getVersion.
4468
+ * UA страницы (getBrowserUserAgent) подменяется stealth-плагином
4469
+ * (puppeteer-extra-plugin-stealth, evasion user-agent-override) в новых CDP-контекстах
4470
+ * и теряет подстроку 'HeadlessChrome' — для детекции режима окна он не годится.
4471
+ * @param sessionId - ID сессии
4472
+ */
4473
+ async getBrowserProduct(sessionId) {
4474
+ const page = await this.getPage(sessionId);
4475
+ if (!this.context) {
4476
+ throw new Error("Browser not available");
4477
+ }
4478
+ const cdp = await this.context.newCDPSession(page);
4479
+ try {
4480
+ const info = await cdp.send("Browser.getVersion");
4481
+ return typeof info?.product === "string" ? info.product : "";
4482
+ } finally {
4483
+ try {
4484
+ await cdp.detach();
4485
+ } catch (error) {
4486
+ console.error(
4487
+ "[BrowserManager] CDP session detach failed:",
4488
+ error instanceof Error ? error.message : String(error)
4489
+ );
4490
+ }
4491
+ }
4492
+ }
4493
+ /**
4494
+ * Определяет, headless ли браузер, по авторитетному CDP product (Browser.getVersion).
4495
+ * Фолбэк на UA страницы — только если CDP-команда недоступна.
4496
+ * @param sessionId - ID сессии
4497
+ */
4498
+ async isHeadlessBrowser(sessionId) {
4499
+ try {
4500
+ const product = await this.getBrowserProduct(sessionId);
4501
+ if (product) return isHeadlessUserAgent(product);
4502
+ } catch (error) {
4503
+ console.error(
4504
+ "[BrowserManager] CDP Browser.getVersion unavailable, falling back to page User-Agent:",
4505
+ error instanceof Error ? error.message : String(error)
4506
+ );
4507
+ }
4508
+ return isHeadlessUserAgent(await this.getBrowserUserAgent(sessionId));
4509
+ }
4427
4510
  /**
4428
4511
  * Приводит браузер к ВИДИМОМУ окну на том же профиле (R7).
4512
+ * CDP-first: если на cdpPort уже жив браузер (в том числе РЕАЛЬНЫЙ Chrome пользователя),
4513
+ * подключаемся к нему и НЕ поднимаем второй браузер на том же профиле.
4514
+ * Режим окна внешнего браузера определяется АВТОРИТЕТНО через CDP Browser.getVersion,
4515
+ * а не по UA страницы (его подменяет stealth-плагин).
4429
4516
  * Свой headless-контекст перезапускается, внешний видимый Chrome не трогается,
4430
4517
  * headless-браузер VSL по CDP закрывается только при явном takeover:true.
4431
4518
  * @param sessionId - ID сессии
@@ -4433,12 +4520,14 @@ var BrowserManager = class {
4433
4520
  */
4434
4521
  async ensureHeaded(sessionId, options) {
4435
4522
  if (!this.context) {
4436
- await this.launch({ headless: false, skipCdpConnect: true });
4437
- return { restarted: true, mode: "headed" };
4523
+ const connected = await this.tryConnectCdp();
4524
+ if (!connected) {
4525
+ await this.launch({ headless: false, skipCdpConnect: true });
4526
+ return { restarted: true, mode: "headed" };
4527
+ }
4438
4528
  }
4439
4529
  if (this.connectedViaCDP) {
4440
- const ua = await this.getBrowserUserAgent(sessionId);
4441
- if (!isHeadlessUserAgent(ua)) {
4530
+ if (!await this.isHeadlessBrowser(sessionId)) {
4442
4531
  return { restarted: false, mode: "cdp" };
4443
4532
  }
4444
4533
  if (options?.takeover !== true) {
@@ -5019,7 +5108,7 @@ var VSL_TOOLS = [
5019
5108
  },
5020
5109
  return_state: {
5021
5110
  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."
5111
+ description: "If true, returns diff and snapshot after the action. Useful for tracking DOM changes without an extra snapshot call. Default: true \u2014 always return state to save agent steps. Set to false to disable."
5023
5112
  },
5024
5113
  timeout: {
5025
5114
  type: "number",
@@ -5727,7 +5816,7 @@ var SessionManager = class {
5727
5816
  };
5728
5817
 
5729
5818
  // src/version.ts
5730
- var VSL_MCP_SERVER_VERSION = "1.4.5";
5819
+ var VSL_MCP_SERVER_VERSION = "1.4.6";
5731
5820
 
5732
5821
  // src/index.ts
5733
5822
  async function main() {