@thinkingos/vsl-mcp-server 1.4.6 → 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();
@@ -5031,7 +5036,7 @@ async function handleManualLogin(args, browser, _session, sessionManager, config
5031
5036
  cookie_count: cookieCount,
5032
5037
  matched,
5033
5038
  waiting: false,
5034
- 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)."
5035
5040
  };
5036
5041
  const result = {
5037
5042
  status: "success",
@@ -5064,7 +5069,7 @@ async function handleManualLogin(args, browser, _session, sessionManager, config
5064
5069
  var VSL_TOOLS = [
5065
5070
  {
5066
5071
  name: "vsl_get_snapshot",
5067
- 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).",
5068
5073
  inputSchema: {
5069
5074
  type: "object",
5070
5075
  properties: {
@@ -5090,13 +5095,13 @@ var VSL_TOOLS = [
5090
5095
  },
5091
5096
  {
5092
5097
  name: "vsl_execute_action",
5093
- 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.`,
5094
5099
  inputSchema: {
5095
5100
  type: "object",
5096
5101
  properties: {
5097
5102
  action: {
5098
5103
  type: "string",
5099
- 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.`
5100
5105
  },
5101
5106
  target_id: {
5102
5107
  type: "string",
@@ -5146,7 +5151,7 @@ var VSL_TOOLS = [
5146
5151
  },
5147
5152
  {
5148
5153
  name: "vsl_get_visual",
5149
- 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.",
5150
5155
  inputSchema: {
5151
5156
  type: "object",
5152
5157
  properties: {
@@ -5164,7 +5169,7 @@ var VSL_TOOLS = [
5164
5169
  },
5165
5170
  {
5166
5171
  name: "vsl_read_page",
5167
- 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.',
5168
5173
  inputSchema: {
5169
5174
  type: "object",
5170
5175
  properties: {
@@ -5175,6 +5180,15 @@ var VSL_TOOLS = [
5175
5180
  readable: {
5176
5181
  type: "boolean",
5177
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."
5178
5192
  }
5179
5193
  },
5180
5194
  required: ["url"]
@@ -5227,7 +5241,7 @@ var VSL_TOOLS = [
5227
5241
  },
5228
5242
  {
5229
5243
  name: "vsl_manual_login",
5230
- 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"}.',
5231
5245
  inputSchema: {
5232
5246
  type: "object",
5233
5247
  properties: {
@@ -5464,6 +5478,17 @@ function registerResources(server, _config, sessionManager) {
5464
5478
 
5465
5479
  // src/session/serverSession.ts
5466
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
+ }
5467
5492
  var ServerSession = class {
5468
5493
  currentDocument = null;
5469
5494
  previousDocument = null;
@@ -5475,6 +5500,8 @@ var ServerSession = class {
5475
5500
  idMap = /* @__PURE__ */ new Map();
5476
5501
  /** Обратная карта longId → shortId для замены ID в выдаче LLM. */
5477
5502
  reverseIdMap = /* @__PURE__ */ new Map();
5503
+ /** Состояние маппера ID для сохранения идентичности коротких ID между снапшотами (E5/D5). */
5504
+ idMapperState = { signatures: /* @__PURE__ */ new Map(), counters: /* @__PURE__ */ new Map() };
5478
5505
  /**
5479
5506
  * Регистрирует callback для уведомлений об изменении snapshot.
5480
5507
  * Вызывается при каждом вызове setSnapshot().
@@ -5495,16 +5522,9 @@ var ServerSession = class {
5495
5522
  this.scrollContext = null;
5496
5523
  const currentObjects = doc.objects ?? [];
5497
5524
  const previousObjects = this.previousDocument?.objects ?? [];
5498
- const unionObjects = [...currentObjects, ...previousObjects];
5499
- if (currentObjects.length > 0) {
5500
- this.idMap = buildIdMap(currentObjects);
5501
- } else {
5502
- this.idMap = /* @__PURE__ */ new Map();
5503
- }
5504
- if (unionObjects.length > 0) {
5505
- this.reverseIdMap = buildReverseIdMap(unionObjects);
5506
- } else {
5507
- this.reverseIdMap = /* @__PURE__ */ new Map();
5525
+ this.buildMaps(currentObjects, previousObjects, this.idMapperState);
5526
+ for (const obj of currentObjects) {
5527
+ this.updateIdSignature(obj);
5508
5528
  }
5509
5529
  if (this.onSnapshotChange) {
5510
5530
  this.onSnapshotChange();
@@ -5529,20 +5549,9 @@ var ServerSession = class {
5529
5549
  this.currentDocument = doc;
5530
5550
  this.version += 1;
5531
5551
  this.scrollContext = input.scroll ? { ...input.scroll } : null;
5532
- const prevReverseIdMap = this.reverseIdMap;
5533
5552
  const currentObjects = doc.objects ?? [];
5534
5553
  const previousObjects = this.previousDocument?.objects ?? [];
5535
- const unionObjects = [...currentObjects, ...previousObjects];
5536
- if (currentObjects.length > 0) {
5537
- this.idMap = buildIdMap(currentObjects, prevReverseIdMap);
5538
- } else {
5539
- this.idMap = /* @__PURE__ */ new Map();
5540
- }
5541
- if (unionObjects.length > 0) {
5542
- this.reverseIdMap = buildReverseIdMap(unionObjects, prevReverseIdMap);
5543
- } else {
5544
- this.reverseIdMap = /* @__PURE__ */ new Map();
5545
- }
5554
+ this.buildMaps(currentObjects, previousObjects);
5546
5555
  if (this.onSnapshotChange) {
5547
5556
  this.onSnapshotChange();
5548
5557
  }
@@ -5601,6 +5610,7 @@ var ServerSession = class {
5601
5610
  this.scrollContext = null;
5602
5611
  this.idMap = /* @__PURE__ */ new Map();
5603
5612
  this.reverseIdMap = /* @__PURE__ */ new Map();
5613
+ this.idMapperState = { signatures: /* @__PURE__ */ new Map(), counters: /* @__PURE__ */ new Map() };
5604
5614
  }
5605
5615
  /**
5606
5616
  * Возвращает текущую версию snapshot.
@@ -5636,6 +5646,46 @@ var ServerSession = class {
5636
5646
  getReverseIdMap() {
5637
5647
  return this.reverseIdMap;
5638
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
+ }
5639
5689
  /**
5640
5690
  * Перестраивает карты маппинга ID (idMap и reverseIdMap) на основе текущего документа.
5641
5691
  * Используется после добавления iframe объектов в currentDoc.objects,
@@ -5649,16 +5699,9 @@ var ServerSession = class {
5649
5699
  if (!this.currentDocument) return;
5650
5700
  const currentObjects = this.currentDocument.objects ?? [];
5651
5701
  const previousObjects = this.previousDocument?.objects ?? [];
5652
- const unionObjects = [...currentObjects, ...previousObjects];
5653
- if (currentObjects.length > 0) {
5654
- this.idMap = buildIdMap(currentObjects);
5655
- } else {
5656
- this.idMap = /* @__PURE__ */ new Map();
5657
- }
5658
- if (unionObjects.length > 0) {
5659
- this.reverseIdMap = buildReverseIdMap(unionObjects);
5660
- } else {
5661
- this.reverseIdMap = /* @__PURE__ */ new Map();
5702
+ this.buildMaps(currentObjects, previousObjects, this.idMapperState);
5703
+ for (const obj of currentObjects) {
5704
+ this.updateIdSignature(obj);
5662
5705
  }
5663
5706
  }
5664
5707
  };
@@ -5816,7 +5859,7 @@ var SessionManager = class {
5816
5859
  };
5817
5860
 
5818
5861
  // src/version.ts
5819
- var VSL_MCP_SERVER_VERSION = "1.4.6";
5862
+ var VSL_MCP_SERVER_VERSION = "1.4.7";
5820
5863
 
5821
5864
  // src/index.ts
5822
5865
  async function main() {