@thinkingos/vsl-mcp-server 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,20 +6,16 @@ VSL MCP Server — интеграция Visual Scene Language с AI-агента
6
6
 
7
7
  ## Быстрая установка (одна команда)
8
8
 
9
- # Через npx — автоматически скачивает пакет и запускает интерактивный setup:
10
-
11
9
 
10
+ # Через npx — автоматически скачивает пакет и запускает интерактивный setup:
12
11
  npx -p @thinkingos/vsl-mcp-server mcp-server-setup
13
12
 
14
13
 
15
14
  Setup скрипт поможет вам:
16
15
  1. Проверить Node.js >= 18
17
16
  2. Установить Playwright (опционально, для браузерных инструментов)
18
- 3. Настроить API ключи для vision-backend (OpenAI / Anthropic / Custom)
19
- 4. Проверить работоспособность API (тестовый запрос)
20
- 5. Сохранить конфигурацию в `~/.vsl/config.json`
21
- 6. Получить инструкции для подключения к агенту
22
-
17
+ 3. Сохранить конфигурацию в `~/.vsl/config.json`
18
+ 4. Получить инструкции для подключения к агенту
23
19
  ## Установка из исходников (для разработчиков)
24
20
 
25
21
  ### Из корня monorepo
@@ -36,18 +32,19 @@ cd packages/mcp-server
36
32
  npm run build
37
33
  ### Интерактивная настройка (рекомендуется)
38
34
 
35
+
39
36
  # Из корня monorepo:
40
37
  node packages/mcp-server/bin/setup.js
41
38
 
42
39
  # Или из директории packages/mcp-server:
43
40
  npm run setup
41
+
42
+
44
43
  Setup скрипт поможет вам:
45
44
  1. Проверить Node.js >= 18
46
45
  2. Установить Playwright (опционально, для браузерных инструментов)
47
- 3. Настроить API ключи для vision-backend (OpenAI, Anthropic, или любой OpenAI-compatible провайдер)
48
- 4. Проверить работоспособность API (тестовый запрос)
49
- 5. Сохранить конфигурацию в `~/.vsl/config.json`
50
- 6. Получить инструкции для подключения к агенту
46
+ 3. Сохранить конфигурацию в `~/.vsl/config.json`
47
+ 4. Получить инструкции для подключения к агенту
51
48
 
52
49
  ## Конфигурация
53
50
 
@@ -102,12 +99,26 @@ export VSL_VISION_MODEL="meta-llama/Llama-Vision"
102
99
  Выполнить действие над элементом VSL.
103
100
 
104
101
  **Параметры:**
105
- - `action` (string, required) — имя действия: `click`, `type`, `fill` (алиас `type`), `scroll`, `select`, `hover`, `focus`, `blur`, `check`, `uncheck`, `press`
102
+ - `action` (string, required) — имя действия: `click`, `type`, `fill` (алиас `type`), `scroll`, `select`, `hover`, `focus`, `blur`, `check`, `uncheck`, `press`, `upload` (загрузка файла, требует `value` — путь к файлу или список путей через запятую)
106
103
  - `target_id` (string, required) — ID элемента в VSL JSON
107
- - `value` (string, optional) — значение для действия (текст для `type`, опция для `select`)
104
+ - `value` (string, optional) — значение для действия (текст для `type`, опция для `select`, путь к файлу для `upload`)
108
105
 
109
106
  **Возвращает:** результат выполнения действия.
110
107
 
108
+ **Пример загрузки файла:**
109
+
110
+
111
+ Agent: vsl_execute_action(action="upload", target_id="file_input_0", value="/path/to/document.pdf")
112
+ → { success: true, data: { action: "upload", upload: { selector: "#file_input_0", files: ["/path/to/document.pdf"], success: true } } }
113
+
114
+
115
+ Для загрузки нескольких файлов (если input имеет `multiple` атрибут):
116
+
117
+
118
+ Agent: vsl_execute_action(action="upload", target_id="file_input_1", value="/path/file1.jpg, /path/file2.jpg")
119
+ → { success: true, data: { upload: { files: ["/path/file1.jpg", "/path/file2.jpg"], success: true } } }
120
+
121
+
111
122
  **Lazy Navigation (DEC-028):**
112
123
  Перед выполнением действия система автоматически проверяет, находится ли браузер на URL из текущего snapshot. Если нет — автоматически навигирует на нужный URL. Это позволяет агенту:
113
124
  1. Прочитать страницу через HTTP-путь (быстро, без браузера)
package/bin/setup.js CHANGED
@@ -6,10 +6,8 @@
6
6
  * Бесшовная установка:
7
7
  * 1. Проверка Node.js >= 18
8
8
  * 2. Проверка/установка Playwright (chromium)
9
- * 3. Настройка API ключей для vision-backend (OpenAI / Anthropic / Custom)
10
- * 4. Валидация API ключа (тестовый запрос)
11
- * 5. Сохранение конфигурации в ~/.vsl/config.json
12
- * 6. Вывод инструкций для подключения к агенту
9
+ * 3. Сохранение конфигурации в ~/.vsl/config.json
10
+ * 4. Вывод инструкций для подключения к агенту
13
11
  *
14
12
  * Usage:
15
13
  * # Из корня monorepo:
@@ -18,6 +16,7 @@
18
16
  * npm run setup
19
17
  */
20
18
 
19
+
21
20
  import { createInterface } from 'readline';
22
21
  import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'fs';
23
22
  import { join } from 'path';
@@ -438,10 +437,8 @@ async function main() {
438
437
  log('Этот скрипт поможет вам:');
439
438
  log(' 1. Проверить Node.js');
440
439
  log(' 2. Установить Playwright (для браузерных инструментов)');
441
- log(' 3. Настроить API ключи для vision-backend');
442
- log(' 4. Проверить работоспособность API');
443
- log(' 5. Сохранить конфигурацию');
444
- log(' 6. Получить инструкции для подключения к агенту');
440
+ log(' 3. Сохранить конфигурацию');
441
+ log(' 4. Получить инструкции для подключения к агенту');
445
442
  log('');
446
443
 
447
444
  // Шаг 1: Node.js
@@ -452,39 +449,16 @@ async function main() {
452
449
  // Шаг 2: Playwright
453
450
  await setupPlaywright();
454
451
 
455
- // Шаг 3: API config
456
- const visionConfig = await setupApiConfig();
457
-
458
- // Шаг 4: Валидация
459
- if (visionConfig) {
460
- await validateApiKey(visionConfig);
461
- }
462
-
463
- // Шаг 5: Сохранение конфига
464
- step(5, 'Сохранение конфигурации');
452
+ // Шаг 3: Сохранение конфига
453
+ step(3, 'Сохранение конфигурации');
465
454
 
466
455
  const configPath = join(ensureConfigDir(), 'config.json');
467
456
  const config = loadOrCreateConfig(configPath);
457
+ saveConfig(configPath, config);
458
+ ok(`Конфигурация сохранена: ${configPath}`);
468
459
 
469
- if (visionConfig) {
470
- config.vision = {
471
- provider: visionConfig.provider,
472
- model: visionConfig.model,
473
- apiKey: visionConfig.apiKey,
474
- ...(visionConfig.baseUrl ? { baseUrl: visionConfig.baseUrl } : {}),
475
- };
476
- saveConfig(configPath, config);
477
- ok(`Конфигурация сохранена: ${configPath}`);
478
- } else {
479
- warn('Vision-backend не настроен. Вы можете настроить его позже.');
480
- info(`Через config file: ${C.dim}~/.vsl/config.json${C.reset}`);
481
- info(`Через env vars: ${C.dim}VSL_VISION_PROVIDER, VSL_VISION_BASE_URL, VSL_VISION_API_KEY, VSL_VISION_MODEL${C.reset}`);
482
- }
483
-
484
- // Шаг 6: Инструкции
485
- if (visionConfig) {
486
- printAgentInstructions(visionConfig);
487
- }
460
+ // Шаг 4: Инструкции
461
+ printAgentInstructions(null);
488
462
 
489
463
  // Финал
490
464
  log(`${C.bold}✨ Готово!${C.reset}`);
package/dist/index.js CHANGED
@@ -72,7 +72,7 @@ import {
72
72
  } from "@modelcontextprotocol/sdk/types.js";
73
73
 
74
74
  // src/tools/getSnapshot.ts
75
- import { segmentTree, buildVslDocument } from "@thinkingos/vsl-sdk";
75
+ import { isVslDiff } from "@thinkingos/vsl-sdk";
76
76
  function extractDomTreeInBrowser() {
77
77
  const NON_RENDERABLE_TAGS = /* @__PURE__ */ new Set([
78
78
  "script",
@@ -180,7 +180,7 @@ async function handleGetSnapshot(args, browser, session, _config) {
180
180
  if (!isAvailable) {
181
181
  return {
182
182
  status: "error",
183
- error: 'Playwright is not installed. Install it with: npm install playwright\nOr use vsl_read_page with mode="http" for static pages.'
183
+ error: "Playwright is not installed. Install it with: npm install playwright"
184
184
  };
185
185
  }
186
186
  const extractedElements = await browser.evaluate(extractDomTreeInBrowser);
@@ -188,12 +188,19 @@ async function handleGetSnapshot(args, browser, session, _config) {
188
188
  width: window.innerWidth,
189
189
  height: window.innerHeight
190
190
  }));
191
- const segmentedElements = segmentTree(extractedElements);
192
- const vslDocument = buildVslDocument(segmentedElements, {
191
+ const url = args.url || await browser.evaluate(() => window.location.href);
192
+ const title = await browser.evaluate(() => document.title);
193
+ const input = {
193
194
  viewport,
194
- url: args.url || await browser.evaluate(() => window.location.href),
195
+ url,
196
+ title,
195
197
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
196
- });
198
+ };
199
+ const result = session.snapshotFromElements(
200
+ extractedElements,
201
+ input
202
+ );
203
+ const currentDoc = isVslDiff(result) ? session.getSnapshot() : result;
197
204
  await browser.evaluate(
198
205
  (objects) => {
199
206
  function visit(obj) {
@@ -219,12 +226,11 @@ async function handleGetSnapshot(args, browser, session, _config) {
219
226
  visit(obj);
220
227
  }
221
228
  },
222
- vslDocument.objects
229
+ currentDoc.objects
223
230
  );
224
- session.setSnapshot(vslDocument);
225
231
  return {
226
232
  status: "success",
227
- data: vslDocument
233
+ data: result
228
234
  };
229
235
  } catch (error) {
230
236
  return {
@@ -335,7 +341,8 @@ var VALID_ACTIONS = [
335
341
  "check",
336
342
  "uncheck",
337
343
  "press",
338
- "download"
344
+ "download",
345
+ "upload"
339
346
  ];
340
347
  async function handleExecuteAction(args, browser, session) {
341
348
  try {
@@ -479,6 +486,35 @@ async function handleExecuteAction(args, browser, session) {
479
486
  }, selector);
480
487
  break;
481
488
  }
489
+ case "upload": {
490
+ if (!args.value) {
491
+ return {
492
+ status: "error",
493
+ error: "value is required for upload action (file path(s), comma-separated)"
494
+ };
495
+ }
496
+ const filePaths = args.value.split(",").map((p) => p.trim()).filter(Boolean);
497
+ if (filePaths.length === 0) {
498
+ return {
499
+ status: "error",
500
+ error: "value must contain at least one file path"
501
+ };
502
+ }
503
+ await browser.uploadFile(selector, filePaths);
504
+ return {
505
+ status: "success",
506
+ data: {
507
+ action: args.action,
508
+ target_id: args.target_id,
509
+ success: true,
510
+ upload: {
511
+ selector,
512
+ files: filePaths,
513
+ success: true
514
+ }
515
+ }
516
+ };
517
+ }
482
518
  default:
483
519
  return {
484
520
  status: "error",
@@ -506,15 +542,15 @@ async function handleGetVisual(args, browser) {
506
542
  try {
507
543
  if (!args.element_id || typeof args.element_id !== "string") {
508
544
  return {
509
- status: "error",
510
- error: "element_id is required"
545
+ content: [{ type: "text", text: "Error: element_id is required" }],
546
+ isError: true
511
547
  };
512
548
  }
513
549
  const isAvailable = await browser.isAvailable();
514
550
  if (!isAvailable) {
515
551
  return {
516
- status: "error",
517
- error: "Playwright is not installed. Install it with: npm install playwright"
552
+ content: [{ type: "text", text: "Error: Playwright is not installed. Install it with: npm install playwright" }],
553
+ isError: true
518
554
  };
519
555
  }
520
556
  if (args.element_id === "root_0") {
@@ -522,12 +558,10 @@ async function handleGetVisual(args, browser) {
522
558
  const screenshotBuffer2 = await page2.screenshot({ type: "png", fullPage: false });
523
559
  const base64Image2 = screenshotBuffer2.toString("base64");
524
560
  return {
525
- status: "success",
526
- data: {
527
- element_id: args.element_id,
528
- image: base64Image2,
529
- mediaType: "image/png"
530
- }
561
+ content: [
562
+ { type: "image", data: base64Image2, mimeType: "image/png" },
563
+ { type: "text", text: `Full page screenshot (${args.element_id})` }
564
+ ]
531
565
  };
532
566
  }
533
567
  const selector = `[data-vsl-id="${args.element_id}"], #${args.element_id}, [id="${args.element_id}"]`;
@@ -536,8 +570,8 @@ async function handleGetVisual(args, browser) {
536
570
  }, selector);
537
571
  if (!elementExists) {
538
572
  return {
539
- status: "error",
540
- error: `Element not found: ${args.element_id}. Note: vsl_get_visual works with IDs from vsl_get_snapshot (browser DOM), not vsl_read_page (semantic IDs).`
573
+ content: [{ type: "text", text: `Error: Element not found: ${args.element_id}. Note: vsl_get_visual works with IDs from vsl_get_snapshot (browser DOM), not vsl_read_page (semantic IDs).` }],
574
+ isError: true
541
575
  };
542
576
  }
543
577
  const page = await browser.getPage();
@@ -549,8 +583,8 @@ async function handleGetVisual(args, browser) {
549
583
  }, selector);
550
584
  if (!rect) {
551
585
  return {
552
- status: "error",
553
- error: `Could not get bounding box for element: ${args.element_id}`
586
+ content: [{ type: "text", text: `Error: Could not get bounding box for element: ${args.element_id}` }],
587
+ isError: true
554
588
  };
555
589
  }
556
590
  const screenshotBuffer = await page.screenshot({
@@ -559,17 +593,15 @@ async function handleGetVisual(args, browser) {
559
593
  });
560
594
  const base64Image = screenshotBuffer.toString("base64");
561
595
  return {
562
- status: "success",
563
- data: {
564
- element_id: args.element_id,
565
- image: base64Image,
566
- mediaType: "image/png"
567
- }
596
+ content: [
597
+ { type: "image", data: base64Image, mimeType: "image/png" },
598
+ { type: "text", text: `Screenshot of element: ${args.element_id}` }
599
+ ]
568
600
  };
569
601
  } catch (error) {
570
602
  return {
571
- status: "error",
572
- error: `vsl_get_visual failed: ${error instanceof Error ? error.message : String(error)}`
603
+ content: [{ type: "text", text: `Error: vsl_get_visual failed: ${error instanceof Error ? error.message : String(error)}` }],
604
+ isError: true
573
605
  };
574
606
  }
575
607
  }
@@ -909,47 +941,66 @@ async function handleReadPage(args, browser, session, _config) {
909
941
  }
910
942
  };
911
943
  } catch (error) {
944
+ const stack = error instanceof Error ? error.stack : String(error);
945
+ console.error("vsl_read_page error:", stack);
912
946
  return {
913
947
  status: "error",
914
- error: `vsl_read_page failed: ${error instanceof Error ? error.message : String(error)}`
948
+ error: `vsl_read_page failed: ${error instanceof Error ? error.message : String(error)}
949
+ Stack: ${stack}`
915
950
  };
916
951
  }
917
952
  }
918
953
  async function extractVslFromPage(browser) {
919
- const domTree = await browser.evaluate(() => {
920
- const extractElement = (el) => {
921
- const rect = el.getBoundingClientRect();
922
- const computedStyle = window.getComputedStyle(el);
923
- return {
924
- tag: el.tagName.toLowerCase(),
925
- id: el.id || void 0,
926
- className: el.className || void 0,
927
- text: el.textContent?.trim().substring(0, 100) || void 0,
928
- rect: {
929
- x: rect.x,
930
- y: rect.y,
931
- width: rect.width,
932
- height: rect.height
933
- },
934
- role: el.getAttribute("role") || void 0,
935
- ariaLabel: el.getAttribute("aria-label") || void 0,
936
- ariaHidden: el.getAttribute("aria-hidden") || void 0,
937
- display: computedStyle.display,
938
- visibility: computedStyle.visibility,
939
- children: Array.from(el.children).filter((child) => {
940
- const style = window.getComputedStyle(child);
941
- return style.display !== "none" && style.visibility !== "hidden";
942
- }).map(extractElement)
954
+ let domTree = null;
955
+ try {
956
+ domTree = await browser.evaluate(() => {
957
+ const extractElement = (el) => {
958
+ const rect2 = el.getBoundingClientRect();
959
+ const computedStyle = window.getComputedStyle(el);
960
+ return {
961
+ tag: el.tagName.toLowerCase(),
962
+ id: el.id || void 0,
963
+ className: el.className || void 0,
964
+ text: el.textContent?.trim().substring(0, 100) || void 0,
965
+ rect: {
966
+ x: rect2.x,
967
+ y: rect2.y,
968
+ width: rect2.width,
969
+ height: rect2.height
970
+ },
971
+ role: el.getAttribute("role") || void 0,
972
+ ariaLabel: el.getAttribute("aria-label") || void 0,
973
+ ariaHidden: el.getAttribute("aria-hidden") || void 0,
974
+ display: computedStyle.display,
975
+ visibility: computedStyle.visibility,
976
+ children: Array.from(el.children).filter((child) => {
977
+ const style = window.getComputedStyle(child);
978
+ return style.display !== "none" && style.visibility !== "hidden";
979
+ }).map(extractElement)
980
+ };
943
981
  };
982
+ return extractElement(document.documentElement);
983
+ });
984
+ } catch (error) {
985
+ console.error("extractVslFromPage: browser.evaluate failed:", error);
986
+ domTree = null;
987
+ }
988
+ if (!domTree || typeof domTree !== "object") {
989
+ domTree = {
990
+ tag: "html",
991
+ rect: { x: 0, y: 0, width: 1280, height: 800 },
992
+ children: []
944
993
  };
945
- return extractElement(document.documentElement);
946
- });
994
+ }
995
+ const rect = domTree.rect;
996
+ const viewportWidth = rect?.width ?? 1280;
997
+ const viewportHeight = rect?.height ?? 800;
947
998
  return {
948
999
  vsl_version: "1.0.0",
949
1000
  canvas: {
950
1001
  viewport: {
951
- width: domTree.rect ? domTree.rect.width : 1280,
952
- height: domTree.rect ? domTree.rect.height : 800,
1002
+ width: viewportWidth,
1003
+ height: viewportHeight,
953
1004
  unit: "px"
954
1005
  },
955
1006
  background: "#ffffff",
@@ -1172,7 +1223,7 @@ var VSL_TOOLS = [
1172
1223
  },
1173
1224
  {
1174
1225
  name: "vsl_execute_action",
1175
- description: "\u0412\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u044C \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0435 \u043D\u0430\u0434 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u043C VSL. \u041D\u0430\u0439\u0434\u0438\u0442\u0435 \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u043F\u043E id \u0432 snapshot (vsl_get_snapshot), \u0437\u0430\u0442\u0435\u043C \u0432\u044B\u0437\u043E\u0432\u0438\u0442\u0435 \u044D\u0442\u043E \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0435. \u041F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u043C\u044B\u0435 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F: click (\u043A\u043B\u0438\u043A \u043F\u043E \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0443), type (\u0432\u0432\u043E\u0434 \u0442\u0435\u043A\u0441\u0442\u0430, \u0442\u0440\u0435\u0431\u0443\u0435\u0442 value), fill (\u0430\u043B\u0438\u0430\u0441 type, \u0432\u0432\u043E\u0434 \u0442\u0435\u043A\u0441\u0442\u0430, \u0442\u0440\u0435\u0431\u0443\u0435\u0442 value), scroll (\u043F\u0440\u043E\u043A\u0440\u0443\u0442\u043A\u0430), select (\u0432\u044B\u0431\u043E\u0440 \u043E\u043F\u0446\u0438\u0438, \u0442\u0440\u0435\u0431\u0443\u0435\u0442 value), hover, focus, blur, check, uncheck, press (\u043D\u0430\u0436\u0430\u0442\u0438\u0435 \u043A\u043B\u0430\u0432\u0438\u0448\u0438). \u041F\u0440\u0438\u043C\u0435\u0440: {action:click, target_id:btn_1} \u0438\u043B\u0438 {action:type, target_id:inp_2, value:hello@mail.com} \u0438\u043B\u0438 {action:fill, target_id:inp_2, value:hello@mail.com}.",
1226
+ description: "\u0412\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u044C \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0435 \u043D\u0430\u0434 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u043C VSL. \u041D\u0430\u0439\u0434\u0438\u0442\u0435 \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u043F\u043E id \u0432 snapshot (vsl_get_snapshot), \u0437\u0430\u0442\u0435\u043C \u0432\u044B\u0437\u043E\u0432\u0438\u0442\u0435 \u044D\u0442\u043E \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0435. \u041F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u043C\u044B\u0435 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F: click (\u043A\u043B\u0438\u043A \u043F\u043E \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0443), type (\u0432\u0432\u043E\u0434 \u0442\u0435\u043A\u0441\u0442\u0430, \u0442\u0440\u0435\u0431\u0443\u0435\u0442 value), fill (\u0430\u043B\u0438\u0430\u0441 type, \u0432\u0432\u043E\u0434 \u0442\u0435\u043A\u0441\u0442\u0430, \u0442\u0440\u0435\u0431\u0443\u0435\u0442 value), scroll (\u043F\u0440\u043E\u043A\u0440\u0443\u0442\u043A\u0430), select (\u0432\u044B\u0431\u043E\u0440 \u043E\u043F\u0446\u0438\u0438, \u0442\u0440\u0435\u0431\u0443\u0435\u0442 value), hover, focus, blur, check, uncheck, press (\u043D\u0430\u0436\u0430\u0442\u0438\u0435 \u043A\u043B\u0430\u0432\u0438\u0448\u0438), upload (\u0437\u0430\u0433\u0440\u0443\u0437\u043A\u0430 \u0444\u0430\u0439\u043B\u0430, \u0442\u0440\u0435\u0431\u0443\u0435\u0442 value \u2014 \u043F\u0443\u0442\u044C \u043A \u0444\u0430\u0439\u043B\u0443 \u0438\u043B\u0438 \u0441\u043F\u0438\u0441\u043E\u043A \u043F\u0443\u0442\u0435\u0439 \u0447\u0435\u0440\u0435\u0437 \u0437\u0430\u043F\u044F\u0442\u0443\u044E). \u041F\u0440\u0438\u043C\u0435\u0440: {action:click, target_id:btn_1} \u0438\u043B\u0438 {action:type, target_id:inp_2, value:hello@mail.com} \u0438\u043B\u0438 {action:fill, target_id:inp_2, value:hello@mail.com} \u0438\u043B\u0438 {action:upload, target_id:file_input_0, value:/path/to/file.pdf}.",
1176
1227
  inputSchema: {
1177
1228
  type: "object",
1178
1229
  properties: {
@@ -1230,7 +1281,7 @@ var VSL_TOOLS = [
1230
1281
  },
1231
1282
  {
1232
1283
  name: "vsl_read_page",
1233
- description: "\u0413\u0438\u0431\u0440\u0438\u0434\u043D\u043E\u0435 \u0447\u0442\u0435\u043D\u0438\u0435 \u0432\u0435\u0431-\u0441\u0442\u0440\u0430\u043D\u0438\u0446. mode=auto (\u043F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E): \u0441\u0442\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438\u0435 \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u044B \u0447\u0438\u0442\u0430\u044E\u0442\u0441\u044F \u0447\u0435\u0440\u0435\u0437 HTTP (\u0431\u044B\u0441\u0442\u0440\u043E), SPA \u0440\u0435\u043D\u0434\u0435\u0440\u044F\u0442\u0441\u044F \u0447\u0435\u0440\u0435\u0437 \u0431\u0440\u0430\u0443\u0437\u0435\u0440. mode=http: \u0442\u043E\u043B\u044C\u043A\u043E HTTP (\u0431\u0435\u0437 \u0431\u0440\u0430\u0443\u0437\u0435\u0440\u0430). mode=render: \u0432\u0441\u0435\u0433\u0434\u0430 \u0440\u0435\u043D\u0434\u0435\u0440\u0438\u0442\u044C \u0447\u0435\u0440\u0435\u0437 \u0431\u0440\u0430\u0443\u0437\u0435\u0440. readable=true: \u0444\u0438\u043B\u044C\u0442\u0440\u0443\u0435\u0442 \u0448\u0443\u043C (\u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u044F, \u0444\u0443\u0442\u0435\u0440\u044B, cookie-\u0431\u0430\u043D\u043D\u0435\u0440\u044B) \u0434\u043B\u044F \u0447\u0438\u0441\u0442\u043E\u0433\u043E \u043A\u043E\u043D\u0442\u0435\u043D\u0442\u0430. \u041F\u0440\u0438 \u043F\u043E\u0432\u0442\u043E\u0440\u043D\u044B\u0445 \u0432\u044B\u0437\u043E\u0432\u0430\u0445 \u0432\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 diff (\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F), \u0430 \u043D\u0435 \u043F\u043E\u043B\u043D\u044B\u0439 \u043A\u043E\u043D\u0442\u0435\u043D\u0442. \u041F\u0440\u0438\u043C\u0435\u0440: {url:https://example.com, mode:auto, readable:true}.",
1284
+ description: '\u0427\u0442\u0435\u043D\u0438\u0435 \u0432\u0435\u0431-\u0441\u0442\u0440\u0430\u043D\u0438\u0446. \u0410\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u044F\u0435\u0442 \u0441\u0442\u0440\u0430\u0442\u0435\u0433\u0438\u044E: \u0441\u0442\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438\u0435 \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u044B \u0447\u0438\u0442\u0430\u044E\u0442\u0441\u044F \u0447\u0435\u0440\u0435\u0437 HTTP (\u0431\u044B\u0441\u0442\u0440\u043E), SPA \u0440\u0435\u043D\u0434\u0435\u0440\u044F\u0442\u0441\u044F \u0447\u0435\u0440\u0435\u0437 \u0431\u0440\u0430\u0443\u0437\u0435\u0440. readable=true \u0444\u0438\u043B\u044C\u0442\u0440\u0443\u0435\u0442 \u0448\u0443\u043C (\u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u044F, \u0444\u0443\u0442\u0435\u0440\u044B, cookie-\u0431\u0430\u043D\u043D\u0435\u0440\u044B) \u0434\u043B\u044F \u0447\u0438\u0441\u0442\u043E\u0433\u043E \u043A\u043E\u043D\u0442\u0435\u043D\u0442\u0430. \u041F\u0440\u0438 \u043F\u043E\u0432\u0442\u043E\u0440\u043D\u044B\u0445 \u0432\u044B\u0437\u043E\u0432\u0430\u0445 \u0432\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 diff (\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F), \u0430 \u043D\u0435 \u043F\u043E\u043B\u043D\u044B\u0439 \u043A\u043E\u043D\u0442\u0435\u043D\u0442. \u041F\u0440\u0438\u043C\u0435\u0440: {url:"https://example.com", readable:true}.',
1234
1285
  inputSchema: {
1235
1286
  type: "object",
1236
1287
  properties: {
@@ -1238,11 +1289,6 @@ var VSL_TOOLS = [
1238
1289
  type: "string",
1239
1290
  description: "URL \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u044B \u0434\u043B\u044F \u0447\u0442\u0435\u043D\u0438\u044F"
1240
1291
  },
1241
- mode: {
1242
- type: "string",
1243
- enum: ["auto", "http", "render"],
1244
- description: "\u0420\u0435\u0436\u0438\u043C \u0447\u0442\u0435\u043D\u0438\u044F: auto (\u0430\u0432\u0442\u043E-\u0434\u0435\u0442\u0435\u043A\u0442), http (\u0442\u043E\u043B\u044C\u043A\u043E HTTP), render (\u0432\u0441\u0435\u0433\u0434\u0430 \u0440\u0435\u043D\u0434\u0435\u0440\u0438\u0442\u044C)"
1245
- },
1246
1292
  readable: {
1247
1293
  type: "boolean",
1248
1294
  description: "Readable-\u0440\u0435\u0436\u0438\u043C: \u0444\u0438\u043B\u044C\u0442\u0440\u0430\u0446\u0438\u044F \u0448\u0443\u043C\u0430 (nav, footer, cookie banners) \u0434\u043B\u044F \u0447\u0438\u0441\u0442\u043E\u0433\u043E \u043A\u043E\u043D\u0442\u0435\u043D\u0442\u0430"
@@ -1326,8 +1372,7 @@ function registerTools(server, config, browser, session) {
1326
1372
  result = await handleClearCache(session);
1327
1373
  break;
1328
1374
  case "vsl_get_visual":
1329
- result = await handleGetVisual(args, browser);
1330
- break;
1375
+ return await handleGetVisual(args, browser);
1331
1376
  case "vsl_read_page":
1332
1377
  result = await handleReadPage(args, browser, session, config);
1333
1378
  break;
@@ -1520,7 +1565,7 @@ var BrowserManager = class {
1520
1565
  const pw = await this.loadPlaywright();
1521
1566
  if (!pw) {
1522
1567
  throw new Error(
1523
- 'Playwright is not installed. Install it with: npm install playwright\nOr use vsl_read_page with mode="http" for static pages (no browser required).'
1568
+ "Playwright is not installed. Install it with: npm install playwright"
1524
1569
  );
1525
1570
  }
1526
1571
  this.browser = await pw.chromium.launch({
@@ -1689,6 +1734,48 @@ var BrowserManager = class {
1689
1734
  clearDownloads() {
1690
1735
  this.activeDownloads.clear();
1691
1736
  }
1737
+ /**
1738
+ * Загружает файлы в <input type="file"> по CSS-селектору.
1739
+ * Использует Playwright page.setInputFiles().
1740
+ * Валидирует пути: абсолютные используются напрямую, относительные разрешаются
1741
+ * относительно CWD с path traversal проверкой.
1742
+ * @param selector - CSS-селектор input[type=file] элемента
1743
+ * @param filePaths - Массив путей к файлам (абсолютные или относительные)
1744
+ * @throws Error если путь выходит за допустимые границы или файл не существует
1745
+ */
1746
+ async uploadFile(selector, filePaths) {
1747
+ const page = await this.getPage();
1748
+ if (filePaths.length === 0) {
1749
+ throw new Error("filePaths must contain at least one file path");
1750
+ }
1751
+ const resolvedPaths = [];
1752
+ for (const filePath of filePaths) {
1753
+ const isAbsolute = path2.isAbsolute(filePath);
1754
+ if (isAbsolute) {
1755
+ resolvedPaths.push(filePath);
1756
+ } else {
1757
+ const resolved = path2.resolve(process.cwd(), filePath);
1758
+ const cwd = path2.resolve(process.cwd());
1759
+ if (!resolved.startsWith(cwd + path2.sep) && resolved !== cwd) {
1760
+ throw new Error(`Path traversal detected: file path '${filePath}' resolves outside working directory '${cwd}'`);
1761
+ }
1762
+ resolvedPaths.push(resolved);
1763
+ }
1764
+ }
1765
+ await page.setInputFiles(selector, resolvedPaths.length === 1 ? resolvedPaths[0] : resolvedPaths);
1766
+ }
1767
+ /**
1768
+ * Ожидает появления file chooser dialog (для кастомных file picker'ов).
1769
+ * Возвращает FileChooser, через который можно установить файлы.
1770
+ * @param timeout - Таймаут ожидания в мс (по умолчанию из config.downloadTimeout)
1771
+ * @returns PlaywrightFileChooser для установки файлов
1772
+ */
1773
+ async waitForFileChooser(timeout) {
1774
+ const page = await this.getPage();
1775
+ const waitTimeout = timeout ?? this.config.downloadTimeout ?? 6e4;
1776
+ const fileChooser = await page.waitForEvent("filechooser", { timeout: waitTimeout });
1777
+ return fileChooser;
1778
+ }
1692
1779
  /**
1693
1780
  * Закрывает браузер и очищает ресурсы.
1694
1781
  */
@@ -1707,11 +1794,14 @@ var BrowserManager = class {
1707
1794
  };
1708
1795
 
1709
1796
  // src/session/serverSession.ts
1710
- import { diffVslDocuments } from "@thinkingos/vsl-sdk";
1797
+ import { VslSnapshotSession, diffVslDocuments } from "@thinkingos/vsl-sdk";
1711
1798
  var ServerSession = class {
1712
- currentSnapshot = null;
1713
- previousSnapshot = null;
1799
+ sdkSession;
1800
+ previousDocument = null;
1714
1801
  onSnapshotChange = null;
1802
+ constructor() {
1803
+ this.sdkSession = new VslSnapshotSession();
1804
+ }
1715
1805
  /**
1716
1806
  * Регистрирует callback для уведомлений об изменении snapshot.
1717
1807
  * Вызывается при каждом вызове setSnapshot().
@@ -1720,49 +1810,86 @@ var ServerSession = class {
1720
1810
  this.onSnapshotChange = callback;
1721
1811
  }
1722
1812
  /**
1723
- * Устанавливает новый snapshot.
1724
- * Предыдущий snapshot сохраняется для вычисления diff.
1725
- * Вызывает onSnapshotChange callback если зарегистрирован.
1813
+ * Устанавливает новый snapshot напрямую (VslDocument).
1814
+ * Для обратной совместимости с кодом, который уже имеет готовый VslDocument.
1815
+ * Предпочтительный способ: snapshotFromElements() для нового pipeline.
1726
1816
  */
1727
1817
  setSnapshot(doc) {
1728
- this.previousSnapshot = this.currentSnapshot;
1729
- this.currentSnapshot = doc;
1818
+ const currentDoc = this.sdkSession.getLastDocument();
1819
+ if (currentDoc) {
1820
+ this.previousDocument = currentDoc;
1821
+ }
1822
+ this.sdkSession.clear();
1823
+ this.sdkSession.lastDocument = doc;
1824
+ this.sdkSession.lastUrl = doc.canvas.url ?? null;
1825
+ this.sdkSession.lastViewport = {
1826
+ width: doc.canvas.viewport.width,
1827
+ height: doc.canvas.viewport.height
1828
+ };
1829
+ this.sdkSession.version = 1;
1730
1830
  if (this.onSnapshotChange) {
1731
1831
  this.onSnapshotChange();
1732
1832
  }
1733
1833
  }
1734
1834
  /**
1735
- * Возвращает текущий snapshot.
1835
+ * Делает snapshot из pre-extracted elements через SDK pipeline.
1836
+ * Это ПРЕДПОЧТИТЕЛЬНЫЙ способ — использует полный pipeline SDK:
1837
+ * segmentTree → buildVslDocument → cache → diff.
1838
+ */
1839
+ snapshotFromElements(extractedElements, input) {
1840
+ const result = this.sdkSession.snapshotFromElements(
1841
+ extractedElements,
1842
+ input
1843
+ );
1844
+ if (this.onSnapshotChange) {
1845
+ this.onSnapshotChange();
1846
+ }
1847
+ return result;
1848
+ }
1849
+ /**
1850
+ * Возвращает текущий snapshot (последний полный документ).
1736
1851
  * @throws Error если snapshot не установлен
1737
1852
  */
1738
1853
  getSnapshot() {
1739
- if (!this.currentSnapshot) {
1854
+ const doc = this.sdkSession.getLastDocument();
1855
+ if (!doc) {
1740
1856
  throw new Error("No snapshot available. Call vsl_get_snapshot first.");
1741
1857
  }
1742
- return this.currentSnapshot;
1858
+ return doc;
1743
1859
  }
1744
1860
  /**
1745
1861
  * Проверяет, есть ли текущий snapshot.
1746
1862
  */
1747
1863
  hasSnapshot() {
1748
- return this.currentSnapshot !== null;
1864
+ return this.sdkSession.getLastDocument() !== null;
1749
1865
  }
1750
1866
  /**
1751
1867
  * Вычисляет diff между текущим и предыдущим snapshot.
1868
+ * Использует SDK функцию diffVslDocuments.
1752
1869
  * @returns VslDiff или null если нет предыдущего snapshot
1753
1870
  */
1754
1871
  getDiff() {
1755
- if (!this.currentSnapshot || !this.previousSnapshot) {
1872
+ const currentDoc = this.sdkSession.getLastDocument();
1873
+ if (!currentDoc || !this.previousDocument) {
1756
1874
  return null;
1757
1875
  }
1758
- return diffVslDocuments(this.previousSnapshot, this.currentSnapshot, { diffVersion: 2, baseVersion: 1 });
1876
+ return diffVslDocuments(this.previousDocument, currentDoc, {
1877
+ diffVersion: this.sdkSession.getVersion() + 1,
1878
+ baseVersion: this.sdkSession.getVersion()
1879
+ });
1759
1880
  }
1760
1881
  /**
1761
1882
  * Сбрасывает сессию (кэш).
1762
1883
  */
1763
1884
  clear() {
1764
- this.currentSnapshot = null;
1765
- this.previousSnapshot = null;
1885
+ this.sdkSession.clear();
1886
+ }
1887
+ /**
1888
+ * Возвращает базовую VslSnapshotSession из SDK.
1889
+ * Для продвинутого использования (прямой доступ к SDK pipeline).
1890
+ */
1891
+ getSession() {
1892
+ return this.sdkSession;
1766
1893
  }
1767
1894
  };
1768
1895