@thinkingos/vsl-mcp-server 1.4.5 → 1.4.7

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
@@ -12,6 +12,12 @@ var __export = (target, all) => {
12
12
  // src/utils/domStabilization.ts
13
13
  async function waitForDomStable(target, options = {}) {
14
14
  const opts = { ...DEFAULT_DOM_STABILIZATION_OPTIONS, ...options };
15
+ if (opts.waitForNetworkIdle && typeof target.waitForLoadState === "function") {
16
+ try {
17
+ await target.waitForLoadState("networkidle", { timeout: opts.networkIdleTimeout });
18
+ } catch {
19
+ }
20
+ }
15
21
  await target.evaluate(
16
22
  ({ stablePeriod, pollInterval, timeout }) => {
17
23
  return new Promise((resolve) => {
@@ -498,6 +504,11 @@ async function injectVslIdsIntoFrame(browser, frame, objects, semanticMap = /* @
498
504
  }
499
505
 
500
506
  // src/utils/idMapper.ts
507
+ function computeIdSignature(obj) {
508
+ const txt = obj.txt ? obj.txt.slice(0, 64) : "";
509
+ const act = obj.act ? obj.act.join(",") : "";
510
+ return `${obj.t ?? ""}|${obj.r ?? ""}|${txt}|${act}`;
511
+ }
501
512
  var TAG_PREFIXES = {
502
513
  button: "btn",
503
514
  input: "inp",
@@ -556,9 +567,9 @@ function extractTag(longId) {
556
567
  function toBase36(n) {
557
568
  return n.toString(36);
558
569
  }
559
- function buildIdMap(objects, previousReverseIdMap) {
570
+ function buildIdMap(objects, previousReverseIdMap, state) {
560
571
  const map = /* @__PURE__ */ new Map();
561
- const counters = /* @__PURE__ */ new Map();
572
+ const counters = state?.counters ?? /* @__PURE__ */ new Map();
562
573
  const assignedShortIds = /* @__PURE__ */ new Set();
563
574
  const elementsWithPrefix = [];
564
575
  function collect(obj, framePrefix) {
@@ -585,14 +596,22 @@ function buildIdMap(objects, previousReverseIdMap) {
585
596
  if (oldShortId && !assignedShortIds.has(oldShortId)) {
586
597
  const expectedPrefix = framePrefix ? `${framePrefix}:` : "";
587
598
  if (oldShortId.startsWith(expectedPrefix) || !framePrefix && !oldShortId.includes(":")) {
588
- map.set(oldShortId, obj.id);
589
- assignedShortIds.add(oldShortId);
599
+ if (state?.signatures) {
600
+ const oldSignature = state.signatures.get(obj.id);
601
+ const newSignature = computeIdSignature(obj);
602
+ if (oldSignature === newSignature) {
603
+ map.set(oldShortId, obj.id);
604
+ assignedShortIds.add(oldShortId);
605
+ }
606
+ } else {
607
+ map.set(oldShortId, obj.id);
608
+ assignedShortIds.add(oldShortId);
609
+ }
590
610
  }
591
611
  }
592
612
  }
593
613
  }
594
614
  for (const { obj, framePrefix } of elementsWithPrefix) {
595
- if (map.has(framePrefix ? `${framePrefix}:${obj.id}` : obj.id)) continue;
596
615
  const alreadyAssigned = Array.from(map.entries()).some(([_, longId]) => longId === obj.id);
597
616
  if (alreadyAssigned) continue;
598
617
  const tag = extractTag(obj.id);
@@ -606,17 +625,12 @@ function buildIdMap(objects, previousReverseIdMap) {
606
625
  counters.set(prefix, counter);
607
626
  assignedShortIds.add(shortId);
608
627
  map.set(shortId, obj.id);
628
+ if (state?.signatures) {
629
+ state.signatures.set(obj.id, computeIdSignature(obj));
630
+ }
609
631
  }
610
632
  return map;
611
633
  }
612
- function buildReverseIdMap(objects, previousReverseIdMap) {
613
- const forward = buildIdMap(objects, previousReverseIdMap);
614
- const reverse = /* @__PURE__ */ new Map();
615
- for (const [shortId, longId] of forward) {
616
- reverse.set(longId, shortId);
617
- }
618
- return reverse;
619
- }
620
634
  function replaceIdsInDocument(document2, longToShort) {
621
635
  if (!document2.objects) return document2;
622
636
  function replaceObj(obj) {
@@ -664,7 +678,10 @@ function replaceIdsInModifiedObject(obj, reverseIdMap) {
664
678
  if (obj.p !== void 0) result.p = obj.p;
665
679
  if (obj.s !== void 0) result.s = obj.s;
666
680
  if (obj.t !== void 0) result.t = obj.t;
681
+ if (obj.r !== void 0) result.r = obj.r;
682
+ if (obj.st !== void 0) result.st = obj.st;
667
683
  if (obj.txt !== void 0) result.txt = obj.txt;
684
+ if (obj.val !== void 0) result.val = obj.val;
668
685
  if (obj.act !== void 0) result.act = obj.act;
669
686
  return result;
670
687
  }
@@ -941,6 +958,13 @@ function extractDomTreeInBrowser() {
941
958
  }
942
959
  return raw.replace(/\s+/g, " ").trim();
943
960
  }
961
+ function readFieldValue(el) {
962
+ const tag = el.tagName.toLowerCase();
963
+ if (tag !== "input" && tag !== "textarea" && tag !== "select") return null;
964
+ const type = el.type?.toLowerCase() || "";
965
+ if (type === "password" || type === "checkbox" || type === "radio" || type === "file") return null;
966
+ return el.value || null;
967
+ }
944
968
  function extractAttributes(el) {
945
969
  const attributes = {};
946
970
  for (const attr of Array.from(el.attributes)) {
@@ -1013,6 +1037,7 @@ function extractDomTreeInBrowser() {
1013
1037
  indexPath: path3,
1014
1038
  rect,
1015
1039
  text: ownText(child) || null,
1040
+ value: readFieldValue(child),
1016
1041
  attributes,
1017
1042
  css,
1018
1043
  children,
@@ -2291,7 +2316,7 @@ async function handleExecuteAction(args, browser, session, sessionId) {
2291
2316
  if (!args.value) {
2292
2317
  return {
2293
2318
  status: "error",
2294
- error: "value is required for type action"
2319
+ error: 'value is required for type/fill action (use action "clear" to empty a field)'
2295
2320
  };
2296
2321
  }
2297
2322
  if (humanization.enabled && !targetFrame) {
@@ -2395,17 +2420,7 @@ async function handleExecuteAction(args, browser, session, sessionId) {
2395
2420
  error: "value is required for select action"
2396
2421
  };
2397
2422
  }
2398
- if (targetFrame) {
2399
- await browser.evaluateInFrame(targetFrame, ({ sel, val }) => {
2400
- const el = document.querySelector(sel);
2401
- if (el) el.value = val;
2402
- }, sessionId, { sel: selector, val: args.value });
2403
- } else {
2404
- await browser.evaluate(({ sel, val }) => {
2405
- const el = document.querySelector(sel);
2406
- if (el) el.value = val;
2407
- }, sessionId, { sel: selector, val: args.value });
2408
- }
2423
+ await target.locator(selector).selectOption(args.value, { timeout: 1e3 });
2409
2424
  break;
2410
2425
  case "hover":
2411
2426
  if (humanization.enabled && !targetFrame) {
@@ -2634,25 +2649,7 @@ async function handleExecuteAction(args, browser, session, sessionId) {
2634
2649
  return result2;
2635
2650
  }
2636
2651
  case "clear": {
2637
- if (targetFrame) {
2638
- await browser.evaluateInFrame(targetFrame, (sel) => {
2639
- const el = document.querySelector(sel);
2640
- if (el) {
2641
- el.value = "";
2642
- el.dispatchEvent(new Event("input", { bubbles: true }));
2643
- el.dispatchEvent(new Event("change", { bubbles: true }));
2644
- }
2645
- }, sessionId, selector);
2646
- } else {
2647
- await browser.evaluate((sel) => {
2648
- const el = document.querySelector(sel);
2649
- if (el) {
2650
- el.value = "";
2651
- el.dispatchEvent(new Event("input", { bubbles: true }));
2652
- el.dispatchEvent(new Event("change", { bubbles: true }));
2653
- }
2654
- }, sessionId, selector);
2655
- }
2652
+ await target.locator(selector).fill("", { timeout: 1e3 });
2656
2653
  break;
2657
2654
  }
2658
2655
  case "drag": {
@@ -2940,7 +2937,7 @@ async function handleExecuteAction(args, browser, session, sessionId) {
2940
2937
  if (navigationOccurred || contextDestroyed) {
2941
2938
  try {
2942
2939
  await page.waitForLoadState("domcontentloaded", { timeout: 5e3 });
2943
- await waitForDomStabilization(page, { waitForNetworkIdle: true, timeout: 2e3 });
2940
+ await waitForDomStabilization(page, { waitForNetworkIdle: true, timeout: 5e3, stablePeriod: 300, networkIdleTimeout: 2e3 });
2944
2941
  } catch (waitError) {
2945
2942
  console.warn("[vsl_execute_action] Navigation detected but waitForLoadState failed:", waitError);
2946
2943
  }
@@ -3549,18 +3546,26 @@ async function handleReadPage(args, browser, session, _config, sessionId) {
3549
3546
  error: "readable must be a boolean (true or false)"
3550
3547
  };
3551
3548
  }
3549
+ if (args.use_browser !== void 0 && typeof args.use_browser !== "boolean") {
3550
+ return {
3551
+ status: "error",
3552
+ error: "use_browser must be a boolean (true or false)"
3553
+ };
3554
+ }
3552
3555
  const detailLevel = args.detail_level || "medium";
3553
3556
  try {
3554
3557
  const readable = args.readable ?? false;
3555
- let detectedMode = "http";
3558
+ let detectedMode = args.use_browser === true ? "render" : "http";
3556
3559
  let httpResult = null;
3557
- try {
3558
- httpResult = await extractViaHttp(args.url, { readable });
3559
- if (httpResult.isSpa) {
3560
+ if (args.use_browser !== true) {
3561
+ try {
3562
+ httpResult = await extractViaHttp(args.url, { readable });
3563
+ if (httpResult.isSpa) {
3564
+ detectedMode = "render";
3565
+ }
3566
+ } catch {
3560
3567
  detectedMode = "render";
3561
3568
  }
3562
- } catch {
3563
- detectedMode = "render";
3564
3569
  }
3565
3570
  if (detectedMode === "render") {
3566
3571
  const isAvailable = await browser.isAvailable();
@@ -4234,28 +4239,8 @@ var BrowserManager = class {
4234
4239
  "Playwright is not installed. Install it with: npm install playwright"
4235
4240
  );
4236
4241
  }
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
- }
4242
+ if (options?.skipCdpConnect !== true && await this.tryConnectCdp()) {
4243
+ return;
4259
4244
  }
4260
4245
  const userDataDir = this.getProfileDir();
4261
4246
  const effectiveHeadless = options?.headless ?? this.config.headless;
@@ -4300,6 +4285,65 @@ var BrowserManager = class {
4300
4285
  }
4301
4286
  this.currentHeadless = effectiveHeadless;
4302
4287
  this.browser = null;
4288
+ if (this.context) {
4289
+ this.watchContextClose(this.context);
4290
+ }
4291
+ }
4292
+ /**
4293
+ * Пробует подключиться к уже запущенному браузеру по CDP (CDP-first).
4294
+ * Возвращает true, если подключение удалось и контекст получен.
4295
+ * Вынесено из launch(), чтобы ensureHeaded() мог сначала проверить внешний браузер
4296
+ * (например РЕАЛЬНЫЙ Chrome пользователя) и не поднимать второй браузер на том же профиле.
4297
+ */
4298
+ async tryConnectCdp() {
4299
+ if (!this.config.cdpPort) return false;
4300
+ const pw = await this.loadPlaywright();
4301
+ if (!pw) return false;
4302
+ try {
4303
+ this.browser = await pw.chromium.connectOverCDP({
4304
+ endpointURL: `http://localhost:${this.config.cdpPort}`
4305
+ });
4306
+ this.connectedViaCDP = true;
4307
+ this.currentHeadless = null;
4308
+ const contexts = this.browser.contexts();
4309
+ if (contexts.length > 0 && contexts[0]) {
4310
+ this.context = contexts[0];
4311
+ } else {
4312
+ const contextOptions = {
4313
+ acceptDownloads: this.config.acceptDownloads ?? true
4314
+ };
4315
+ if (this.config.downloadsPath) {
4316
+ contextOptions.downloadsPath = this.config.downloadsPath;
4317
+ }
4318
+ this.context = await this.browser.newContext(contextOptions);
4319
+ }
4320
+ if (this.context) {
4321
+ this.watchContextClose(this.context);
4322
+ }
4323
+ return true;
4324
+ } catch {
4325
+ this.browser = null;
4326
+ this.context = null;
4327
+ this.connectedViaCDP = false;
4328
+ this.currentHeadless = null;
4329
+ return false;
4330
+ }
4331
+ }
4332
+ /**
4333
+ * Сбрасывает состояние менеджера при закрытии контекста/браузера ИЗВНЕ.
4334
+ * Без этого мёртвый persistent-контекст считается живым (ранний выход launch()),
4335
+ * и процесс не переподключается к новому браузеру без перезапуска MCP-сервера.
4336
+ * @param context - контекст, за которым следим
4337
+ */
4338
+ watchContextClose(context) {
4339
+ context.on("close", () => {
4340
+ if (this.context !== context) return;
4341
+ this.context = null;
4342
+ this.browser = null;
4343
+ this.pages.clear();
4344
+ this.connectedViaCDP = false;
4345
+ this.currentHeadless = null;
4346
+ });
4303
4347
  }
4304
4348
  /**
4305
4349
  * Запускает persistent context с восстановлением отсутствующего бинарника браузера.
@@ -4424,8 +4468,56 @@ var BrowserManager = class {
4424
4468
  const page = await this.getPage(sessionId);
4425
4469
  return await page.evaluate(() => navigator.userAgent);
4426
4470
  }
4471
+ /**
4472
+ * Возвращает АВТОРИТЕТНЫЙ product браузера через CDP Browser.getVersion.
4473
+ * UA страницы (getBrowserUserAgent) подменяется stealth-плагином
4474
+ * (puppeteer-extra-plugin-stealth, evasion user-agent-override) в новых CDP-контекстах
4475
+ * и теряет подстроку 'HeadlessChrome' — для детекции режима окна он не годится.
4476
+ * @param sessionId - ID сессии
4477
+ */
4478
+ async getBrowserProduct(sessionId) {
4479
+ const page = await this.getPage(sessionId);
4480
+ if (!this.context) {
4481
+ throw new Error("Browser not available");
4482
+ }
4483
+ const cdp = await this.context.newCDPSession(page);
4484
+ try {
4485
+ const info = await cdp.send("Browser.getVersion");
4486
+ return typeof info?.product === "string" ? info.product : "";
4487
+ } finally {
4488
+ try {
4489
+ await cdp.detach();
4490
+ } catch (error) {
4491
+ console.error(
4492
+ "[BrowserManager] CDP session detach failed:",
4493
+ error instanceof Error ? error.message : String(error)
4494
+ );
4495
+ }
4496
+ }
4497
+ }
4498
+ /**
4499
+ * Определяет, headless ли браузер, по авторитетному CDP product (Browser.getVersion).
4500
+ * Фолбэк на UA страницы — только если CDP-команда недоступна.
4501
+ * @param sessionId - ID сессии
4502
+ */
4503
+ async isHeadlessBrowser(sessionId) {
4504
+ try {
4505
+ const product = await this.getBrowserProduct(sessionId);
4506
+ if (product) return isHeadlessUserAgent(product);
4507
+ } catch (error) {
4508
+ console.error(
4509
+ "[BrowserManager] CDP Browser.getVersion unavailable, falling back to page User-Agent:",
4510
+ error instanceof Error ? error.message : String(error)
4511
+ );
4512
+ }
4513
+ return isHeadlessUserAgent(await this.getBrowserUserAgent(sessionId));
4514
+ }
4427
4515
  /**
4428
4516
  * Приводит браузер к ВИДИМОМУ окну на том же профиле (R7).
4517
+ * CDP-first: если на cdpPort уже жив браузер (в том числе РЕАЛЬНЫЙ Chrome пользователя),
4518
+ * подключаемся к нему и НЕ поднимаем второй браузер на том же профиле.
4519
+ * Режим окна внешнего браузера определяется АВТОРИТЕТНО через CDP Browser.getVersion,
4520
+ * а не по UA страницы (его подменяет stealth-плагин).
4429
4521
  * Свой headless-контекст перезапускается, внешний видимый Chrome не трогается,
4430
4522
  * headless-браузер VSL по CDP закрывается только при явном takeover:true.
4431
4523
  * @param sessionId - ID сессии
@@ -4433,12 +4525,14 @@ var BrowserManager = class {
4433
4525
  */
4434
4526
  async ensureHeaded(sessionId, options) {
4435
4527
  if (!this.context) {
4436
- await this.launch({ headless: false, skipCdpConnect: true });
4437
- return { restarted: true, mode: "headed" };
4528
+ const connected = await this.tryConnectCdp();
4529
+ if (!connected) {
4530
+ await this.launch({ headless: false, skipCdpConnect: true });
4531
+ return { restarted: true, mode: "headed" };
4532
+ }
4438
4533
  }
4439
4534
  if (this.connectedViaCDP) {
4440
- const ua = await this.getBrowserUserAgent(sessionId);
4441
- if (!isHeadlessUserAgent(ua)) {
4535
+ if (!await this.isHeadlessBrowser(sessionId)) {
4442
4536
  return { restarted: false, mode: "cdp" };
4443
4537
  }
4444
4538
  if (options?.takeover !== true) {
@@ -4942,7 +5036,7 @@ async function handleManualLogin(args, browser, _session, sessionManager, config
4942
5036
  cookie_count: cookieCount,
4943
5037
  matched,
4944
5038
  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."
5039
+ instructions: "Manual login finished. Cookies and localStorage are stored in the VSL browser profile, so all BROWSER tools (vsl_navigate, vsl_get_snapshot, vsl_execute_action, vsl_get_visual, vsl_click_coordinates) in all sessions are signed in. IMPORTANT: vsl_read_page is NOT signed in by default \u2014 its HTTP path sends no cookies and reads as an anonymous visitor; call vsl_read_page with {use_browser:true} to read as the signed-in user (the actual path is reported in data.mode)."
4946
5040
  };
4947
5041
  const result = {
4948
5042
  status: "success",
@@ -4975,7 +5069,7 @@ async function handleManualLogin(args, browser, _session, sessionManager, config
4975
5069
  var VSL_TOOLS = [
4976
5070
  {
4977
5071
  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.",
5072
+ 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. BROWSER tool: reads the live page in the VSL browser, so the signed-in profile cookies apply (unlike the default HTTP path of vsl_read_page).",
4979
5073
  inputSchema: {
4980
5074
  type: "object",
4981
5075
  properties: {
@@ -5001,13 +5095,13 @@ var VSL_TOOLS = [
5001
5095
  },
5002
5096
  {
5003
5097
  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.',
5098
+ 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: ${VALID_ACTIONS.join(", ")}. BROWSER tool: acts in the VSL browser with the signed-in profile cookies.`,
5005
5099
  inputSchema: {
5006
5100
  type: "object",
5007
5101
  properties: {
5008
5102
  action: {
5009
5103
  type: "string",
5010
- description: "Action name (click, type, fill, scroll, select, etc.)"
5104
+ description: `Action name (${VALID_ACTIONS.join(", ")}). Note: fill is an alias for type and requires a non-empty value; use action "clear" to empty a field.`
5011
5105
  },
5012
5106
  target_id: {
5013
5107
  type: "string",
@@ -5019,7 +5113,7 @@ var VSL_TOOLS = [
5019
5113
  },
5020
5114
  return_state: {
5021
5115
  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."
5116
+ 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
5117
  },
5024
5118
  timeout: {
5025
5119
  type: "number",
@@ -5057,7 +5151,7 @@ var VSL_TOOLS = [
5057
5151
  },
5058
5152
  {
5059
5153
  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.",
5154
+ 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. BROWSER tool: screenshots the live page in the VSL browser with the signed-in profile cookies.",
5061
5155
  inputSchema: {
5062
5156
  type: "object",
5063
5157
  properties: {
@@ -5075,7 +5169,7 @@ var VSL_TOOLS = [
5075
5169
  },
5076
5170
  {
5077
5171
  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.',
5172
+ description: 'Read web pages. TWO PATHS: (1) HTTP path (default, fast) \u2014 a plain Node fetch WITHOUT the browser: it sends NO cookies, so it reads as an ANONYMOUS visitor (the user sign-in is NOT used) and the visible browser tab does NOT change; (2) BROWSER path \u2014 renders the page in the VSL browser using the signed-in profile cookies, and the page really opens in the agent tab. By default the strategy is automatic: static pages go via HTTP, SPAs are rendered via browser, and a failed HTTP request (403/404/timeout) falls back to the browser. Set use_browser=true to FORCE the browser path \u2014 required for pages that need sign-in (after vsl_manual_login) or when the user should see the navigation. The response contains data.mode ("http" or "render") \u2014 check it to know which path was actually used. 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"} or {url:"https://example.com/account", use_browser:true}. Returns snapshot and diff automatically.',
5079
5173
  inputSchema: {
5080
5174
  type: "object",
5081
5175
  properties: {
@@ -5086,6 +5180,15 @@ var VSL_TOOLS = [
5086
5180
  readable: {
5087
5181
  type: "boolean",
5088
5182
  description: "Readable mode: filter noise (nav, footer, cookie banners) for clean content"
5183
+ },
5184
+ detail_level: {
5185
+ type: "string",
5186
+ enum: ["low", "medium", "high"],
5187
+ description: "Snapshot detail level (default medium): low \u2014 interactive elements only, medium \u2014 interactive + containers, high \u2014 all objects"
5188
+ },
5189
+ use_browser: {
5190
+ type: "boolean",
5191
+ description: "Force the BROWSER path (default false). true \u2014 render the page in the VSL browser with the signed-in profile cookies (the page opens in the agent tab) and skip the HTTP request entirely. Use it for pages that require sign-in or when the user must see the navigation. Without it the HTTP path is used when possible: NO cookies (anonymous) and NO change in the visible browser tab."
5089
5192
  }
5090
5193
  },
5091
5194
  required: ["url"]
@@ -5138,7 +5241,7 @@ var VSL_TOOLS = [
5138
5241
  },
5139
5242
  {
5140
5243
  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"}.',
5244
+ 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 BROWSER tools (vsl_navigate, vsl_get_snapshot, vsl_execute_action, vsl_get_visual, vsl_click_coordinates) in all sessions are signed in after the user logs in. IMPORTANT: vsl_read_page is NOT signed in by default \u2014 its HTTP path sends no cookies and reads as an anonymous visitor; call vsl_read_page with {use_browser:true} to read as the signed-in user. Example: {action: "open", url: "https://example.com/login"}.',
5142
5245
  inputSchema: {
5143
5246
  type: "object",
5144
5247
  properties: {
@@ -5375,6 +5478,17 @@ function registerResources(server, _config, sessionManager) {
5375
5478
 
5376
5479
  // src/session/serverSession.ts
5377
5480
  import { diffVslDocuments, segmentTree, buildVslDocument } from "@thinkingos/vsl-sdk";
5481
+ function collectLongIds(objects, into) {
5482
+ for (const obj of objects) {
5483
+ into.add(obj.id);
5484
+ if (obj.ch) {
5485
+ collectLongIds(obj.ch, into);
5486
+ }
5487
+ if (obj.iframe?.vsl?.objects) {
5488
+ collectLongIds(obj.iframe.vsl.objects, into);
5489
+ }
5490
+ }
5491
+ }
5378
5492
  var ServerSession = class {
5379
5493
  currentDocument = null;
5380
5494
  previousDocument = null;
@@ -5386,6 +5500,8 @@ var ServerSession = class {
5386
5500
  idMap = /* @__PURE__ */ new Map();
5387
5501
  /** Обратная карта longId → shortId для замены ID в выдаче LLM. */
5388
5502
  reverseIdMap = /* @__PURE__ */ new Map();
5503
+ /** Состояние маппера ID для сохранения идентичности коротких ID между снапшотами (E5/D5). */
5504
+ idMapperState = { signatures: /* @__PURE__ */ new Map(), counters: /* @__PURE__ */ new Map() };
5389
5505
  /**
5390
5506
  * Регистрирует callback для уведомлений об изменении snapshot.
5391
5507
  * Вызывается при каждом вызове setSnapshot().
@@ -5406,16 +5522,9 @@ var ServerSession = class {
5406
5522
  this.scrollContext = null;
5407
5523
  const currentObjects = doc.objects ?? [];
5408
5524
  const previousObjects = this.previousDocument?.objects ?? [];
5409
- const unionObjects = [...currentObjects, ...previousObjects];
5410
- if (currentObjects.length > 0) {
5411
- this.idMap = buildIdMap(currentObjects);
5412
- } else {
5413
- this.idMap = /* @__PURE__ */ new Map();
5414
- }
5415
- if (unionObjects.length > 0) {
5416
- this.reverseIdMap = buildReverseIdMap(unionObjects);
5417
- } else {
5418
- this.reverseIdMap = /* @__PURE__ */ new Map();
5525
+ this.buildMaps(currentObjects, previousObjects, this.idMapperState);
5526
+ for (const obj of currentObjects) {
5527
+ this.updateIdSignature(obj);
5419
5528
  }
5420
5529
  if (this.onSnapshotChange) {
5421
5530
  this.onSnapshotChange();
@@ -5440,20 +5549,9 @@ var ServerSession = class {
5440
5549
  this.currentDocument = doc;
5441
5550
  this.version += 1;
5442
5551
  this.scrollContext = input.scroll ? { ...input.scroll } : null;
5443
- const prevReverseIdMap = this.reverseIdMap;
5444
5552
  const currentObjects = doc.objects ?? [];
5445
5553
  const previousObjects = this.previousDocument?.objects ?? [];
5446
- const unionObjects = [...currentObjects, ...previousObjects];
5447
- if (currentObjects.length > 0) {
5448
- this.idMap = buildIdMap(currentObjects, prevReverseIdMap);
5449
- } else {
5450
- this.idMap = /* @__PURE__ */ new Map();
5451
- }
5452
- if (unionObjects.length > 0) {
5453
- this.reverseIdMap = buildReverseIdMap(unionObjects, prevReverseIdMap);
5454
- } else {
5455
- this.reverseIdMap = /* @__PURE__ */ new Map();
5456
- }
5554
+ this.buildMaps(currentObjects, previousObjects);
5457
5555
  if (this.onSnapshotChange) {
5458
5556
  this.onSnapshotChange();
5459
5557
  }
@@ -5512,6 +5610,7 @@ var ServerSession = class {
5512
5610
  this.scrollContext = null;
5513
5611
  this.idMap = /* @__PURE__ */ new Map();
5514
5612
  this.reverseIdMap = /* @__PURE__ */ new Map();
5613
+ this.idMapperState = { signatures: /* @__PURE__ */ new Map(), counters: /* @__PURE__ */ new Map() };
5515
5614
  }
5516
5615
  /**
5517
5616
  * Возвращает текущую версию snapshot.
@@ -5547,6 +5646,46 @@ var ServerSession = class {
5547
5646
  getReverseIdMap() {
5548
5647
  return this.reverseIdMap;
5549
5648
  }
5649
+ /**
5650
+ * Вычисляет и сохраняет подпись идентичности для объекта в состоянии маппера.
5651
+ * Используется для детекции семантических изменений элемента между снапшотами.
5652
+ */
5653
+ updateIdSignature(obj) {
5654
+ this.idMapperState.signatures.set(obj.id, computeIdSignature(obj));
5655
+ }
5656
+ /**
5657
+ * Строит ОБЕ карты маппинга ID за ОДНУ аллокацию коротких ID.
5658
+ *
5659
+ * Аллокация идёт по union (current + previous): текущие объекты первыми
5660
+ * получают младшие счётчики, удалённые объекты из previous — следом либо
5661
+ * восстанавливают прежние ID из предыдущей reverse-карты.
5662
+ * idMap (short→long) — только объекты текущего документа (резолвинг ID агента),
5663
+ * reverseIdMap (long→short) — весь union (короткие ID для removed/unchanged_refs).
5664
+ *
5665
+ * Один вызов buildIdMap вместо двух обязателен: два вызова с общим
5666
+ * state.counters давали расхождение карт (btn_0 в idMap против btn_1 в
5667
+ * reverseIdMap), так как первый вызов уже поднимал монотонные счётчики.
5668
+ */
5669
+ buildMaps(currentObjects, previousObjects, state) {
5670
+ if (currentObjects.length === 0 && previousObjects.length === 0) {
5671
+ this.idMap = /* @__PURE__ */ new Map();
5672
+ this.reverseIdMap = /* @__PURE__ */ new Map();
5673
+ return;
5674
+ }
5675
+ const forward = buildIdMap([...currentObjects, ...previousObjects], this.reverseIdMap, state);
5676
+ const currentLongIds = /* @__PURE__ */ new Set();
5677
+ collectLongIds(currentObjects, currentLongIds);
5678
+ const idMap = /* @__PURE__ */ new Map();
5679
+ const reverseIdMap = /* @__PURE__ */ new Map();
5680
+ for (const [shortId, longId] of forward) {
5681
+ reverseIdMap.set(longId, shortId);
5682
+ if (currentLongIds.has(longId)) {
5683
+ idMap.set(shortId, longId);
5684
+ }
5685
+ }
5686
+ this.idMap = idMap;
5687
+ this.reverseIdMap = reverseIdMap;
5688
+ }
5550
5689
  /**
5551
5690
  * Перестраивает карты маппинга ID (idMap и reverseIdMap) на основе текущего документа.
5552
5691
  * Используется после добавления iframe объектов в currentDoc.objects,
@@ -5560,16 +5699,9 @@ var ServerSession = class {
5560
5699
  if (!this.currentDocument) return;
5561
5700
  const currentObjects = this.currentDocument.objects ?? [];
5562
5701
  const previousObjects = this.previousDocument?.objects ?? [];
5563
- const unionObjects = [...currentObjects, ...previousObjects];
5564
- if (currentObjects.length > 0) {
5565
- this.idMap = buildIdMap(currentObjects);
5566
- } else {
5567
- this.idMap = /* @__PURE__ */ new Map();
5568
- }
5569
- if (unionObjects.length > 0) {
5570
- this.reverseIdMap = buildReverseIdMap(unionObjects);
5571
- } else {
5572
- this.reverseIdMap = /* @__PURE__ */ new Map();
5702
+ this.buildMaps(currentObjects, previousObjects, this.idMapperState);
5703
+ for (const obj of currentObjects) {
5704
+ this.updateIdSignature(obj);
5573
5705
  }
5574
5706
  }
5575
5707
  };
@@ -5727,7 +5859,7 @@ var SessionManager = class {
5727
5859
  };
5728
5860
 
5729
5861
  // src/version.ts
5730
- var VSL_MCP_SERVER_VERSION = "1.4.5";
5862
+ var VSL_MCP_SERVER_VERSION = "1.4.7";
5731
5863
 
5732
5864
  // src/index.ts
5733
5865
  async function main() {