@thinkingos/vsl-mcp-server 0.3.0 → 0.4.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/dist/index.js CHANGED
@@ -73,6 +73,78 @@ import {
73
73
 
74
74
  // src/tools/getSnapshot.ts
75
75
  import { isVslDiff } from "@thinkingos/vsl-sdk";
76
+ var DEFAULT_SNAPSHOT_TTL_MS = 5e3;
77
+ var snapshotCache = /* @__PURE__ */ new Map();
78
+ function filterObjectsByDetailLevel(objects, level) {
79
+ if (level === "high") return objects;
80
+ const INTERACTIVE_TYPES = /* @__PURE__ */ new Set([
81
+ "button",
82
+ "link",
83
+ "input",
84
+ "select",
85
+ "checkbox",
86
+ "radio",
87
+ "textarea",
88
+ "file",
89
+ "submit",
90
+ "reset"
91
+ ]);
92
+ const CONTAINER_TYPES = /* @__PURE__ */ new Set([
93
+ "div",
94
+ "section",
95
+ "article",
96
+ "nav",
97
+ "header",
98
+ "footer",
99
+ "main",
100
+ "aside",
101
+ "form",
102
+ "fieldset"
103
+ ]);
104
+ function filterRecursive(obj) {
105
+ const type = obj.t || "";
106
+ if (level === "low") {
107
+ if (!INTERACTIVE_TYPES.has(type)) {
108
+ if (obj.ch && obj.ch.length > 0) {
109
+ const filteredChildren = obj.ch.map(filterRecursive).filter((child) => child !== null);
110
+ if (filteredChildren.length > 0) {
111
+ return { ...obj, ch: filteredChildren };
112
+ }
113
+ }
114
+ return null;
115
+ }
116
+ return obj;
117
+ }
118
+ if (level === "medium") {
119
+ if (INTERACTIVE_TYPES.has(type) || CONTAINER_TYPES.has(type)) {
120
+ if (obj.ch && obj.ch.length > 0) {
121
+ const filteredChildren = obj.ch.map(filterRecursive).filter((child) => child !== null);
122
+ return { ...obj, ch: filteredChildren };
123
+ }
124
+ return obj;
125
+ }
126
+ if (obj.ch && obj.ch.length > 0) {
127
+ const filteredChildren = obj.ch.map(filterRecursive).filter((child) => child !== null);
128
+ if (filteredChildren.length > 0) {
129
+ return { ...obj, ch: filteredChildren };
130
+ }
131
+ }
132
+ return null;
133
+ }
134
+ return obj;
135
+ }
136
+ return objects.map(filterRecursive).filter((obj) => obj !== null);
137
+ }
138
+ function countObjects(objects) {
139
+ let count = 0;
140
+ for (const obj of objects) {
141
+ count++;
142
+ if (obj.ch && obj.ch.length > 0) {
143
+ count += countObjects(obj.ch);
144
+ }
145
+ }
146
+ return count;
147
+ }
76
148
  function extractDomTreeInBrowser() {
77
149
  const NON_RENDERABLE_TAGS = /* @__PURE__ */ new Set([
78
150
  "script",
@@ -172,7 +244,40 @@ function extractDomTreeInBrowser() {
172
244
  return collectVisibleChildren(body, []);
173
245
  }
174
246
  async function handleGetSnapshot(args, browser, session, _config) {
247
+ const startTime = Date.now();
248
+ const detailLevel = args.detail_level || "high";
249
+ const ttl = args.ttl ?? DEFAULT_SNAPSHOT_TTL_MS;
250
+ const VALID_DETAIL_LEVELS = ["low", "medium", "high"];
251
+ if (args.detail_level !== void 0 && !VALID_DETAIL_LEVELS.includes(args.detail_level)) {
252
+ return {
253
+ status: "error",
254
+ error: "Invalid detail_level: " + args.detail_level + ". Valid values: " + VALID_DETAIL_LEVELS.join(", ")
255
+ };
256
+ }
257
+ if (args.ttl !== void 0 && (typeof args.ttl !== "number" || args.ttl < 0)) {
258
+ return {
259
+ status: "error",
260
+ error: "Invalid ttl: " + args.ttl + ". Must be a non-negative number (milliseconds)."
261
+ };
262
+ }
175
263
  try {
264
+ if (ttl > 0) {
265
+ const cacheKey = `${args.url || "current"}:${detailLevel}`;
266
+ const cached = snapshotCache.get(cacheKey);
267
+ if (cached && Date.now() - cached.timestamp < ttl) {
268
+ return {
269
+ ...cached.result,
270
+ metadata: {
271
+ ...cached.result.metadata,
272
+ json_size_bytes: cached.result.metadata?.json_size_bytes ?? 0,
273
+ estimated_tokens: cached.result.metadata?.estimated_tokens ?? 0,
274
+ object_count: cached.result.metadata?.object_count ?? 0,
275
+ execution_time_ms: Date.now() - startTime,
276
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
277
+ }
278
+ };
279
+ }
280
+ }
176
281
  if (args.url) {
177
282
  await browser.navigate(args.url);
178
283
  }
@@ -228,9 +333,38 @@ async function handleGetSnapshot(args, browser, session, _config) {
228
333
  },
229
334
  currentDoc.objects
230
335
  );
336
+ const filteredObjects = filterObjectsByDetailLevel(currentDoc.objects, detailLevel);
337
+ const filteredResult = isVslDiff(result) ? { ...result, objects: filteredObjects } : { ...result, objects: filteredObjects };
338
+ const executionTimeMs = Date.now() - startTime;
339
+ const resultJson = JSON.stringify(filteredResult);
340
+ const jsonSizeBytes = Buffer.byteLength(resultJson, "utf-8");
341
+ const estimatedTokens = Math.ceil(jsonSizeBytes / 4);
342
+ const objectCount = countObjects(filteredObjects);
343
+ const metadata = {
344
+ json_size_bytes: jsonSizeBytes,
345
+ estimated_tokens: estimatedTokens,
346
+ object_count: objectCount,
347
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
348
+ execution_time_ms: executionTimeMs
349
+ };
350
+ if (ttl > 0) {
351
+ const cacheKey = `${args.url || "current"}:${detailLevel}`;
352
+ const resultToCache = {
353
+ status: "success",
354
+ data: filteredResult,
355
+ metadata
356
+ };
357
+ snapshotCache.set(cacheKey, {
358
+ result: resultToCache,
359
+ timestamp: Date.now(),
360
+ url: args.url || "current",
361
+ detailLevel
362
+ });
363
+ }
231
364
  return {
232
365
  status: "success",
233
- data: result
366
+ data: filteredResult,
367
+ metadata
234
368
  };
235
369
  } catch (error) {
236
370
  return {
@@ -240,8 +374,23 @@ async function handleGetSnapshot(args, browser, session, _config) {
240
374
  }
241
375
  }
242
376
 
377
+ // src/utils/metrics.ts
378
+ function computeToolMetrics(result, startTime) {
379
+ const executionTimeMs = Date.now() - startTime;
380
+ const resultJson = JSON.stringify(result);
381
+ const jsonSizeBytes = Buffer.byteLength(resultJson, "utf-8");
382
+ const estimatedTokens = Math.ceil(jsonSizeBytes / 4);
383
+ return {
384
+ json_size_bytes: jsonSizeBytes,
385
+ estimated_tokens: estimatedTokens,
386
+ execution_time_ms: executionTimeMs,
387
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
388
+ };
389
+ }
390
+
243
391
  // src/tools/getDiff.ts
244
392
  async function handleGetDiff(session) {
393
+ const startTime = Date.now();
245
394
  try {
246
395
  if (!session.hasSnapshot()) {
247
396
  return {
@@ -258,7 +407,8 @@ async function handleGetDiff(session) {
258
407
  }
259
408
  return {
260
409
  status: "success",
261
- data: diff
410
+ data: diff,
411
+ metadata: computeToolMetrics(diff, startTime)
262
412
  };
263
413
  } catch (error) {
264
414
  return {
@@ -269,7 +419,8 @@ async function handleGetDiff(session) {
269
419
  }
270
420
 
271
421
  // src/tools/navigate.ts
272
- async function handleNavigate(args, browser) {
422
+ async function handleNavigate(args, browser, session) {
423
+ const startTime = Date.now();
273
424
  try {
274
425
  if (!args.url || typeof args.url !== "string") {
275
426
  return {
@@ -294,12 +445,32 @@ async function handleNavigate(args, browser) {
294
445
  }
295
446
  await browser.navigate(args.url);
296
447
  const title = await browser.evaluate(() => document.title);
448
+ let snapshot;
449
+ try {
450
+ const elements = await browser.evaluate(extractDomTreeInBrowser);
451
+ const viewport = await browser.evaluate(() => ({
452
+ width: window.innerWidth,
453
+ height: window.innerHeight
454
+ }));
455
+ const input = {
456
+ viewport,
457
+ url: args.url,
458
+ title,
459
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
460
+ };
461
+ session.snapshotFromElements(elements, input);
462
+ snapshot = session.getSnapshot();
463
+ } catch {
464
+ }
465
+ const data = {
466
+ url: args.url,
467
+ title,
468
+ snapshot
469
+ };
297
470
  return {
298
471
  status: "success",
299
- data: {
300
- url: args.url,
301
- title
302
- }
472
+ data,
473
+ metadata: computeToolMetrics(data, startTime)
303
474
  };
304
475
  } catch (error) {
305
476
  return {
@@ -311,13 +482,15 @@ async function handleNavigate(args, browser) {
311
482
 
312
483
  // src/tools/clearCache.ts
313
484
  async function handleClearCache(session) {
485
+ const startTime = Date.now();
314
486
  try {
315
487
  session.clear();
316
488
  return {
317
489
  status: "success",
318
490
  data: {
319
491
  message: "Cache cleared. Next vsl_get_snapshot will create a new snapshot from scratch."
320
- }
492
+ },
493
+ metadata: computeToolMetrics({ cleared: true }, startTime)
321
494
  };
322
495
  } catch (error) {
323
496
  return {
@@ -344,7 +517,30 @@ var VALID_ACTIONS = [
344
517
  "download",
345
518
  "upload"
346
519
  ];
520
+ async function getStateAfterAction(session, browser, url) {
521
+ try {
522
+ const elements = await browser.evaluate(extractDomTreeInBrowser);
523
+ const viewport = await browser.evaluate(() => ({
524
+ width: window.innerWidth,
525
+ height: window.innerHeight
526
+ }));
527
+ const input = {
528
+ viewport,
529
+ url,
530
+ title: "",
531
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
532
+ };
533
+ session.snapshotFromElements(elements, input);
534
+ const diff = session.getDiff();
535
+ const snapshot = session.getSnapshot();
536
+ return { diff, snapshot };
537
+ } catch (error) {
538
+ console.warn("Failed to get state after action:", error);
539
+ return void 0;
540
+ }
541
+ }
347
542
  async function handleExecuteAction(args, browser, session) {
543
+ const startTime = Date.now();
348
544
  try {
349
545
  if (!args.action || typeof args.action !== "string") {
350
546
  return {
@@ -364,6 +560,29 @@ async function handleExecuteAction(args, browser, session) {
364
560
  error: `Unknown action: ${args.action}. Valid actions: ${VALID_ACTIONS.join(", ")}`
365
561
  };
366
562
  }
563
+ if (args.return_state !== void 0 && typeof args.return_state !== "boolean") {
564
+ return {
565
+ status: "error",
566
+ error: "return_state must be a boolean (true or false)"
567
+ };
568
+ }
569
+ if (args.action === "scroll" && args.value !== void 0) {
570
+ const VALID_SCROLL_VALUES = ["up", "down"];
571
+ if (!VALID_SCROLL_VALUES.includes(args.value)) {
572
+ return {
573
+ status: "error",
574
+ error: "Invalid scroll value: " + args.value + ". Valid values: " + VALID_SCROLL_VALUES.join(", ")
575
+ };
576
+ }
577
+ }
578
+ if ((args.action === "type" || args.action === "fill" || args.action === "select") && args.value !== void 0) {
579
+ if (typeof args.value !== "string") {
580
+ return {
581
+ status: "error",
582
+ error: "value must be a string for " + args.action + " action"
583
+ };
584
+ }
585
+ }
367
586
  if (!session.hasSnapshot()) {
368
587
  return {
369
588
  status: "error",
@@ -385,6 +604,20 @@ async function handleExecuteAction(args, browser, session) {
385
604
  await browser.navigate(snapshotUrl);
386
605
  }
387
606
  }
607
+ const hasVslIds = await browser.evaluate(() => {
608
+ return document.querySelector("[data-vsl-id]") !== null;
609
+ });
610
+ if (!hasVslIds) {
611
+ const elements = await browser.evaluate(extractDomTreeInBrowser);
612
+ const viewport = await browser.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
613
+ const input = {
614
+ viewport,
615
+ url: snapshotUrl || "",
616
+ title: "",
617
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
618
+ };
619
+ session.snapshotFromElements(elements, input);
620
+ }
388
621
  const selector = `[data-vsl-id="${args.target_id}"], #${args.target_id}, .${args.target_id}`;
389
622
  switch (args.action) {
390
623
  case "click":
@@ -465,7 +698,7 @@ async function handleExecuteAction(args, browser, session) {
465
698
  return id;
466
699
  }, args.value);
467
700
  const filename = args.value.split("/").pop() || "download";
468
- return {
701
+ const result2 = {
469
702
  status: "success",
470
703
  data: {
471
704
  action: args.action,
@@ -479,6 +712,18 @@ async function handleExecuteAction(args, browser, session) {
479
712
  }
480
713
  }
481
714
  };
715
+ if (args.return_state !== false) {
716
+ try {
717
+ const currentUrl = await browser.evaluate(() => window.location.href);
718
+ const state = await getStateAfterAction(session, browser, currentUrl);
719
+ if (state && result2.data) {
720
+ result2.data.state = state;
721
+ }
722
+ } catch {
723
+ }
724
+ }
725
+ result2.metadata = computeToolMetrics(result2.data, startTime);
726
+ return result2;
482
727
  }
483
728
  await browser.evaluate((sel) => {
484
729
  const el = document.querySelector(sel);
@@ -501,7 +746,7 @@ async function handleExecuteAction(args, browser, session) {
501
746
  };
502
747
  }
503
748
  await browser.uploadFile(selector, filePaths);
504
- return {
749
+ const result2 = {
505
750
  status: "success",
506
751
  data: {
507
752
  action: args.action,
@@ -514,6 +759,18 @@ async function handleExecuteAction(args, browser, session) {
514
759
  }
515
760
  }
516
761
  };
762
+ if (args.return_state !== false) {
763
+ try {
764
+ const currentUrl = await browser.evaluate(() => window.location.href);
765
+ const state = await getStateAfterAction(session, browser, currentUrl);
766
+ if (state && result2.data) {
767
+ result2.data.state = state;
768
+ }
769
+ } catch {
770
+ }
771
+ }
772
+ result2.metadata = computeToolMetrics(result2.data, startTime);
773
+ return result2;
517
774
  }
518
775
  default:
519
776
  return {
@@ -521,7 +778,7 @@ async function handleExecuteAction(args, browser, session) {
521
778
  error: `Action ${args.action} is not yet implemented`
522
779
  };
523
780
  }
524
- return {
781
+ const result = {
525
782
  status: "success",
526
783
  data: {
527
784
  action: args.action,
@@ -529,6 +786,16 @@ async function handleExecuteAction(args, browser, session) {
529
786
  success: true
530
787
  }
531
788
  };
789
+ try {
790
+ const currentUrl = await browser.evaluate(() => window.location.href);
791
+ const state = await getStateAfterAction(session, browser, currentUrl);
792
+ if (state && result.data) {
793
+ result.data.state = state;
794
+ }
795
+ } catch {
796
+ }
797
+ result.metadata = computeToolMetrics(result.data, startTime);
798
+ return result;
532
799
  } catch (error) {
533
800
  return {
534
801
  status: "error",
@@ -538,7 +805,8 @@ async function handleExecuteAction(args, browser, session) {
538
805
  }
539
806
 
540
807
  // src/tools/getVisual.ts
541
- async function handleGetVisual(args, browser) {
808
+ async function handleGetVisual(args, browser, session) {
809
+ const startTime = Date.now();
542
810
  try {
543
811
  if (!args.element_id || typeof args.element_id !== "string") {
544
812
  return {
@@ -546,35 +814,102 @@ async function handleGetVisual(args, browser) {
546
814
  isError: true
547
815
  };
548
816
  }
817
+ if (args.auto_refresh !== void 0 && typeof args.auto_refresh !== "boolean") {
818
+ return {
819
+ content: [{ type: "text", text: "Error: auto_refresh must be a boolean (true or false)" }],
820
+ isError: true
821
+ };
822
+ }
823
+ if (args.auto_scroll !== void 0 && typeof args.auto_scroll !== "boolean") {
824
+ return {
825
+ content: [{ type: "text", text: "Error: auto_scroll must be a boolean (true or false)" }],
826
+ isError: true
827
+ };
828
+ }
549
829
  const isAvailable = await browser.isAvailable();
550
830
  if (!isAvailable) {
551
831
  return {
552
832
  content: [{ type: "text", text: "Error: Playwright is not installed. Install it with: npm install playwright" }],
553
- isError: true
833
+ isError: true,
834
+ possible_causes: ["Playwright \u043D\u0435 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D"],
835
+ suggestions: ["Run: npm install playwright", "Or: npm install -g playwright"]
554
836
  };
555
837
  }
556
838
  if (args.element_id === "root_0") {
557
839
  const page2 = await browser.getPage();
558
840
  const screenshotBuffer2 = await page2.screenshot({ type: "png", fullPage: false });
559
841
  const base64Image2 = screenshotBuffer2.toString("base64");
560
- return {
842
+ const result2 = {
561
843
  content: [
562
844
  { type: "image", data: base64Image2, mimeType: "image/png" },
563
845
  { type: "text", text: `Full page screenshot (${args.element_id})` }
564
- ]
846
+ ],
847
+ metadata: computeToolMetrics({ type: "full_page", element_id: args.element_id }, startTime)
565
848
  };
849
+ return result2;
566
850
  }
567
851
  const selector = `[data-vsl-id="${args.element_id}"], #${args.element_id}, [id="${args.element_id}"]`;
568
- const elementExists = await browser.evaluate((sel) => {
852
+ let elementExists = await browser.evaluate((sel) => {
569
853
  return document.querySelector(sel) !== null;
570
854
  }, selector);
855
+ if (!elementExists && args.auto_refresh && session) {
856
+ await handleGetSnapshot({}, browser, session, { downloadsPath: "" });
857
+ elementExists = await browser.evaluate((sel) => {
858
+ return document.querySelector(sel) !== null;
859
+ }, selector);
860
+ }
571
861
  if (!elementExists) {
862
+ const suggestions = [
863
+ "Call vsl_get_snapshot to refresh DOM IDs",
864
+ "Use auto_refresh: true parameter to automatically refresh before search",
865
+ "Element may have been removed from DOM after navigation or action",
866
+ "DOM structure changed \u2014 IDs are index-based and may have shifted"
867
+ ];
572
868
  return {
573
869
  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
870
+ isError: true,
871
+ possible_causes: [
872
+ "Snapshot is outdated \u2014 DOM changed after navigation or action",
873
+ "Element was removed from DOM",
874
+ "Using semantic ID from vsl_read_page instead of browser DOM ID from vsl_get_snapshot"
875
+ ],
876
+ suggestions
575
877
  };
576
878
  }
577
879
  const page = await browser.getPage();
880
+ const autoScroll = args.auto_scroll !== false;
881
+ let scrolled = false;
882
+ let scrollOffset;
883
+ if (autoScroll) {
884
+ const scrollResult = await browser.evaluate((sel) => {
885
+ const el = document.querySelector(sel);
886
+ if (!el) return { needsScroll: false, scrolled: false };
887
+ const rect2 = el.getBoundingClientRect();
888
+ const viewportWidth = window.innerWidth;
889
+ const viewportHeight = window.innerHeight;
890
+ const isVisible = rect2.top >= 0 && rect2.left >= 0 && rect2.bottom <= viewportHeight && rect2.right <= viewportWidth;
891
+ if (isVisible) {
892
+ return { needsScroll: false, scrolled: false };
893
+ }
894
+ el.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
895
+ return { needsScroll: true, scrolled: true };
896
+ }, selector);
897
+ if (scrollResult.scrolled) {
898
+ scrolled = true;
899
+ await browser.evaluate(() => {
900
+ return new Promise((resolve) => {
901
+ requestAnimationFrame(() => {
902
+ requestAnimationFrame(() => {
903
+ resolve();
904
+ });
905
+ });
906
+ });
907
+ });
908
+ scrollOffset = await browser.evaluate(() => {
909
+ return { x: window.scrollX, y: window.scrollY };
910
+ });
911
+ }
912
+ }
578
913
  const rect = await browser.evaluate((sel) => {
579
914
  const el = document.querySelector(sel);
580
915
  if (!el) return null;
@@ -592,12 +927,21 @@ async function handleGetVisual(args, browser) {
592
927
  clip: rect
593
928
  });
594
929
  const base64Image = screenshotBuffer.toString("base64");
595
- return {
930
+ const metricsData = { type: "element", element_id: args.element_id, width: rect.width, height: rect.height };
931
+ const result = {
596
932
  content: [
597
933
  { type: "image", data: base64Image, mimeType: "image/png" },
598
934
  { type: "text", text: `Screenshot of element: ${args.element_id}` }
599
- ]
935
+ ],
936
+ metadata: computeToolMetrics(metricsData, startTime)
600
937
  };
938
+ if (scrolled) {
939
+ result.scroll_info = {
940
+ scrolled: true,
941
+ scroll_offset: scrollOffset
942
+ };
943
+ }
944
+ return result;
601
945
  } catch (error) {
602
946
  return {
603
947
  content: [{ type: "text", text: `Error: vsl_get_visual failed: ${error instanceof Error ? error.message : String(error)}` }],
@@ -872,6 +1216,33 @@ function determineActions(type, state, $el) {
872
1216
 
873
1217
  // src/tools/readPage.ts
874
1218
  async function handleReadPage(args, browser, session, _config) {
1219
+ const startTime = Date.now();
1220
+ if (!args.url || typeof args.url !== "string" || args.url.trim() === "") {
1221
+ return {
1222
+ status: "error",
1223
+ error: "url is required and must be a non-empty string"
1224
+ };
1225
+ }
1226
+ if (args.detail_level !== void 0 && typeof args.detail_level !== "string") {
1227
+ return {
1228
+ status: "error",
1229
+ error: "detail_level must be a string (low, medium, or high)"
1230
+ };
1231
+ }
1232
+ const validDetailLevels = ["low", "medium", "high"];
1233
+ if (args.detail_level !== void 0 && !validDetailLevels.includes(args.detail_level)) {
1234
+ return {
1235
+ status: "error",
1236
+ error: "Invalid detail_level: " + args.detail_level + ". Valid values: " + validDetailLevels.join(", ")
1237
+ };
1238
+ }
1239
+ if (args.readable !== void 0 && typeof args.readable !== "boolean") {
1240
+ return {
1241
+ status: "error",
1242
+ error: "readable must be a boolean (true or false)"
1243
+ };
1244
+ }
1245
+ const detailLevel = args.detail_level || "medium";
875
1246
  try {
876
1247
  const readable = args.readable ?? false;
877
1248
  let detectedMode = "http";
@@ -901,21 +1272,31 @@ async function handleReadPage(args, browser, session, _config) {
901
1272
  const hasDiff2 = hadPreviousSnapshot2;
902
1273
  const readableHtml = readable ? applyReadableFilter(html) : html;
903
1274
  const content = extractTextContent(readableHtml);
1275
+ const rawSnapshot2 = session.getSnapshot();
1276
+ const rawDiff2 = hasDiff2 ? session.getDiff() : void 0;
1277
+ const fullSnapshot2 = rawSnapshot2 ? applyDetailLevelFilter(rawSnapshot2, detailLevel) : void 0;
1278
+ const fullDiff2 = rawDiff2 ? applyDetailLevelFilter(rawDiff2, detailLevel) : void 0;
1279
+ const data2 = {
1280
+ url: args.url,
1281
+ mode: "render",
1282
+ content,
1283
+ vslDocument,
1284
+ snapshot: fullSnapshot2,
1285
+ diff: fullDiff2,
1286
+ hasDiff: hasDiff2,
1287
+ metadata: {
1288
+ title: extractTitle(html),
1289
+ wordCount: countWords(content),
1290
+ isSpa,
1291
+ readableApplied: readable,
1292
+ detail_level: detailLevel,
1293
+ ...computeVslMetrics(fullSnapshot2)
1294
+ }
1295
+ };
904
1296
  return {
905
1297
  status: "success",
906
- data: {
907
- url: args.url,
908
- mode: "render",
909
- content,
910
- vslDocument,
911
- hasDiff: hasDiff2,
912
- metadata: {
913
- title: extractTitle(html),
914
- wordCount: countWords(content),
915
- isSpa,
916
- readableApplied: readable
917
- }
918
- }
1298
+ data: data2,
1299
+ tool_metadata: computeToolMetrics(data2, startTime)
919
1300
  };
920
1301
  }
921
1302
  if (!httpResult) {
@@ -924,21 +1305,31 @@ async function handleReadPage(args, browser, session, _config) {
924
1305
  const hadPreviousSnapshot = session.hasSnapshot();
925
1306
  session.setSnapshot(httpResult.vslDocument);
926
1307
  const hasDiff = hadPreviousSnapshot;
1308
+ const rawSnapshot = session.getSnapshot();
1309
+ const rawDiff = hasDiff ? session.getDiff() : void 0;
1310
+ const fullSnapshot = rawSnapshot ? applyDetailLevelFilter(rawSnapshot, detailLevel) : void 0;
1311
+ const fullDiff = rawDiff ? applyDetailLevelFilter(rawDiff, detailLevel) : void 0;
1312
+ const data = {
1313
+ url: args.url,
1314
+ mode: "http",
1315
+ content: httpResult.textContent,
1316
+ vslDocument: httpResult.vslDocument,
1317
+ snapshot: fullSnapshot,
1318
+ diff: fullDiff,
1319
+ hasDiff,
1320
+ metadata: {
1321
+ title: httpResult.title,
1322
+ wordCount: httpResult.wordCount,
1323
+ isSpa: httpResult.isSpa,
1324
+ readableApplied: httpResult.readableApplied,
1325
+ detail_level: detailLevel,
1326
+ ...computeVslMetrics(fullSnapshot)
1327
+ }
1328
+ };
927
1329
  return {
928
1330
  status: "success",
929
- data: {
930
- url: args.url,
931
- mode: "http",
932
- content: httpResult.textContent,
933
- vslDocument: httpResult.vslDocument,
934
- hasDiff,
935
- metadata: {
936
- title: httpResult.title,
937
- wordCount: httpResult.wordCount,
938
- isSpa: httpResult.isSpa,
939
- readableApplied: httpResult.readableApplied
940
- }
941
- }
1331
+ data,
1332
+ tool_metadata: computeToolMetrics(data, startTime)
942
1333
  };
943
1334
  } catch (error) {
944
1335
  const stack = error instanceof Error ? error.stack : String(error);
@@ -1019,9 +1410,111 @@ async function extractVslFromPage(browser) {
1019
1410
  ]
1020
1411
  };
1021
1412
  }
1413
+ function applyDetailLevelFilter(document2, level) {
1414
+ if (level === "high") return document2;
1415
+ const objects = document2.objects;
1416
+ if (!objects || !Array.isArray(objects)) return document2;
1417
+ const INTERACTIVE_TYPES = /* @__PURE__ */ new Set([
1418
+ "button",
1419
+ "link",
1420
+ "input",
1421
+ "select",
1422
+ "checkbox",
1423
+ "radio",
1424
+ "textarea",
1425
+ "file",
1426
+ "submit",
1427
+ "reset"
1428
+ ]);
1429
+ const CONTAINER_TYPES = /* @__PURE__ */ new Set([
1430
+ "div",
1431
+ "section",
1432
+ "article",
1433
+ "nav",
1434
+ "header",
1435
+ "footer",
1436
+ "main",
1437
+ "aside",
1438
+ "form",
1439
+ "fieldset"
1440
+ ]);
1441
+ function filterRecursive(obj) {
1442
+ const type = obj.t || obj.type || "";
1443
+ if (level === "low") {
1444
+ if (!INTERACTIVE_TYPES.has(type)) {
1445
+ const children = obj.ch || obj.children;
1446
+ if (children && Array.isArray(children) && children.length > 0) {
1447
+ const filteredChildren = children.map(filterRecursive).filter((child) => child !== null);
1448
+ if (filteredChildren.length > 0) {
1449
+ return { ...obj, ch: filteredChildren };
1450
+ }
1451
+ }
1452
+ return null;
1453
+ }
1454
+ return obj;
1455
+ }
1456
+ if (level === "medium") {
1457
+ if (INTERACTIVE_TYPES.has(type) || CONTAINER_TYPES.has(type)) {
1458
+ const children2 = obj.ch || obj.children;
1459
+ if (children2 && Array.isArray(children2) && children2.length > 0) {
1460
+ const filteredChildren = children2.map(filterRecursive).filter((child) => child !== null);
1461
+ return { ...obj, ch: filteredChildren };
1462
+ }
1463
+ return obj;
1464
+ }
1465
+ const children = obj.ch || obj.children;
1466
+ if (children && Array.isArray(children) && children.length > 0) {
1467
+ const filteredChildren = children.map(filterRecursive).filter((child) => child !== null);
1468
+ if (filteredChildren.length > 0) {
1469
+ return { ...obj, ch: filteredChildren };
1470
+ }
1471
+ }
1472
+ return null;
1473
+ }
1474
+ return obj;
1475
+ }
1476
+ const filteredObjects = objects.map(filterRecursive).filter((obj) => obj !== null);
1477
+ return { ...document2, objects: filteredObjects };
1478
+ }
1479
+ function computeVslMetrics(snapshot) {
1480
+ if (!snapshot) return {};
1481
+ try {
1482
+ const jsonStr = JSON.stringify(snapshot);
1483
+ const sizeBytes = Buffer.byteLength(jsonStr, "utf-8");
1484
+ const estimatedTokens = Math.ceil(sizeBytes / 4);
1485
+ const objects = snapshot.objects;
1486
+ let objectCount = 0;
1487
+ if (objects && Array.isArray(objects)) {
1488
+ let countRecursive2 = function(obj) {
1489
+ let count = 1;
1490
+ const children = obj.ch || obj.children;
1491
+ if (children && Array.isArray(children)) {
1492
+ for (const child of children) {
1493
+ if (child && typeof child === "object") {
1494
+ count += countRecursive2(child);
1495
+ }
1496
+ }
1497
+ }
1498
+ return count;
1499
+ };
1500
+ var countRecursive = countRecursive2;
1501
+ for (const obj of objects) {
1502
+ objectCount += countRecursive2(obj);
1503
+ }
1504
+ }
1505
+ return {
1506
+ vsl_size_bytes: sizeBytes,
1507
+ vsl_estimated_tokens: estimatedTokens,
1508
+ vsl_object_count: objectCount
1509
+ };
1510
+ } catch {
1511
+ return {};
1512
+ }
1513
+ }
1022
1514
 
1023
1515
  // src/tools/getFullJson.ts
1024
1516
  async function handleGetFullJson(_args, session) {
1517
+ const startTime = Date.now();
1025
1518
  try {
1026
1519
  if (!session.hasSnapshot()) {
1027
1520
  return {
@@ -1033,7 +1526,8 @@ async function handleGetFullJson(_args, session) {
1033
1526
  const snapshot = session.getSnapshot();
1034
1527
  return {
1035
1528
  status: "success",
1036
- data: snapshot
1529
+ data: snapshot,
1530
+ metadata: computeToolMetrics(snapshot, startTime)
1037
1531
  };
1038
1532
  } catch (error) {
1039
1533
  return {
@@ -1045,6 +1539,7 @@ async function handleGetFullJson(_args, session) {
1045
1539
 
1046
1540
  // src/tools/getTextBlock.ts
1047
1541
  async function handleGetTextBlock(args, session) {
1542
+ const startTime = Date.now();
1048
1543
  try {
1049
1544
  if (!args.block_id || typeof args.block_id !== "string") {
1050
1545
  return {
@@ -1072,12 +1567,14 @@ async function handleGetTextBlock(args, session) {
1072
1567
  error: `Text block not found: ${args.block_id}`
1073
1568
  };
1074
1569
  }
1570
+ const data = {
1571
+ block_id: args.block_id,
1572
+ text: fullText
1573
+ };
1075
1574
  return {
1076
1575
  status: "success",
1077
- data: {
1078
- block_id: args.block_id,
1079
- text: fullText
1080
- }
1576
+ data,
1577
+ metadata: computeToolMetrics(data, startTime)
1081
1578
  };
1082
1579
  } catch (error) {
1083
1580
  return {
@@ -1097,6 +1594,30 @@ async function handleDownload(args, browser, session) {
1097
1594
  error: "Either target_id (element to click) or value (URL to download) is required"
1098
1595
  };
1099
1596
  }
1597
+ if (args.target_id !== void 0 && typeof args.target_id !== "string") {
1598
+ return {
1599
+ status: "error",
1600
+ error: "target_id must be a string"
1601
+ };
1602
+ }
1603
+ if (args.value !== void 0 && typeof args.value !== "string") {
1604
+ return {
1605
+ status: "error",
1606
+ error: "value must be a string"
1607
+ };
1608
+ }
1609
+ if (args.timeout !== void 0 && (typeof args.timeout !== "number" || args.timeout <= 0)) {
1610
+ return {
1611
+ status: "error",
1612
+ error: "timeout must be a positive number (milliseconds)"
1613
+ };
1614
+ }
1615
+ if (args.save_path !== void 0 && typeof args.save_path !== "string") {
1616
+ return {
1617
+ status: "error",
1618
+ error: "save_path must be a string"
1619
+ };
1620
+ }
1100
1621
  if (args.target_id && !session.hasSnapshot()) {
1101
1622
  return {
1102
1623
  status: "error",
@@ -1162,6 +1683,12 @@ async function handleDownload(args, browser, session) {
1162
1683
  };
1163
1684
  }
1164
1685
  const latestDownload = downloads[downloads.length - 1];
1686
+ if (!latestDownload) {
1687
+ return {
1688
+ status: "error",
1689
+ error: "No active downloads found after triggering download."
1690
+ };
1691
+ }
1165
1692
  const downloadId = latestDownload.downloadId;
1166
1693
  const timeout = args.timeout;
1167
1694
  const result = await browser.waitForDownload(downloadId, timeout);
@@ -1202,13 +1729,22 @@ async function handleDownload(args, browser, session) {
1202
1729
  var VSL_TOOLS = [
1203
1730
  {
1204
1731
  name: "vsl_get_snapshot",
1205
- description: "\u041F\u043E\u043B\u0443\u0447\u0438\u0442\u044C \u0442\u0435\u043A\u0443\u0449\u0438\u0439 VSL snapshot \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u044B. \u0412\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 VSL JSON \u0441 \u0441\u0435\u043C\u0430\u043D\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0439 \u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u043E\u0439 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432. VSL (Visual Scene Language) \u2014 \u044D\u0442\u043E JSON-\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u044B, \u0433\u0434\u0435 \u043A\u0430\u0436\u0434\u044B\u0439 \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u0438\u043C\u0435\u0435\u0442: id (\u0443\u043D\u0438\u043A\u0430\u043B\u044C\u043D\u044B\u0439 \u0438\u0434\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440, \u043D\u0430\u043F\u0440\u0438\u043C\u0435\u0440 btn_123), type (button/input/link/text/image), text (\u0442\u0435\u043A\u0441\u0442\u043E\u0432\u043E\u0435 \u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0435), bbox ([x,y,width,height]), children (\u0432\u043B\u043E\u0436\u0435\u043D\u043D\u044B\u0435 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B). \u041F\u0440\u0438\u043C\u0435\u0440: { viewport:{width:1920,height:1080}, objects:[{id:btn_1,type:button,text:\u0412\u043E\u0439\u0442\u0438,bbox:[100,200,80,30]},{id:inp_2,type:input,text:,bbox:[100,250,200,30]}] }. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u0435 snapshot, \u043D\u0430\u0439\u0434\u0438\u0442\u0435 \u043D\u0443\u0436\u043D\u044B\u0439 \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u043F\u043E id, \u0437\u0430\u0442\u0435\u043C \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 vsl_execute_action \u0434\u043B\u044F \u0432\u0437\u0430\u0438\u043C\u043E\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F.",
1732
+ description: "\u041F\u043E\u043B\u0443\u0447\u0438\u0442\u044C \u0442\u0435\u043A\u0443\u0449\u0438\u0439 VSL snapshot \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u044B. \u0412\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 VSL JSON \u0441 \u0441\u0435\u043C\u0430\u043D\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0439 \u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u043E\u0439 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432. VSL (Visual Scene Language) \u2014 \u044D\u0442\u043E JSON-\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u044B, \u0433\u0434\u0435 \u043A\u0430\u0436\u0434\u044B\u0439 \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u0438\u043C\u0435\u0435\u0442: id (\u0443\u043D\u0438\u043A\u0430\u043B\u044C\u043D\u044B\u0439 \u0438\u0434\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440, \u043D\u0430\u043F\u0440\u0438\u043C\u0435\u0440 btn_123), type (button/input/link/text/image), text (\u0442\u0435\u043A\u0441\u0442\u043E\u0432\u043E\u0435 \u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0435), bbox ([x,y,width,height]), children (\u0432\u043B\u043E\u0436\u0435\u043D\u043D\u044B\u0435 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B). \u041F\u0440\u0438\u043C\u0435\u0440: { viewport:{width:1920,height:1080}, objects:[{id:btn_1,type:button,text:\u0412\u043E\u0439\u0442\u0438,bbox:[100,200,80,30]},{id:inp_2,type:input,text:,bbox:[100,250,200,30]}] }. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u0435 snapshot, \u043D\u0430\u0439\u0434\u0438\u0442\u0435 \u043D\u0443\u0436\u043D\u044B\u0439 \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u043F\u043E id, \u0437\u0430\u0442\u0435\u043C \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 vsl_execute_action \u0434\u043B\u044F \u0432\u0437\u0430\u0438\u043C\u043E\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F. Lazy text loading (DEC-026): \u0442\u0435\u043A\u0441\u0442\u044B \u0434\u043B\u0438\u043D\u043D\u0435\u0435 200 \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432 \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u0437\u0430\u043C\u0435\u043D\u044F\u044E\u0442\u0441\u044F \u043D\u0430 txt_preview (\u043F\u0435\u0440\u0432\u044B\u0435 ~50 \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432) + txt_ref (\u0441\u0441\u044B\u043B\u043A\u0430 \u0432\u0438\u0434\u0430 tb_001). \u041F\u043E\u043B\u043D\u044B\u0435 \u0442\u0435\u043A\u0441\u0442\u044B \u0445\u0440\u0430\u043D\u044F\u0442\u0441\u044F \u0432 text_blocks map. \u0414\u043B\u044F \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u044F \u043F\u043E\u043B\u043D\u043E\u0433\u043E \u0442\u0435\u043A\u0441\u0442\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 vsl_get_text_block. \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B: detail_level (low/medium/high) \u0434\u043B\u044F \u0444\u0438\u043B\u044C\u0442\u0440\u0430\u0446\u0438\u0438 \u043E\u0431\u044A\u0435\u043A\u0442\u043E\u0432, ttl (\u043C\u0441) \u0434\u043B\u044F \u043A\u044D\u0448\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F.",
1206
1733
  inputSchema: {
1207
1734
  type: "object",
1208
1735
  properties: {
1209
1736
  url: {
1210
1737
  type: "string",
1211
1738
  description: "URL \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u044B (\u043E\u043F\u0446\u0438\u043E\u043D\u0430\u043B\u044C\u043D\u043E, \u0435\u0441\u043B\u0438 \u043D\u0435 \u0443\u043A\u0430\u0437\u0430\u043D \u2014 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u0442\u0441\u044F \u0442\u0435\u043A\u0443\u0449\u0430\u044F \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u0430)"
1739
+ },
1740
+ detail_level: {
1741
+ type: "string",
1742
+ enum: ["low", "medium", "high"],
1743
+ description: "\u0423\u0440\u043E\u0432\u0435\u043D\u044C \u0434\u0435\u0442\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 snapshot. 'low': \u0442\u043E\u043B\u044C\u043A\u043E \u0438\u043D\u0442\u0435\u0440\u0430\u043A\u0442\u0438\u0432\u043D\u044B\u0435 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B (\u043A\u043D\u043E\u043F\u043A\u0438, \u0441\u0441\u044B\u043B\u043A\u0438, \u0438\u043D\u043F\u0443\u0442\u044B). 'medium': \u0438\u043D\u0442\u0435\u0440\u0430\u043A\u0442\u0438\u0432\u043D\u044B\u0435 + \u043A\u043E\u043D\u0442\u0435\u0439\u043D\u0435\u0440\u044B. 'high': \u0432\u0441\u0435 \u043E\u0431\u044A\u0435\u043A\u0442\u044B (\u043F\u043E\u043B\u043D\u044B\u0439 DOM). Default: 'high'."
1744
+ },
1745
+ ttl: {
1746
+ type: "number",
1747
+ description: "TTL \u043A\u044D\u0448\u0430 \u0432 \u043C\u0438\u043B\u043B\u0438\u0441\u0435\u043A\u0443\u043D\u0434\u0430\u0445 (default: 5000 = 5s). \u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0435 0 \u0434\u043B\u044F \u043E\u0442\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F \u043A\u044D\u0448\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F."
1212
1748
  }
1213
1749
  }
1214
1750
  }
@@ -1223,7 +1759,7 @@ var VSL_TOOLS = [
1223
1759
  },
1224
1760
  {
1225
1761
  name: "vsl_execute_action",
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}.",
1762
+ 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}. \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440 return_state=true \u0432\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 diff \u0438 snapshot \u043F\u043E\u0441\u043B\u0435 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F.",
1227
1763
  inputSchema: {
1228
1764
  type: "object",
1229
1765
  properties: {
@@ -1238,6 +1774,10 @@ var VSL_TOOLS = [
1238
1774
  value: {
1239
1775
  type: "string",
1240
1776
  description: "\u0417\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0434\u043B\u044F \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F (\u043D\u0430\u043F\u0440\u0438\u043C\u0435\u0440, \u0442\u0435\u043A\u0441\u0442 \u0434\u043B\u044F type/fill, \u043E\u043F\u0446\u0438\u044F \u0434\u043B\u044F select)"
1777
+ },
1778
+ return_state: {
1779
+ type: "boolean",
1780
+ description: "\u0415\u0441\u043B\u0438 true, \u0432\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 diff \u0438 snapshot \u043F\u043E\u0441\u043B\u0435 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F. \u041F\u043E\u043B\u0435\u0437\u043D\u043E \u0434\u043B\u044F \u043E\u0442\u0441\u043B\u0435\u0436\u0438\u0432\u0430\u043D\u0438\u044F \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439 DOM \u0431\u0435\u0437 \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0433\u043E \u0432\u044B\u0437\u043E\u0432\u0430 vsl_get_diff. Default: true \u2014 \u0432\u0441\u0435\u0433\u0434\u0430 \u0432\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0442\u044C \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435 \u0434\u043B\u044F \u044D\u043A\u043E\u043D\u043E\u043C\u0438\u0438 \u0445\u043E\u0434\u043E\u0432 \u0430\u0433\u0435\u043D\u0442\u0430. \u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0435 false \u0434\u043B\u044F \u043E\u0442\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F."
1241
1781
  }
1242
1782
  },
1243
1783
  required: ["action", "target_id"]
@@ -1267,13 +1807,17 @@ var VSL_TOOLS = [
1267
1807
  },
1268
1808
  {
1269
1809
  name: "vsl_get_visual",
1270
- description: "\u041F\u043E\u043B\u0443\u0447\u0438\u0442\u044C visual fragment (\u0441\u043A\u0440\u0438\u043D\u0448\u043E\u0442) \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64 WebP. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 \u0434\u043B\u044F \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432, \u043A\u043E\u0442\u043E\u0440\u044B\u0435 \u0441\u043B\u043E\u0436\u043D\u043E \u043A\u043B\u0430\u0441\u0441\u0438\u0444\u0438\u0446\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u043F\u043E \u0442\u0435\u043A\u0441\u0442\u0443 (\u0438\u043A\u043E\u043D\u043A\u0438, \u0433\u0440\u0430\u0444\u0438\u043A\u0438, \u043A\u0430\u0441\u0442\u043E\u043C\u043D\u044B\u0435 \u0432\u0438\u0434\u0436\u0435\u0442\u044B). \u0412\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 {mediaType:image/webp, data:base64data}. \u041F\u0440\u0438\u043C\u0435\u0440: {element_id: img_5}.",
1810
+ description: "\u041F\u043E\u043B\u0443\u0447\u0438\u0442\u044C visual fragment (\u0441\u043A\u0440\u0438\u043D\u0448\u043E\u0442) \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64 WebP. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 \u0434\u043B\u044F \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432, \u043A\u043E\u0442\u043E\u0440\u044B\u0435 \u0441\u043B\u043E\u0436\u043D\u043E \u043A\u043B\u0430\u0441\u0441\u0438\u0444\u0438\u0446\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u043F\u043E \u0442\u0435\u043A\u0441\u0442\u0443 (\u0438\u043A\u043E\u043D\u043A\u0438, \u0433\u0440\u0430\u0444\u0438\u043A\u0438, \u043A\u0430\u0441\u0442\u043E\u043C\u043D\u044B\u0435 \u0432\u0438\u0434\u0436\u0435\u0442\u044B). \u0412\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 {mediaType:image/webp, data:base64data}. \u041F\u0440\u0438\u043C\u0435\u0440: {element_id: img_5}. \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440 auto_refresh=true \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u043E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u0442 snapshot \u043F\u0435\u0440\u0435\u0434 \u043F\u043E\u0438\u0441\u043A\u043E\u043C \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430.",
1271
1811
  inputSchema: {
1272
1812
  type: "object",
1273
1813
  properties: {
1274
1814
  element_id: {
1275
1815
  type: "string",
1276
1816
  description: "ID \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430 \u0432 VSL JSON"
1817
+ },
1818
+ auto_refresh: {
1819
+ type: "boolean",
1820
+ description: "\u0415\u0441\u043B\u0438 true, \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u043E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u0442 snapshot \u043F\u0435\u0440\u0435\u0434 \u043F\u043E\u0438\u0441\u043A\u043E\u043C \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430. \u041F\u043E\u043B\u0435\u0437\u043D\u043E \u043F\u043E\u0441\u043B\u0435 \u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u0438 \u0438\u043B\u0438 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0439, \u043A\u043E\u0442\u043E\u0440\u044B\u0435 \u0438\u0437\u043C\u0435\u043D\u044F\u044E\u0442 DOM. Default: false."
1277
1821
  }
1278
1822
  },
1279
1823
  required: ["element_id"]
@@ -1281,7 +1825,7 @@ var VSL_TOOLS = [
1281
1825
  },
1282
1826
  {
1283
1827
  name: "vsl_read_page",
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}.',
1828
+ 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\u0430\u0440\u0430\u043C\u0435\u0442\u0440 detail_level (low/medium/high) \u0444\u0438\u043B\u044C\u0442\u0440\u0443\u0435\u0442 \u043E\u0431\u044A\u0435\u043A\u0442\u044B \u0432 snapshot: low \u2014 \u0442\u043E\u043B\u044C\u043A\u043E \u0438\u043D\u0442\u0435\u0440\u0430\u043A\u0442\u0438\u0432\u043D\u044B\u0435 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B (\u043A\u043D\u043E\u043F\u043A\u0438, \u0441\u0441\u044B\u043B\u043A\u0438, \u0438\u043D\u043F\u0443\u0442\u044B), medium \u2014 \u0438\u043D\u0442\u0435\u0440\u0430\u043A\u0442\u0438\u0432\u043D\u044B\u0435 + \u043A\u043E\u043D\u0442\u0435\u0439\u043D\u0435\u0440\u044B (\u043F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E), high \u2014 \u0432\u0441\u0435 \u043E\u0431\u044A\u0435\u043A\u0442\u044B. \u0412 metadata \u0432\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442\u0441\u044F vsl_estimated_tokens \u2014 \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0442\u043E\u043A\u0435\u043D\u043E\u0432 \u0432 VSL snapshot \u0434\u043B\u044F \u043E\u0446\u0435\u043D\u043A\u0438 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430. \u041F\u0440\u0438\u043C\u0435\u0440: {url:"https://example.com", readable:true, detail_level:"medium"}. \u0412\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 snapshot \u0438 diff \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438.',
1285
1829
  inputSchema: {
1286
1830
  type: "object",
1287
1831
  properties: {
@@ -1345,14 +1889,16 @@ var VSL_TOOLS = [
1345
1889
  }
1346
1890
  }
1347
1891
  ];
1348
- function registerTools(server, config, browser, session) {
1892
+ function registerTools(server, config, sessionManager) {
1349
1893
  server.setRequestHandler(ListToolsRequestSchema, async () => {
1350
1894
  return {
1351
1895
  tools: VSL_TOOLS
1352
1896
  };
1353
1897
  });
1354
1898
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
1355
- const { name, arguments: args } = request.params;
1899
+ const { name, arguments: args, _meta } = request.params;
1900
+ const sessionId = _meta?.sessionId ?? sessionManager.getDefaultSessionId();
1901
+ const { browser, session } = sessionManager.getSession(sessionId);
1356
1902
  try {
1357
1903
  let result;
1358
1904
  switch (name) {
@@ -1366,13 +1912,14 @@ function registerTools(server, config, browser, session) {
1366
1912
  result = await handleExecuteAction(args, browser, session);
1367
1913
  break;
1368
1914
  case "vsl_navigate":
1369
- result = await handleNavigate(args, browser);
1915
+ result = await handleNavigate(args, browser, session);
1370
1916
  break;
1371
1917
  case "vsl_clear_cache":
1372
1918
  result = await handleClearCache(session);
1373
1919
  break;
1374
1920
  case "vsl_get_visual":
1375
- return await handleGetVisual(args, browser);
1921
+ result = await handleGetVisual(args, browser, session);
1922
+ break;
1376
1923
  case "vsl_read_page":
1377
1924
  result = await handleReadPage(args, browser, session, config);
1378
1925
  break;
@@ -1441,7 +1988,7 @@ var VSL_RESOURCES = [
1441
1988
  mimeType: "application/json"
1442
1989
  }
1443
1990
  ];
1444
- function registerResources(server, _config, session) {
1991
+ function registerResources(server, _config, sessionManager) {
1445
1992
  server.setRequestHandler(ListResourcesRequestSchema, async () => {
1446
1993
  return {
1447
1994
  resources: VSL_RESOURCES
@@ -1449,6 +1996,9 @@ function registerResources(server, _config, session) {
1449
1996
  });
1450
1997
  server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
1451
1998
  const { uri } = request.params;
1999
+ const sessionId = request.params._meta?.sessionId ?? sessionManager.getDefaultSessionId();
2000
+ const { session } = sessionManager.getSession(sessionId);
2001
+ ensureSubscribed(sessionId, session);
1452
2002
  switch (uri) {
1453
2003
  case "vsl://current":
1454
2004
  try {
@@ -1517,14 +2067,19 @@ function registerResources(server, _config, session) {
1517
2067
  throw new Error(`Unknown resource: ${uri}`);
1518
2068
  }
1519
2069
  });
1520
- session.setOnSnapshotChange(() => {
1521
- server.sendResourceUpdated({ uri: "vsl://current" }).catch(() => {
1522
- });
1523
- if (session.getDiff()) {
1524
- server.sendResourceUpdated({ uri: "vsl://diff" }).catch(() => {
2070
+ const subscribedSessions = /* @__PURE__ */ new Set();
2071
+ function ensureSubscribed(sessionId, session) {
2072
+ if (subscribedSessions.has(sessionId)) return;
2073
+ subscribedSessions.add(sessionId);
2074
+ session.setOnSnapshotChange(() => {
2075
+ server.sendResourceUpdated({ uri: "vsl://current" }).catch(() => {
1525
2076
  });
1526
- }
1527
- });
2077
+ if (session.getDiff()) {
2078
+ server.sendResourceUpdated({ uri: "vsl://diff" }).catch(() => {
2079
+ });
2080
+ }
2081
+ });
2082
+ }
1528
2083
  }
1529
2084
 
1530
2085
  // src/browser/manager.ts
@@ -1619,6 +2174,7 @@ var BrowserManager = class {
1619
2174
  /**
1620
2175
  * Выполняет JavaScript в контексте страницы.
1621
2176
  */
2177
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1622
2178
  async evaluate(fn, ...args) {
1623
2179
  const page = await this.getPage();
1624
2180
  return page.evaluate(fn, ...args);
@@ -1708,7 +2264,8 @@ var BrowserManager = class {
1708
2264
  if (isAbsolute) {
1709
2265
  await download.saveAs(savePath);
1710
2266
  } else {
1711
- const resolvedBase = path2.resolve(this.config.downloadsPath.replace(/^~/, os.homedir()));
2267
+ const downloadsPath = this.config.downloadsPath ?? os.tmpdir();
2268
+ const resolvedBase = path2.resolve(downloadsPath.replace(/^~/, os.homedir()));
1712
2269
  const resolvedSave = path2.resolve(resolvedBase, savePath);
1713
2270
  if (!resolvedSave.startsWith(resolvedBase + path2.sep) && resolvedSave !== resolvedBase) {
1714
2271
  throw new Error(`Path traversal detected: save_path '${savePath}' escapes downloads directory '${resolvedBase}'`);
@@ -1794,14 +2351,12 @@ var BrowserManager = class {
1794
2351
  };
1795
2352
 
1796
2353
  // src/session/serverSession.ts
1797
- import { VslSnapshotSession, diffVslDocuments } from "@thinkingos/vsl-sdk";
2354
+ import { diffVslDocuments, segmentTree, buildVslDocument } from "@thinkingos/vsl-sdk";
1798
2355
  var ServerSession = class {
1799
- sdkSession;
2356
+ currentDocument = null;
1800
2357
  previousDocument = null;
2358
+ version = 0;
1801
2359
  onSnapshotChange = null;
1802
- constructor() {
1803
- this.sdkSession = new VslSnapshotSession();
1804
- }
1805
2360
  /**
1806
2361
  * Регистрирует callback для уведомлений об изменении snapshot.
1807
2362
  * Вызывается при каждом вызове setSnapshot().
@@ -1810,58 +2365,63 @@ var ServerSession = class {
1810
2365
  this.onSnapshotChange = callback;
1811
2366
  }
1812
2367
  /**
1813
- * Устанавливает новый snapshot напрямую (VslDocument).
1814
- * Для обратной совместимости с кодом, который уже имеет готовый VslDocument.
1815
- * Предпочтительный способ: snapshotFromElements() для нового pipeline.
2368
+ * Устанавливает новый snapshot (VslDocument).
2369
+ * Сохраняет текущий документ как previousDocument для getDiff().
1816
2370
  */
1817
2371
  setSnapshot(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;
2372
+ if (this.currentDocument) {
2373
+ this.previousDocument = this.currentDocument;
2374
+ }
2375
+ this.currentDocument = doc;
2376
+ this.version += 1;
1830
2377
  if (this.onSnapshotChange) {
1831
2378
  this.onSnapshotChange();
1832
2379
  }
1833
2380
  }
1834
2381
  /**
1835
2382
  * Делает snapshot из pre-extracted elements через SDK pipeline.
1836
- * Это ПРЕДПОЧТИТЕЛЬНЫЙ способ — использует полный pipeline SDK:
1837
- * segmentTree → buildVslDocument → cache → diff.
2383
+ * segmentTree → buildVslDocument → store as current document.
2384
+ * Возвращает VslDocument (первый вызов) или VslDiff (последующие).
1838
2385
  */
1839
2386
  snapshotFromElements(extractedElements, input) {
1840
- const result = this.sdkSession.snapshotFromElements(
1841
- extractedElements,
1842
- input
1843
- );
2387
+ const segmented = segmentTree(extractedElements);
2388
+ const doc = buildVslDocument(segmented, {
2389
+ viewport: input.viewport,
2390
+ timestamp: input.timestamp,
2391
+ url: input.url,
2392
+ title: input.title
2393
+ });
2394
+ if (this.currentDocument) {
2395
+ this.previousDocument = this.currentDocument;
2396
+ }
2397
+ this.currentDocument = doc;
2398
+ this.version += 1;
1844
2399
  if (this.onSnapshotChange) {
1845
2400
  this.onSnapshotChange();
1846
2401
  }
1847
- return result;
2402
+ if (!this.previousDocument) {
2403
+ return doc;
2404
+ }
2405
+ return diffVslDocuments(this.previousDocument, doc, {
2406
+ diffVersion: this.version,
2407
+ baseVersion: this.version - 1
2408
+ });
1848
2409
  }
1849
2410
  /**
1850
2411
  * Возвращает текущий snapshot (последний полный документ).
1851
2412
  * @throws Error если snapshot не установлен
1852
2413
  */
1853
2414
  getSnapshot() {
1854
- const doc = this.sdkSession.getLastDocument();
1855
- if (!doc) {
2415
+ if (!this.currentDocument) {
1856
2416
  throw new Error("No snapshot available. Call vsl_get_snapshot first.");
1857
2417
  }
1858
- return doc;
2418
+ return this.currentDocument;
1859
2419
  }
1860
2420
  /**
1861
2421
  * Проверяет, есть ли текущий snapshot.
1862
2422
  */
1863
2423
  hasSnapshot() {
1864
- return this.sdkSession.getLastDocument() !== null;
2424
+ return this.currentDocument !== null;
1865
2425
  }
1866
2426
  /**
1867
2427
  * Вычисляет diff между текущим и предыдущим snapshot.
@@ -1869,27 +2429,152 @@ var ServerSession = class {
1869
2429
  * @returns VslDiff или null если нет предыдущего snapshot
1870
2430
  */
1871
2431
  getDiff() {
1872
- const currentDoc = this.sdkSession.getLastDocument();
1873
- if (!currentDoc || !this.previousDocument) {
2432
+ if (!this.currentDocument || !this.previousDocument) {
1874
2433
  return null;
1875
2434
  }
1876
- return diffVslDocuments(this.previousDocument, currentDoc, {
1877
- diffVersion: this.sdkSession.getVersion() + 1,
1878
- baseVersion: this.sdkSession.getVersion()
2435
+ return diffVslDocuments(this.previousDocument, this.currentDocument, {
2436
+ diffVersion: this.version,
2437
+ baseVersion: this.version - 1
1879
2438
  });
1880
2439
  }
1881
2440
  /**
1882
- * Сбрасывает сессию (кэш).
2441
+ * Сбрасывает сессию (состояние).
1883
2442
  */
1884
2443
  clear() {
1885
- this.sdkSession.clear();
2444
+ this.currentDocument = null;
2445
+ this.previousDocument = null;
2446
+ this.version = 0;
1886
2447
  }
1887
2448
  /**
1888
- * Возвращает базовую VslSnapshotSession из SDK.
1889
- * Для продвинутого использования (прямой доступ к SDK pipeline).
2449
+ * Возвращает текущую версию snapshot.
1890
2450
  */
1891
- getSession() {
1892
- return this.sdkSession;
2451
+ getVersion() {
2452
+ return this.version;
2453
+ }
2454
+ };
2455
+
2456
+ // src/session/sessionManager.ts
2457
+ var SessionManager = class {
2458
+ sessions = /* @__PURE__ */ new Map();
2459
+ browserConfig;
2460
+ cleanupIntervalMs;
2461
+ sessionTtlMs;
2462
+ defaultSessionId;
2463
+ cleanupTimer = null;
2464
+ constructor(browserConfig, options) {
2465
+ this.browserConfig = browserConfig;
2466
+ this.cleanupIntervalMs = options?.cleanupIntervalMs ?? 6e4;
2467
+ this.sessionTtlMs = options?.sessionTtlMs ?? 3e5;
2468
+ this.defaultSessionId = options?.defaultSessionId ?? "default";
2469
+ this.startCleanup();
2470
+ }
2471
+ /**
2472
+ * Возвращает default session ID (из env VSL_SESSION_ID или 'default').
2473
+ * Используется для fallback, когда _meta.sessionId не передан.
2474
+ */
2475
+ getDefaultSessionId() {
2476
+ return this.defaultSessionId;
2477
+ }
2478
+ /**
2479
+ * Получает или создаёт сессию по sessionId.
2480
+ * Если сессия не существует — создаёт новую с собственным BrowserManager и ServerSession.
2481
+ */
2482
+ getSession(sessionId) {
2483
+ const normalizedId = sessionId || this.defaultSessionId;
2484
+ if (!this.sessions.has(normalizedId)) {
2485
+ const context2 = {
2486
+ sessionId: normalizedId,
2487
+ browser: new BrowserManager(this.browserConfig),
2488
+ session: new ServerSession(),
2489
+ createdAt: Date.now(),
2490
+ lastAccessedAt: Date.now()
2491
+ };
2492
+ this.sessions.set(normalizedId, context2);
2493
+ }
2494
+ const context = this.sessions.get(normalizedId);
2495
+ context.lastAccessedAt = Date.now();
2496
+ return context;
2497
+ }
2498
+ /**
2499
+ * Проверяет, существует ли сессия.
2500
+ */
2501
+ hasSession(sessionId) {
2502
+ return this.sessions.has(sessionId || this.defaultSessionId);
2503
+ }
2504
+ /**
2505
+ * Закрывает сессию и освобождает ресурсы (browser, cache).
2506
+ */
2507
+ async closeSession(sessionId) {
2508
+ const normalizedId = sessionId || this.defaultSessionId;
2509
+ const context = this.sessions.get(normalizedId);
2510
+ if (context) {
2511
+ await context.browser.close();
2512
+ this.sessions.delete(normalizedId);
2513
+ }
2514
+ }
2515
+ /**
2516
+ * Закрывает все сессии (при shutdown сервера).
2517
+ */
2518
+ async closeAll() {
2519
+ this.stopCleanup();
2520
+ const closePromises = Array.from(this.sessions.values()).map(
2521
+ (context) => context.browser.close()
2522
+ );
2523
+ await Promise.all(closePromises);
2524
+ this.sessions.clear();
2525
+ }
2526
+ /**
2527
+ * Возвращает список активных сессий (для мониторинга).
2528
+ */
2529
+ getActiveSessions() {
2530
+ return Array.from(this.sessions.values()).map((context) => ({
2531
+ sessionId: context.sessionId,
2532
+ createdAt: context.createdAt,
2533
+ lastAccessedAt: context.lastAccessedAt,
2534
+ hasSnapshot: context.session.hasSnapshot()
2535
+ }));
2536
+ }
2537
+ /**
2538
+ * Возвращает количество активных сессий.
2539
+ */
2540
+ getSessionCount() {
2541
+ return this.sessions.size;
2542
+ }
2543
+ /**
2544
+ * Запускает периодический cleanup неактивных сессий.
2545
+ */
2546
+ startCleanup() {
2547
+ this.cleanupTimer = setInterval(() => {
2548
+ this.cleanupInactiveSessions();
2549
+ }, this.cleanupIntervalMs);
2550
+ if (this.cleanupTimer.unref) {
2551
+ this.cleanupTimer.unref();
2552
+ }
2553
+ }
2554
+ /**
2555
+ * Останавливает cleanup таймер.
2556
+ */
2557
+ stopCleanup() {
2558
+ if (this.cleanupTimer) {
2559
+ clearInterval(this.cleanupTimer);
2560
+ this.cleanupTimer = null;
2561
+ }
2562
+ }
2563
+ /**
2564
+ * Очищает сессии, которые не использовались дольше sessionTtlMs.
2565
+ */
2566
+ async cleanupInactiveSessions() {
2567
+ const now = Date.now();
2568
+ const sessionsToClose = [];
2569
+ for (const [sessionId, context] of this.sessions.entries()) {
2570
+ const idleTime = now - context.lastAccessedAt;
2571
+ if (idleTime > this.sessionTtlMs) {
2572
+ sessionsToClose.push(sessionId);
2573
+ }
2574
+ }
2575
+ for (const sessionId of sessionsToClose) {
2576
+ await this.closeSession(sessionId);
2577
+ }
1893
2578
  }
1894
2579
  };
1895
2580
 
@@ -1899,8 +2584,8 @@ var VSL_MCP_SERVER_VERSION = "0.1.0";
1899
2584
  // src/index.ts
1900
2585
  async function main() {
1901
2586
  const config = loadConfig();
1902
- const browser = new BrowserManager(config.browser);
1903
- const session = new ServerSession();
2587
+ const defaultSessionId = process.env.VSL_SESSION_ID || "default";
2588
+ const sessionManager = new SessionManager(config.browser, { defaultSessionId });
1904
2589
  const server = new Server(
1905
2590
  {
1906
2591
  name: "vsl-mcp-server",
@@ -1913,12 +2598,21 @@ async function main() {
1913
2598
  }
1914
2599
  }
1915
2600
  );
1916
- registerTools(server, config, browser, session);
1917
- registerResources(server, config, session);
2601
+ registerTools(server, config, sessionManager);
2602
+ registerResources(server, config, sessionManager);
1918
2603
  const transport = new StdioServerTransport();
1919
2604
  await server.connect(transport);
1920
2605
  console.error(`[VSL MCP Server] v${VSL_MCP_SERVER_VERSION} started (stdio transport)`);
1921
2606
  console.error(`[VSL MCP Server] Config: vision=${config.vision.provider}, model=${config.vision.model}`);
2607
+ console.error(`[VSL MCP Server] Per-session isolation enabled`);
2608
+ console.error(`[VSL MCP Server] Default session ID: ${defaultSessionId}`);
2609
+ const shutdown = async () => {
2610
+ console.error("[VSL MCP Server] Shutting down...");
2611
+ await sessionManager.closeAll();
2612
+ process.exit(0);
2613
+ };
2614
+ process.on("SIGINT", shutdown);
2615
+ process.on("SIGTERM", shutdown);
1922
2616
  }
1923
2617
  main().catch((error) => {
1924
2618
  console.error("[VSL MCP Server] Fatal error:", error);