@thinkingos/vsl-mcp-server 0.2.0 → 0.3.1

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
@@ -72,7 +72,79 @@ import {
72
72
  } from "@modelcontextprotocol/sdk/types.js";
73
73
 
74
74
  // src/tools/getSnapshot.ts
75
- import { segmentTree, buildVslDocument } from "@thinkingos/vsl-sdk";
75
+ import { isVslDiff } from "@thinkingos/vsl-sdk";
76
+ 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
  }
@@ -180,7 +285,7 @@ async function handleGetSnapshot(args, browser, session, _config) {
180
285
  if (!isAvailable) {
181
286
  return {
182
287
  status: "error",
183
- error: 'Playwright is not installed. Install it with: npm install playwright\nOr use vsl_read_page with mode="http" for static pages.'
288
+ error: "Playwright is not installed. Install it with: npm install playwright"
184
289
  };
185
290
  }
186
291
  const extractedElements = await browser.evaluate(extractDomTreeInBrowser);
@@ -188,14 +293,19 @@ async function handleGetSnapshot(args, browser, session, _config) {
188
293
  width: window.innerWidth,
189
294
  height: window.innerHeight
190
295
  }));
296
+ const url = args.url || await browser.evaluate(() => window.location.href);
191
297
  const title = await browser.evaluate(() => document.title);
192
- const segmentedElements = segmentTree(extractedElements);
193
- const vslDocument = buildVslDocument(segmentedElements, {
298
+ const input = {
194
299
  viewport,
195
- url: args.url || await browser.evaluate(() => window.location.href),
300
+ url,
196
301
  title,
197
302
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
198
- });
303
+ };
304
+ const result = session.snapshotFromElements(
305
+ extractedElements,
306
+ input
307
+ );
308
+ const currentDoc = isVslDiff(result) ? session.getSnapshot() : result;
199
309
  await browser.evaluate(
200
310
  (objects) => {
201
311
  function visit(obj) {
@@ -221,12 +331,40 @@ async function handleGetSnapshot(args, browser, session, _config) {
221
331
  visit(obj);
222
332
  }
223
333
  },
224
- vslDocument.objects
334
+ currentDoc.objects
225
335
  );
226
- session.setSnapshot(vslDocument);
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
+ }
227
364
  return {
228
365
  status: "success",
229
- data: vslDocument
366
+ data: filteredResult,
367
+ metadata
230
368
  };
231
369
  } catch (error) {
232
370
  return {
@@ -236,8 +374,23 @@ async function handleGetSnapshot(args, browser, session, _config) {
236
374
  }
237
375
  }
238
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
+
239
391
  // src/tools/getDiff.ts
240
392
  async function handleGetDiff(session) {
393
+ const startTime = Date.now();
241
394
  try {
242
395
  if (!session.hasSnapshot()) {
243
396
  return {
@@ -254,7 +407,8 @@ async function handleGetDiff(session) {
254
407
  }
255
408
  return {
256
409
  status: "success",
257
- data: diff
410
+ data: diff,
411
+ metadata: computeToolMetrics(diff, startTime)
258
412
  };
259
413
  } catch (error) {
260
414
  return {
@@ -266,6 +420,7 @@ async function handleGetDiff(session) {
266
420
 
267
421
  // src/tools/navigate.ts
268
422
  async function handleNavigate(args, browser) {
423
+ const startTime = Date.now();
269
424
  try {
270
425
  if (!args.url || typeof args.url !== "string") {
271
426
  return {
@@ -290,12 +445,14 @@ async function handleNavigate(args, browser) {
290
445
  }
291
446
  await browser.navigate(args.url);
292
447
  const title = await browser.evaluate(() => document.title);
448
+ const data = {
449
+ url: args.url,
450
+ title
451
+ };
293
452
  return {
294
453
  status: "success",
295
- data: {
296
- url: args.url,
297
- title
298
- }
454
+ data,
455
+ metadata: computeToolMetrics(data, startTime)
299
456
  };
300
457
  } catch (error) {
301
458
  return {
@@ -307,13 +464,15 @@ async function handleNavigate(args, browser) {
307
464
 
308
465
  // src/tools/clearCache.ts
309
466
  async function handleClearCache(session) {
467
+ const startTime = Date.now();
310
468
  try {
311
469
  session.clear();
312
470
  return {
313
471
  status: "success",
314
472
  data: {
315
473
  message: "Cache cleared. Next vsl_get_snapshot will create a new snapshot from scratch."
316
- }
474
+ },
475
+ metadata: computeToolMetrics({ cleared: true }, startTime)
317
476
  };
318
477
  } catch (error) {
319
478
  return {
@@ -340,7 +499,30 @@ var VALID_ACTIONS = [
340
499
  "download",
341
500
  "upload"
342
501
  ];
502
+ async function getStateAfterAction(session, browser, url) {
503
+ try {
504
+ const elements = await browser.evaluate(extractDomTreeInBrowser);
505
+ const viewport = await browser.evaluate(() => ({
506
+ width: window.innerWidth,
507
+ height: window.innerHeight
508
+ }));
509
+ const input = {
510
+ viewport,
511
+ url,
512
+ title: "",
513
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
514
+ };
515
+ session.snapshotFromElements(elements, input);
516
+ const diff = session.getDiff();
517
+ const snapshot = session.getSnapshot();
518
+ return { diff, snapshot };
519
+ } catch (error) {
520
+ console.warn("Failed to get state after action:", error);
521
+ return void 0;
522
+ }
523
+ }
343
524
  async function handleExecuteAction(args, browser, session) {
525
+ const startTime = Date.now();
344
526
  try {
345
527
  if (!args.action || typeof args.action !== "string") {
346
528
  return {
@@ -360,6 +542,29 @@ async function handleExecuteAction(args, browser, session) {
360
542
  error: `Unknown action: ${args.action}. Valid actions: ${VALID_ACTIONS.join(", ")}`
361
543
  };
362
544
  }
545
+ if (args.return_state !== void 0 && typeof args.return_state !== "boolean") {
546
+ return {
547
+ status: "error",
548
+ error: "return_state must be a boolean (true or false)"
549
+ };
550
+ }
551
+ if (args.action === "scroll" && args.value !== void 0) {
552
+ const VALID_SCROLL_VALUES = ["up", "down"];
553
+ if (!VALID_SCROLL_VALUES.includes(args.value)) {
554
+ return {
555
+ status: "error",
556
+ error: "Invalid scroll value: " + args.value + ". Valid values: " + VALID_SCROLL_VALUES.join(", ")
557
+ };
558
+ }
559
+ }
560
+ if ((args.action === "type" || args.action === "fill" || args.action === "select") && args.value !== void 0) {
561
+ if (typeof args.value !== "string") {
562
+ return {
563
+ status: "error",
564
+ error: "value must be a string for " + args.action + " action"
565
+ };
566
+ }
567
+ }
363
568
  if (!session.hasSnapshot()) {
364
569
  return {
365
570
  status: "error",
@@ -381,6 +586,20 @@ async function handleExecuteAction(args, browser, session) {
381
586
  await browser.navigate(snapshotUrl);
382
587
  }
383
588
  }
589
+ const hasVslIds = await browser.evaluate(() => {
590
+ return document.querySelector("[data-vsl-id]") !== null;
591
+ });
592
+ if (!hasVslIds) {
593
+ const elements = await browser.evaluate(extractDomTreeInBrowser);
594
+ const viewport = await browser.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
595
+ const input = {
596
+ viewport,
597
+ url: snapshotUrl || "",
598
+ title: "",
599
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
600
+ };
601
+ session.snapshotFromElements(elements, input);
602
+ }
384
603
  const selector = `[data-vsl-id="${args.target_id}"], #${args.target_id}, .${args.target_id}`;
385
604
  switch (args.action) {
386
605
  case "click":
@@ -461,7 +680,7 @@ async function handleExecuteAction(args, browser, session) {
461
680
  return id;
462
681
  }, args.value);
463
682
  const filename = args.value.split("/").pop() || "download";
464
- return {
683
+ const result2 = {
465
684
  status: "success",
466
685
  data: {
467
686
  action: args.action,
@@ -475,6 +694,18 @@ async function handleExecuteAction(args, browser, session) {
475
694
  }
476
695
  }
477
696
  };
697
+ if (args.return_state) {
698
+ try {
699
+ const currentUrl = await browser.evaluate(() => window.location.href);
700
+ const state = await getStateAfterAction(session, browser, currentUrl);
701
+ if (state && result2.data) {
702
+ result2.data.state = state;
703
+ }
704
+ } catch {
705
+ }
706
+ }
707
+ result2.metadata = computeToolMetrics(result2.data, startTime);
708
+ return result2;
478
709
  }
479
710
  await browser.evaluate((sel) => {
480
711
  const el = document.querySelector(sel);
@@ -497,7 +728,7 @@ async function handleExecuteAction(args, browser, session) {
497
728
  };
498
729
  }
499
730
  await browser.uploadFile(selector, filePaths);
500
- return {
731
+ const result2 = {
501
732
  status: "success",
502
733
  data: {
503
734
  action: args.action,
@@ -510,6 +741,18 @@ async function handleExecuteAction(args, browser, session) {
510
741
  }
511
742
  }
512
743
  };
744
+ if (args.return_state) {
745
+ try {
746
+ const currentUrl = await browser.evaluate(() => window.location.href);
747
+ const state = await getStateAfterAction(session, browser, currentUrl);
748
+ if (state && result2.data) {
749
+ result2.data.state = state;
750
+ }
751
+ } catch {
752
+ }
753
+ }
754
+ result2.metadata = computeToolMetrics(result2.data, startTime);
755
+ return result2;
513
756
  }
514
757
  default:
515
758
  return {
@@ -517,7 +760,7 @@ async function handleExecuteAction(args, browser, session) {
517
760
  error: `Action ${args.action} is not yet implemented`
518
761
  };
519
762
  }
520
- return {
763
+ const result = {
521
764
  status: "success",
522
765
  data: {
523
766
  action: args.action,
@@ -525,6 +768,18 @@ async function handleExecuteAction(args, browser, session) {
525
768
  success: true
526
769
  }
527
770
  };
771
+ if (args.return_state) {
772
+ try {
773
+ const currentUrl = await browser.evaluate(() => window.location.href);
774
+ const state = await getStateAfterAction(session, browser, currentUrl);
775
+ if (state && result.data) {
776
+ result.data.state = state;
777
+ }
778
+ } catch {
779
+ }
780
+ }
781
+ result.metadata = computeToolMetrics(result.data, startTime);
782
+ return result;
528
783
  } catch (error) {
529
784
  return {
530
785
  status: "error",
@@ -534,42 +789,69 @@ async function handleExecuteAction(args, browser, session) {
534
789
  }
535
790
 
536
791
  // src/tools/getVisual.ts
537
- async function handleGetVisual(args, browser) {
792
+ async function handleGetVisual(args, browser, session) {
793
+ const startTime = Date.now();
538
794
  try {
539
795
  if (!args.element_id || typeof args.element_id !== "string") {
540
796
  return {
541
- status: "error",
542
- error: "element_id is required"
797
+ content: [{ type: "text", text: "Error: element_id is required" }],
798
+ isError: true
799
+ };
800
+ }
801
+ if (args.auto_refresh !== void 0 && typeof args.auto_refresh !== "boolean") {
802
+ return {
803
+ content: [{ type: "text", text: "Error: auto_refresh must be a boolean (true or false)" }],
804
+ isError: true
543
805
  };
544
806
  }
545
807
  const isAvailable = await browser.isAvailable();
546
808
  if (!isAvailable) {
547
809
  return {
548
- status: "error",
549
- error: "Playwright is not installed. Install it with: npm install playwright"
810
+ content: [{ type: "text", text: "Error: Playwright is not installed. Install it with: npm install playwright" }],
811
+ isError: true,
812
+ possible_causes: ["Playwright \u043D\u0435 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D"],
813
+ suggestions: ["Run: npm install playwright", "Or: npm install -g playwright"]
550
814
  };
551
815
  }
552
816
  if (args.element_id === "root_0") {
553
817
  const page2 = await browser.getPage();
554
818
  const screenshotBuffer2 = await page2.screenshot({ type: "png", fullPage: false });
555
819
  const base64Image2 = screenshotBuffer2.toString("base64");
556
- return {
557
- status: "success",
558
- data: {
559
- element_id: args.element_id,
560
- image: base64Image2,
561
- mediaType: "image/png"
562
- }
820
+ const result = {
821
+ content: [
822
+ { type: "image", data: base64Image2, mimeType: "image/png" },
823
+ { type: "text", text: `Full page screenshot (${args.element_id})` }
824
+ ],
825
+ metadata: computeToolMetrics({ type: "full_page", element_id: args.element_id }, startTime)
563
826
  };
827
+ return result;
564
828
  }
565
829
  const selector = `[data-vsl-id="${args.element_id}"], #${args.element_id}, [id="${args.element_id}"]`;
566
- const elementExists = await browser.evaluate((sel) => {
830
+ let elementExists = await browser.evaluate((sel) => {
567
831
  return document.querySelector(sel) !== null;
568
832
  }, selector);
833
+ if (!elementExists && args.auto_refresh && session) {
834
+ await handleGetSnapshot({}, browser, session, { downloadsPath: "" });
835
+ elementExists = await browser.evaluate((sel) => {
836
+ return document.querySelector(sel) !== null;
837
+ }, selector);
838
+ }
569
839
  if (!elementExists) {
840
+ const suggestions = [
841
+ "Call vsl_get_snapshot to refresh DOM IDs",
842
+ "Use auto_refresh: true parameter to automatically refresh before search",
843
+ "Element may have been removed from DOM after navigation or action",
844
+ "DOM structure changed \u2014 IDs are index-based and may have shifted"
845
+ ];
570
846
  return {
571
- status: "error",
572
- 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).`
847
+ 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).` }],
848
+ isError: true,
849
+ possible_causes: [
850
+ "Snapshot is outdated \u2014 DOM changed after navigation or action",
851
+ "Element was removed from DOM",
852
+ "Using semantic ID from vsl_read_page instead of browser DOM ID from vsl_get_snapshot"
853
+ ],
854
+ suggestions
573
855
  };
574
856
  }
575
857
  const page = await browser.getPage();
@@ -581,8 +863,8 @@ async function handleGetVisual(args, browser) {
581
863
  }, selector);
582
864
  if (!rect) {
583
865
  return {
584
- status: "error",
585
- error: `Could not get bounding box for element: ${args.element_id}`
866
+ content: [{ type: "text", text: `Error: Could not get bounding box for element: ${args.element_id}` }],
867
+ isError: true
586
868
  };
587
869
  }
588
870
  const screenshotBuffer = await page.screenshot({
@@ -590,18 +872,18 @@ async function handleGetVisual(args, browser) {
590
872
  clip: rect
591
873
  });
592
874
  const base64Image = screenshotBuffer.toString("base64");
875
+ const metricsData = { type: "element", element_id: args.element_id, width: rect.width, height: rect.height };
593
876
  return {
594
- status: "success",
595
- data: {
596
- element_id: args.element_id,
597
- image: base64Image,
598
- mediaType: "image/png"
599
- }
877
+ content: [
878
+ { type: "image", data: base64Image, mimeType: "image/png" },
879
+ { type: "text", text: `Screenshot of element: ${args.element_id}` }
880
+ ],
881
+ metadata: computeToolMetrics(metricsData, startTime)
600
882
  };
601
883
  } catch (error) {
602
884
  return {
603
- status: "error",
604
- error: `vsl_get_visual failed: ${error instanceof Error ? error.message : String(error)}`
885
+ content: [{ type: "text", text: `Error: vsl_get_visual failed: ${error instanceof Error ? error.message : String(error)}` }],
886
+ isError: true
605
887
  };
606
888
  }
607
889
  }
@@ -872,6 +1154,19 @@ function determineActions(type, state, $el) {
872
1154
 
873
1155
  // src/tools/readPage.ts
874
1156
  async function handleReadPage(args, browser, session, _config) {
1157
+ const startTime = Date.now();
1158
+ if (!args.url || typeof args.url !== "string" || args.url.trim() === "") {
1159
+ return {
1160
+ status: "error",
1161
+ error: "url is required and must be a non-empty string"
1162
+ };
1163
+ }
1164
+ if (args.readable !== void 0 && typeof args.readable !== "boolean") {
1165
+ return {
1166
+ status: "error",
1167
+ error: "readable must be a boolean (true or false)"
1168
+ };
1169
+ }
875
1170
  try {
876
1171
  const readable = args.readable ?? false;
877
1172
  let detectedMode = "http";
@@ -901,21 +1196,23 @@ async function handleReadPage(args, browser, session, _config) {
901
1196
  const hasDiff2 = hadPreviousSnapshot2;
902
1197
  const readableHtml = readable ? applyReadableFilter(html) : html;
903
1198
  const content = extractTextContent(readableHtml);
1199
+ const data2 = {
1200
+ url: args.url,
1201
+ mode: "render",
1202
+ content,
1203
+ vslDocument,
1204
+ hasDiff: hasDiff2,
1205
+ metadata: {
1206
+ title: extractTitle(html),
1207
+ wordCount: countWords(content),
1208
+ isSpa,
1209
+ readableApplied: readable
1210
+ }
1211
+ };
904
1212
  return {
905
1213
  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
- }
1214
+ data: data2,
1215
+ tool_metadata: computeToolMetrics(data2, startTime)
919
1216
  };
920
1217
  }
921
1218
  if (!httpResult) {
@@ -924,64 +1221,85 @@ async function handleReadPage(args, browser, session, _config) {
924
1221
  const hadPreviousSnapshot = session.hasSnapshot();
925
1222
  session.setSnapshot(httpResult.vslDocument);
926
1223
  const hasDiff = hadPreviousSnapshot;
1224
+ const data = {
1225
+ url: args.url,
1226
+ mode: "http",
1227
+ content: httpResult.textContent,
1228
+ vslDocument: httpResult.vslDocument,
1229
+ hasDiff,
1230
+ metadata: {
1231
+ title: httpResult.title,
1232
+ wordCount: httpResult.wordCount,
1233
+ isSpa: httpResult.isSpa,
1234
+ readableApplied: httpResult.readableApplied
1235
+ }
1236
+ };
927
1237
  return {
928
1238
  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
- }
1239
+ data,
1240
+ tool_metadata: computeToolMetrics(data, startTime)
942
1241
  };
943
1242
  } catch (error) {
1243
+ const stack = error instanceof Error ? error.stack : String(error);
1244
+ console.error("vsl_read_page error:", stack);
944
1245
  return {
945
1246
  status: "error",
946
- error: `vsl_read_page failed: ${error instanceof Error ? error.message : String(error)}`
1247
+ error: `vsl_read_page failed: ${error instanceof Error ? error.message : String(error)}
1248
+ Stack: ${stack}`
947
1249
  };
948
1250
  }
949
1251
  }
950
1252
  async function extractVslFromPage(browser) {
951
- const domTree = await browser.evaluate(() => {
952
- const extractElement = (el) => {
953
- const rect = el.getBoundingClientRect();
954
- const computedStyle = window.getComputedStyle(el);
955
- return {
956
- tag: el.tagName.toLowerCase(),
957
- id: el.id || void 0,
958
- className: el.className || void 0,
959
- text: el.textContent?.trim().substring(0, 100) || void 0,
960
- rect: {
961
- x: rect.x,
962
- y: rect.y,
963
- width: rect.width,
964
- height: rect.height
965
- },
966
- role: el.getAttribute("role") || void 0,
967
- ariaLabel: el.getAttribute("aria-label") || void 0,
968
- ariaHidden: el.getAttribute("aria-hidden") || void 0,
969
- display: computedStyle.display,
970
- visibility: computedStyle.visibility,
971
- children: Array.from(el.children).filter((child) => {
972
- const style = window.getComputedStyle(child);
973
- return style.display !== "none" && style.visibility !== "hidden";
974
- }).map(extractElement)
1253
+ let domTree = null;
1254
+ try {
1255
+ domTree = await browser.evaluate(() => {
1256
+ const extractElement = (el) => {
1257
+ const rect2 = el.getBoundingClientRect();
1258
+ const computedStyle = window.getComputedStyle(el);
1259
+ return {
1260
+ tag: el.tagName.toLowerCase(),
1261
+ id: el.id || void 0,
1262
+ className: el.className || void 0,
1263
+ text: el.textContent?.trim().substring(0, 100) || void 0,
1264
+ rect: {
1265
+ x: rect2.x,
1266
+ y: rect2.y,
1267
+ width: rect2.width,
1268
+ height: rect2.height
1269
+ },
1270
+ role: el.getAttribute("role") || void 0,
1271
+ ariaLabel: el.getAttribute("aria-label") || void 0,
1272
+ ariaHidden: el.getAttribute("aria-hidden") || void 0,
1273
+ display: computedStyle.display,
1274
+ visibility: computedStyle.visibility,
1275
+ children: Array.from(el.children).filter((child) => {
1276
+ const style = window.getComputedStyle(child);
1277
+ return style.display !== "none" && style.visibility !== "hidden";
1278
+ }).map(extractElement)
1279
+ };
975
1280
  };
1281
+ return extractElement(document.documentElement);
1282
+ });
1283
+ } catch (error) {
1284
+ console.error("extractVslFromPage: browser.evaluate failed:", error);
1285
+ domTree = null;
1286
+ }
1287
+ if (!domTree || typeof domTree !== "object") {
1288
+ domTree = {
1289
+ tag: "html",
1290
+ rect: { x: 0, y: 0, width: 1280, height: 800 },
1291
+ children: []
976
1292
  };
977
- return extractElement(document.documentElement);
978
- });
1293
+ }
1294
+ const rect = domTree.rect;
1295
+ const viewportWidth = rect?.width ?? 1280;
1296
+ const viewportHeight = rect?.height ?? 800;
979
1297
  return {
980
1298
  vsl_version: "1.0.0",
981
1299
  canvas: {
982
1300
  viewport: {
983
- width: domTree.rect ? domTree.rect.width : 1280,
984
- height: domTree.rect ? domTree.rect.height : 800,
1301
+ width: viewportWidth,
1302
+ height: viewportHeight,
985
1303
  unit: "px"
986
1304
  },
987
1305
  background: "#ffffff",
@@ -1003,6 +1321,7 @@ async function extractVslFromPage(browser) {
1003
1321
 
1004
1322
  // src/tools/getFullJson.ts
1005
1323
  async function handleGetFullJson(_args, session) {
1324
+ const startTime = Date.now();
1006
1325
  try {
1007
1326
  if (!session.hasSnapshot()) {
1008
1327
  return {
@@ -1014,7 +1333,8 @@ async function handleGetFullJson(_args, session) {
1014
1333
  const snapshot = session.getSnapshot();
1015
1334
  return {
1016
1335
  status: "success",
1017
- data: snapshot
1336
+ data: snapshot,
1337
+ metadata: computeToolMetrics(snapshot, startTime)
1018
1338
  };
1019
1339
  } catch (error) {
1020
1340
  return {
@@ -1026,6 +1346,7 @@ async function handleGetFullJson(_args, session) {
1026
1346
 
1027
1347
  // src/tools/getTextBlock.ts
1028
1348
  async function handleGetTextBlock(args, session) {
1349
+ const startTime = Date.now();
1029
1350
  try {
1030
1351
  if (!args.block_id || typeof args.block_id !== "string") {
1031
1352
  return {
@@ -1053,12 +1374,14 @@ async function handleGetTextBlock(args, session) {
1053
1374
  error: `Text block not found: ${args.block_id}`
1054
1375
  };
1055
1376
  }
1377
+ const data = {
1378
+ block_id: args.block_id,
1379
+ text: fullText
1380
+ };
1056
1381
  return {
1057
1382
  status: "success",
1058
- data: {
1059
- block_id: args.block_id,
1060
- text: fullText
1061
- }
1383
+ data,
1384
+ metadata: computeToolMetrics(data, startTime)
1062
1385
  };
1063
1386
  } catch (error) {
1064
1387
  return {
@@ -1078,6 +1401,30 @@ async function handleDownload(args, browser, session) {
1078
1401
  error: "Either target_id (element to click) or value (URL to download) is required"
1079
1402
  };
1080
1403
  }
1404
+ if (args.target_id !== void 0 && typeof args.target_id !== "string") {
1405
+ return {
1406
+ status: "error",
1407
+ error: "target_id must be a string"
1408
+ };
1409
+ }
1410
+ if (args.value !== void 0 && typeof args.value !== "string") {
1411
+ return {
1412
+ status: "error",
1413
+ error: "value must be a string"
1414
+ };
1415
+ }
1416
+ if (args.timeout !== void 0 && (typeof args.timeout !== "number" || args.timeout <= 0)) {
1417
+ return {
1418
+ status: "error",
1419
+ error: "timeout must be a positive number (milliseconds)"
1420
+ };
1421
+ }
1422
+ if (args.save_path !== void 0 && typeof args.save_path !== "string") {
1423
+ return {
1424
+ status: "error",
1425
+ error: "save_path must be a string"
1426
+ };
1427
+ }
1081
1428
  if (args.target_id && !session.hasSnapshot()) {
1082
1429
  return {
1083
1430
  status: "error",
@@ -1143,6 +1490,12 @@ async function handleDownload(args, browser, session) {
1143
1490
  };
1144
1491
  }
1145
1492
  const latestDownload = downloads[downloads.length - 1];
1493
+ if (!latestDownload) {
1494
+ return {
1495
+ status: "error",
1496
+ error: "No active downloads found after triggering download."
1497
+ };
1498
+ }
1146
1499
  const downloadId = latestDownload.downloadId;
1147
1500
  const timeout = args.timeout;
1148
1501
  const result = await browser.waitForDownload(downloadId, timeout);
@@ -1183,13 +1536,22 @@ async function handleDownload(args, browser, session) {
1183
1536
  var VSL_TOOLS = [
1184
1537
  {
1185
1538
  name: "vsl_get_snapshot",
1186
- 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.",
1539
+ 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.",
1187
1540
  inputSchema: {
1188
1541
  type: "object",
1189
1542
  properties: {
1190
1543
  url: {
1191
1544
  type: "string",
1192
1545
  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)"
1546
+ },
1547
+ detail_level: {
1548
+ type: "string",
1549
+ enum: ["low", "medium", "high"],
1550
+ 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'."
1551
+ },
1552
+ ttl: {
1553
+ type: "number",
1554
+ 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."
1193
1555
  }
1194
1556
  }
1195
1557
  }
@@ -1204,7 +1566,7 @@ var VSL_TOOLS = [
1204
1566
  },
1205
1567
  {
1206
1568
  name: "vsl_execute_action",
1207
- 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}.",
1569
+ 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.",
1208
1570
  inputSchema: {
1209
1571
  type: "object",
1210
1572
  properties: {
@@ -1219,6 +1581,10 @@ var VSL_TOOLS = [
1219
1581
  value: {
1220
1582
  type: "string",
1221
1583
  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)"
1584
+ },
1585
+ return_state: {
1586
+ type: "boolean",
1587
+ 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: false."
1222
1588
  }
1223
1589
  },
1224
1590
  required: ["action", "target_id"]
@@ -1248,13 +1614,17 @@ var VSL_TOOLS = [
1248
1614
  },
1249
1615
  {
1250
1616
  name: "vsl_get_visual",
1251
- 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}.",
1617
+ 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.",
1252
1618
  inputSchema: {
1253
1619
  type: "object",
1254
1620
  properties: {
1255
1621
  element_id: {
1256
1622
  type: "string",
1257
1623
  description: "ID \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430 \u0432 VSL JSON"
1624
+ },
1625
+ auto_refresh: {
1626
+ type: "boolean",
1627
+ 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."
1258
1628
  }
1259
1629
  },
1260
1630
  required: ["element_id"]
@@ -1262,7 +1632,7 @@ var VSL_TOOLS = [
1262
1632
  },
1263
1633
  {
1264
1634
  name: "vsl_read_page",
1265
- description: "\u0413\u0438\u0431\u0440\u0438\u0434\u043D\u043E\u0435 \u0447\u0442\u0435\u043D\u0438\u0435 \u0432\u0435\u0431-\u0441\u0442\u0440\u0430\u043D\u0438\u0446. mode=auto (\u043F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E): \u0441\u0442\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438\u0435 \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u044B \u0447\u0438\u0442\u0430\u044E\u0442\u0441\u044F \u0447\u0435\u0440\u0435\u0437 HTTP (\u0431\u044B\u0441\u0442\u0440\u043E), SPA \u0440\u0435\u043D\u0434\u0435\u0440\u044F\u0442\u0441\u044F \u0447\u0435\u0440\u0435\u0437 \u0431\u0440\u0430\u0443\u0437\u0435\u0440. mode=http: \u0442\u043E\u043B\u044C\u043A\u043E HTTP (\u0431\u0435\u0437 \u0431\u0440\u0430\u0443\u0437\u0435\u0440\u0430). mode=render: \u0432\u0441\u0435\u0433\u0434\u0430 \u0440\u0435\u043D\u0434\u0435\u0440\u0438\u0442\u044C \u0447\u0435\u0440\u0435\u0437 \u0431\u0440\u0430\u0443\u0437\u0435\u0440. readable=true: \u0444\u0438\u043B\u044C\u0442\u0440\u0443\u0435\u0442 \u0448\u0443\u043C (\u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u044F, \u0444\u0443\u0442\u0435\u0440\u044B, cookie-\u0431\u0430\u043D\u043D\u0435\u0440\u044B) \u0434\u043B\u044F \u0447\u0438\u0441\u0442\u043E\u0433\u043E \u043A\u043E\u043D\u0442\u0435\u043D\u0442\u0430. \u041F\u0440\u0438 \u043F\u043E\u0432\u0442\u043E\u0440\u043D\u044B\u0445 \u0432\u044B\u0437\u043E\u0432\u0430\u0445 \u0432\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 diff (\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F), \u0430 \u043D\u0435 \u043F\u043E\u043B\u043D\u044B\u0439 \u043A\u043E\u043D\u0442\u0435\u043D\u0442. \u041F\u0440\u0438\u043C\u0435\u0440: {url:https://example.com, mode:auto, readable:true}.",
1635
+ 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}.',
1266
1636
  inputSchema: {
1267
1637
  type: "object",
1268
1638
  properties: {
@@ -1270,11 +1640,6 @@ var VSL_TOOLS = [
1270
1640
  type: "string",
1271
1641
  description: "URL \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u044B \u0434\u043B\u044F \u0447\u0442\u0435\u043D\u0438\u044F"
1272
1642
  },
1273
- mode: {
1274
- type: "string",
1275
- enum: ["auto", "http", "render"],
1276
- description: "\u0420\u0435\u0436\u0438\u043C \u0447\u0442\u0435\u043D\u0438\u044F: auto (\u0430\u0432\u0442\u043E-\u0434\u0435\u0442\u0435\u043A\u0442), http (\u0442\u043E\u043B\u044C\u043A\u043E HTTP), render (\u0432\u0441\u0435\u0433\u0434\u0430 \u0440\u0435\u043D\u0434\u0435\u0440\u0438\u0442\u044C)"
1277
- },
1278
1643
  readable: {
1279
1644
  type: "boolean",
1280
1645
  description: "Readable-\u0440\u0435\u0436\u0438\u043C: \u0444\u0438\u043B\u044C\u0442\u0440\u0430\u0446\u0438\u044F \u0448\u0443\u043C\u0430 (nav, footer, cookie banners) \u0434\u043B\u044F \u0447\u0438\u0441\u0442\u043E\u0433\u043E \u043A\u043E\u043D\u0442\u0435\u043D\u0442\u0430"
@@ -1331,14 +1696,16 @@ var VSL_TOOLS = [
1331
1696
  }
1332
1697
  }
1333
1698
  ];
1334
- function registerTools(server, config, browser, session) {
1699
+ function registerTools(server, config, sessionManager) {
1335
1700
  server.setRequestHandler(ListToolsRequestSchema, async () => {
1336
1701
  return {
1337
1702
  tools: VSL_TOOLS
1338
1703
  };
1339
1704
  });
1340
1705
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
1341
- const { name, arguments: args } = request.params;
1706
+ const { name, arguments: args, _meta } = request.params;
1707
+ const sessionId = _meta?.sessionId ?? sessionManager.getDefaultSessionId();
1708
+ const { browser, session } = sessionManager.getSession(sessionId);
1342
1709
  try {
1343
1710
  let result;
1344
1711
  switch (name) {
@@ -1358,7 +1725,7 @@ function registerTools(server, config, browser, session) {
1358
1725
  result = await handleClearCache(session);
1359
1726
  break;
1360
1727
  case "vsl_get_visual":
1361
- result = await handleGetVisual(args, browser);
1728
+ result = await handleGetVisual(args, browser, session);
1362
1729
  break;
1363
1730
  case "vsl_read_page":
1364
1731
  result = await handleReadPage(args, browser, session, config);
@@ -1428,7 +1795,7 @@ var VSL_RESOURCES = [
1428
1795
  mimeType: "application/json"
1429
1796
  }
1430
1797
  ];
1431
- function registerResources(server, _config, session) {
1798
+ function registerResources(server, _config, sessionManager) {
1432
1799
  server.setRequestHandler(ListResourcesRequestSchema, async () => {
1433
1800
  return {
1434
1801
  resources: VSL_RESOURCES
@@ -1436,6 +1803,9 @@ function registerResources(server, _config, session) {
1436
1803
  });
1437
1804
  server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
1438
1805
  const { uri } = request.params;
1806
+ const sessionId = request.params._meta?.sessionId ?? sessionManager.getDefaultSessionId();
1807
+ const { session } = sessionManager.getSession(sessionId);
1808
+ ensureSubscribed(sessionId, session);
1439
1809
  switch (uri) {
1440
1810
  case "vsl://current":
1441
1811
  try {
@@ -1504,14 +1874,19 @@ function registerResources(server, _config, session) {
1504
1874
  throw new Error(`Unknown resource: ${uri}`);
1505
1875
  }
1506
1876
  });
1507
- session.setOnSnapshotChange(() => {
1508
- server.sendResourceUpdated({ uri: "vsl://current" }).catch(() => {
1509
- });
1510
- if (session.getDiff()) {
1511
- server.sendResourceUpdated({ uri: "vsl://diff" }).catch(() => {
1877
+ const subscribedSessions = /* @__PURE__ */ new Set();
1878
+ function ensureSubscribed(sessionId, session) {
1879
+ if (subscribedSessions.has(sessionId)) return;
1880
+ subscribedSessions.add(sessionId);
1881
+ session.setOnSnapshotChange(() => {
1882
+ server.sendResourceUpdated({ uri: "vsl://current" }).catch(() => {
1512
1883
  });
1513
- }
1514
- });
1884
+ if (session.getDiff()) {
1885
+ server.sendResourceUpdated({ uri: "vsl://diff" }).catch(() => {
1886
+ });
1887
+ }
1888
+ });
1889
+ }
1515
1890
  }
1516
1891
 
1517
1892
  // src/browser/manager.ts
@@ -1552,7 +1927,7 @@ var BrowserManager = class {
1552
1927
  const pw = await this.loadPlaywright();
1553
1928
  if (!pw) {
1554
1929
  throw new Error(
1555
- 'Playwright is not installed. Install it with: npm install playwright\nOr use vsl_read_page with mode="http" for static pages (no browser required).'
1930
+ "Playwright is not installed. Install it with: npm install playwright"
1556
1931
  );
1557
1932
  }
1558
1933
  this.browser = await pw.chromium.launch({
@@ -1606,6 +1981,7 @@ var BrowserManager = class {
1606
1981
  /**
1607
1982
  * Выполняет JavaScript в контексте страницы.
1608
1983
  */
1984
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1609
1985
  async evaluate(fn, ...args) {
1610
1986
  const page = await this.getPage();
1611
1987
  return page.evaluate(fn, ...args);
@@ -1695,7 +2071,8 @@ var BrowserManager = class {
1695
2071
  if (isAbsolute) {
1696
2072
  await download.saveAs(savePath);
1697
2073
  } else {
1698
- const resolvedBase = path2.resolve(this.config.downloadsPath.replace(/^~/, os.homedir()));
2074
+ const downloadsPath = this.config.downloadsPath ?? os.tmpdir();
2075
+ const resolvedBase = path2.resolve(downloadsPath.replace(/^~/, os.homedir()));
1699
2076
  const resolvedSave = path2.resolve(resolvedBase, savePath);
1700
2077
  if (!resolvedSave.startsWith(resolvedBase + path2.sep) && resolvedSave !== resolvedBase) {
1701
2078
  throw new Error(`Path traversal detected: save_path '${savePath}' escapes downloads directory '${resolvedBase}'`);
@@ -1781,10 +2158,11 @@ var BrowserManager = class {
1781
2158
  };
1782
2159
 
1783
2160
  // src/session/serverSession.ts
1784
- import { diffVslDocuments } from "@thinkingos/vsl-sdk";
2161
+ import { diffVslDocuments, segmentTree, buildVslDocument } from "@thinkingos/vsl-sdk";
1785
2162
  var ServerSession = class {
1786
- currentSnapshot = null;
1787
- previousSnapshot = null;
2163
+ currentDocument = null;
2164
+ previousDocument = null;
2165
+ version = 0;
1788
2166
  onSnapshotChange = null;
1789
2167
  /**
1790
2168
  * Регистрирует callback для уведомлений об изменении snapshot.
@@ -1794,49 +2172,216 @@ var ServerSession = class {
1794
2172
  this.onSnapshotChange = callback;
1795
2173
  }
1796
2174
  /**
1797
- * Устанавливает новый snapshot.
1798
- * Предыдущий snapshot сохраняется для вычисления diff.
1799
- * Вызывает onSnapshotChange callback если зарегистрирован.
2175
+ * Устанавливает новый snapshot (VslDocument).
2176
+ * Сохраняет текущий документ как previousDocument для getDiff().
1800
2177
  */
1801
2178
  setSnapshot(doc) {
1802
- this.previousSnapshot = this.currentSnapshot;
1803
- this.currentSnapshot = doc;
2179
+ if (this.currentDocument) {
2180
+ this.previousDocument = this.currentDocument;
2181
+ }
2182
+ this.currentDocument = doc;
2183
+ this.version += 1;
2184
+ if (this.onSnapshotChange) {
2185
+ this.onSnapshotChange();
2186
+ }
2187
+ }
2188
+ /**
2189
+ * Делает snapshot из pre-extracted elements через SDK pipeline.
2190
+ * segmentTree → buildVslDocument → store as current document.
2191
+ * Возвращает VslDocument (первый вызов) или VslDiff (последующие).
2192
+ */
2193
+ snapshotFromElements(extractedElements, input) {
2194
+ const segmented = segmentTree(extractedElements);
2195
+ const doc = buildVslDocument(segmented, {
2196
+ viewport: input.viewport,
2197
+ timestamp: input.timestamp,
2198
+ url: input.url,
2199
+ title: input.title
2200
+ });
2201
+ if (this.currentDocument) {
2202
+ this.previousDocument = this.currentDocument;
2203
+ }
2204
+ this.currentDocument = doc;
2205
+ this.version += 1;
1804
2206
  if (this.onSnapshotChange) {
1805
2207
  this.onSnapshotChange();
1806
2208
  }
2209
+ if (!this.previousDocument) {
2210
+ return doc;
2211
+ }
2212
+ return diffVslDocuments(this.previousDocument, doc, {
2213
+ diffVersion: this.version,
2214
+ baseVersion: this.version - 1
2215
+ });
1807
2216
  }
1808
2217
  /**
1809
- * Возвращает текущий snapshot.
2218
+ * Возвращает текущий snapshot (последний полный документ).
1810
2219
  * @throws Error если snapshot не установлен
1811
2220
  */
1812
2221
  getSnapshot() {
1813
- if (!this.currentSnapshot) {
2222
+ if (!this.currentDocument) {
1814
2223
  throw new Error("No snapshot available. Call vsl_get_snapshot first.");
1815
2224
  }
1816
- return this.currentSnapshot;
2225
+ return this.currentDocument;
1817
2226
  }
1818
2227
  /**
1819
2228
  * Проверяет, есть ли текущий snapshot.
1820
2229
  */
1821
2230
  hasSnapshot() {
1822
- return this.currentSnapshot !== null;
2231
+ return this.currentDocument !== null;
1823
2232
  }
1824
2233
  /**
1825
2234
  * Вычисляет diff между текущим и предыдущим snapshot.
2235
+ * Использует SDK функцию diffVslDocuments.
1826
2236
  * @returns VslDiff или null если нет предыдущего snapshot
1827
2237
  */
1828
2238
  getDiff() {
1829
- if (!this.currentSnapshot || !this.previousSnapshot) {
2239
+ if (!this.currentDocument || !this.previousDocument) {
1830
2240
  return null;
1831
2241
  }
1832
- return diffVslDocuments(this.previousSnapshot, this.currentSnapshot, { diffVersion: 2, baseVersion: 1 });
2242
+ return diffVslDocuments(this.previousDocument, this.currentDocument, {
2243
+ diffVersion: this.version,
2244
+ baseVersion: this.version - 1
2245
+ });
1833
2246
  }
1834
2247
  /**
1835
- * Сбрасывает сессию (кэш).
2248
+ * Сбрасывает сессию (состояние).
1836
2249
  */
1837
2250
  clear() {
1838
- this.currentSnapshot = null;
1839
- this.previousSnapshot = null;
2251
+ this.currentDocument = null;
2252
+ this.previousDocument = null;
2253
+ this.version = 0;
2254
+ }
2255
+ /**
2256
+ * Возвращает текущую версию snapshot.
2257
+ */
2258
+ getVersion() {
2259
+ return this.version;
2260
+ }
2261
+ };
2262
+
2263
+ // src/session/sessionManager.ts
2264
+ var SessionManager = class {
2265
+ sessions = /* @__PURE__ */ new Map();
2266
+ browserConfig;
2267
+ cleanupIntervalMs;
2268
+ sessionTtlMs;
2269
+ defaultSessionId;
2270
+ cleanupTimer = null;
2271
+ constructor(browserConfig, options) {
2272
+ this.browserConfig = browserConfig;
2273
+ this.cleanupIntervalMs = options?.cleanupIntervalMs ?? 6e4;
2274
+ this.sessionTtlMs = options?.sessionTtlMs ?? 3e5;
2275
+ this.defaultSessionId = options?.defaultSessionId ?? "default";
2276
+ this.startCleanup();
2277
+ }
2278
+ /**
2279
+ * Возвращает default session ID (из env VSL_SESSION_ID или 'default').
2280
+ * Используется для fallback, когда _meta.sessionId не передан.
2281
+ */
2282
+ getDefaultSessionId() {
2283
+ return this.defaultSessionId;
2284
+ }
2285
+ /**
2286
+ * Получает или создаёт сессию по sessionId.
2287
+ * Если сессия не существует — создаёт новую с собственным BrowserManager и ServerSession.
2288
+ */
2289
+ getSession(sessionId) {
2290
+ const normalizedId = sessionId || this.defaultSessionId;
2291
+ if (!this.sessions.has(normalizedId)) {
2292
+ const context2 = {
2293
+ sessionId: normalizedId,
2294
+ browser: new BrowserManager(this.browserConfig),
2295
+ session: new ServerSession(),
2296
+ createdAt: Date.now(),
2297
+ lastAccessedAt: Date.now()
2298
+ };
2299
+ this.sessions.set(normalizedId, context2);
2300
+ }
2301
+ const context = this.sessions.get(normalizedId);
2302
+ context.lastAccessedAt = Date.now();
2303
+ return context;
2304
+ }
2305
+ /**
2306
+ * Проверяет, существует ли сессия.
2307
+ */
2308
+ hasSession(sessionId) {
2309
+ return this.sessions.has(sessionId || this.defaultSessionId);
2310
+ }
2311
+ /**
2312
+ * Закрывает сессию и освобождает ресурсы (browser, cache).
2313
+ */
2314
+ async closeSession(sessionId) {
2315
+ const normalizedId = sessionId || this.defaultSessionId;
2316
+ const context = this.sessions.get(normalizedId);
2317
+ if (context) {
2318
+ await context.browser.close();
2319
+ this.sessions.delete(normalizedId);
2320
+ }
2321
+ }
2322
+ /**
2323
+ * Закрывает все сессии (при shutdown сервера).
2324
+ */
2325
+ async closeAll() {
2326
+ this.stopCleanup();
2327
+ const closePromises = Array.from(this.sessions.values()).map(
2328
+ (context) => context.browser.close()
2329
+ );
2330
+ await Promise.all(closePromises);
2331
+ this.sessions.clear();
2332
+ }
2333
+ /**
2334
+ * Возвращает список активных сессий (для мониторинга).
2335
+ */
2336
+ getActiveSessions() {
2337
+ return Array.from(this.sessions.values()).map((context) => ({
2338
+ sessionId: context.sessionId,
2339
+ createdAt: context.createdAt,
2340
+ lastAccessedAt: context.lastAccessedAt,
2341
+ hasSnapshot: context.session.hasSnapshot()
2342
+ }));
2343
+ }
2344
+ /**
2345
+ * Возвращает количество активных сессий.
2346
+ */
2347
+ getSessionCount() {
2348
+ return this.sessions.size;
2349
+ }
2350
+ /**
2351
+ * Запускает периодический cleanup неактивных сессий.
2352
+ */
2353
+ startCleanup() {
2354
+ this.cleanupTimer = setInterval(() => {
2355
+ this.cleanupInactiveSessions();
2356
+ }, this.cleanupIntervalMs);
2357
+ if (this.cleanupTimer.unref) {
2358
+ this.cleanupTimer.unref();
2359
+ }
2360
+ }
2361
+ /**
2362
+ * Останавливает cleanup таймер.
2363
+ */
2364
+ stopCleanup() {
2365
+ if (this.cleanupTimer) {
2366
+ clearInterval(this.cleanupTimer);
2367
+ this.cleanupTimer = null;
2368
+ }
2369
+ }
2370
+ /**
2371
+ * Очищает сессии, которые не использовались дольше sessionTtlMs.
2372
+ */
2373
+ async cleanupInactiveSessions() {
2374
+ const now = Date.now();
2375
+ const sessionsToClose = [];
2376
+ for (const [sessionId, context] of this.sessions.entries()) {
2377
+ const idleTime = now - context.lastAccessedAt;
2378
+ if (idleTime > this.sessionTtlMs) {
2379
+ sessionsToClose.push(sessionId);
2380
+ }
2381
+ }
2382
+ for (const sessionId of sessionsToClose) {
2383
+ await this.closeSession(sessionId);
2384
+ }
1840
2385
  }
1841
2386
  };
1842
2387
 
@@ -1846,8 +2391,8 @@ var VSL_MCP_SERVER_VERSION = "0.1.0";
1846
2391
  // src/index.ts
1847
2392
  async function main() {
1848
2393
  const config = loadConfig();
1849
- const browser = new BrowserManager(config.browser);
1850
- const session = new ServerSession();
2394
+ const defaultSessionId = process.env.VSL_SESSION_ID || "default";
2395
+ const sessionManager = new SessionManager(config.browser, { defaultSessionId });
1851
2396
  const server = new Server(
1852
2397
  {
1853
2398
  name: "vsl-mcp-server",
@@ -1860,12 +2405,21 @@ async function main() {
1860
2405
  }
1861
2406
  }
1862
2407
  );
1863
- registerTools(server, config, browser, session);
1864
- registerResources(server, config, session);
2408
+ registerTools(server, config, sessionManager);
2409
+ registerResources(server, config, sessionManager);
1865
2410
  const transport = new StdioServerTransport();
1866
2411
  await server.connect(transport);
1867
2412
  console.error(`[VSL MCP Server] v${VSL_MCP_SERVER_VERSION} started (stdio transport)`);
1868
2413
  console.error(`[VSL MCP Server] Config: vision=${config.vision.provider}, model=${config.vision.model}`);
2414
+ console.error(`[VSL MCP Server] Per-session isolation enabled`);
2415
+ console.error(`[VSL MCP Server] Default session ID: ${defaultSessionId}`);
2416
+ const shutdown = async () => {
2417
+ console.error("[VSL MCP Server] Shutting down...");
2418
+ await sessionManager.closeAll();
2419
+ process.exit(0);
2420
+ };
2421
+ process.on("SIGINT", shutdown);
2422
+ process.on("SIGTERM", shutdown);
1869
2423
  }
1870
2424
  main().catch((error) => {
1871
2425
  console.error("[VSL MCP Server] Fatal error:", error);