@thinkingos/vsl-mcp-server 0.3.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
@@ -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 {
@@ -270,6 +420,7 @@ async function handleGetDiff(session) {
270
420
 
271
421
  // src/tools/navigate.ts
272
422
  async function handleNavigate(args, browser) {
423
+ const startTime = Date.now();
273
424
  try {
274
425
  if (!args.url || typeof args.url !== "string") {
275
426
  return {
@@ -294,12 +445,14 @@ async function handleNavigate(args, browser) {
294
445
  }
295
446
  await browser.navigate(args.url);
296
447
  const title = await browser.evaluate(() => document.title);
448
+ const data = {
449
+ url: args.url,
450
+ title
451
+ };
297
452
  return {
298
453
  status: "success",
299
- data: {
300
- url: args.url,
301
- title
302
- }
454
+ data,
455
+ metadata: computeToolMetrics(data, startTime)
303
456
  };
304
457
  } catch (error) {
305
458
  return {
@@ -311,13 +464,15 @@ async function handleNavigate(args, browser) {
311
464
 
312
465
  // src/tools/clearCache.ts
313
466
  async function handleClearCache(session) {
467
+ const startTime = Date.now();
314
468
  try {
315
469
  session.clear();
316
470
  return {
317
471
  status: "success",
318
472
  data: {
319
473
  message: "Cache cleared. Next vsl_get_snapshot will create a new snapshot from scratch."
320
- }
474
+ },
475
+ metadata: computeToolMetrics({ cleared: true }, startTime)
321
476
  };
322
477
  } catch (error) {
323
478
  return {
@@ -344,7 +499,30 @@ var VALID_ACTIONS = [
344
499
  "download",
345
500
  "upload"
346
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
+ }
347
524
  async function handleExecuteAction(args, browser, session) {
525
+ const startTime = Date.now();
348
526
  try {
349
527
  if (!args.action || typeof args.action !== "string") {
350
528
  return {
@@ -364,6 +542,29 @@ async function handleExecuteAction(args, browser, session) {
364
542
  error: `Unknown action: ${args.action}. Valid actions: ${VALID_ACTIONS.join(", ")}`
365
543
  };
366
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
+ }
367
568
  if (!session.hasSnapshot()) {
368
569
  return {
369
570
  status: "error",
@@ -385,6 +586,20 @@ async function handleExecuteAction(args, browser, session) {
385
586
  await browser.navigate(snapshotUrl);
386
587
  }
387
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
+ }
388
603
  const selector = `[data-vsl-id="${args.target_id}"], #${args.target_id}, .${args.target_id}`;
389
604
  switch (args.action) {
390
605
  case "click":
@@ -465,7 +680,7 @@ async function handleExecuteAction(args, browser, session) {
465
680
  return id;
466
681
  }, args.value);
467
682
  const filename = args.value.split("/").pop() || "download";
468
- return {
683
+ const result2 = {
469
684
  status: "success",
470
685
  data: {
471
686
  action: args.action,
@@ -479,6 +694,18 @@ async function handleExecuteAction(args, browser, session) {
479
694
  }
480
695
  }
481
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;
482
709
  }
483
710
  await browser.evaluate((sel) => {
484
711
  const el = document.querySelector(sel);
@@ -501,7 +728,7 @@ async function handleExecuteAction(args, browser, session) {
501
728
  };
502
729
  }
503
730
  await browser.uploadFile(selector, filePaths);
504
- return {
731
+ const result2 = {
505
732
  status: "success",
506
733
  data: {
507
734
  action: args.action,
@@ -514,6 +741,18 @@ async function handleExecuteAction(args, browser, session) {
514
741
  }
515
742
  }
516
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;
517
756
  }
518
757
  default:
519
758
  return {
@@ -521,7 +760,7 @@ async function handleExecuteAction(args, browser, session) {
521
760
  error: `Action ${args.action} is not yet implemented`
522
761
  };
523
762
  }
524
- return {
763
+ const result = {
525
764
  status: "success",
526
765
  data: {
527
766
  action: args.action,
@@ -529,6 +768,18 @@ async function handleExecuteAction(args, browser, session) {
529
768
  success: true
530
769
  }
531
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;
532
783
  } catch (error) {
533
784
  return {
534
785
  status: "error",
@@ -538,7 +789,8 @@ async function handleExecuteAction(args, browser, session) {
538
789
  }
539
790
 
540
791
  // src/tools/getVisual.ts
541
- async function handleGetVisual(args, browser) {
792
+ async function handleGetVisual(args, browser, session) {
793
+ const startTime = Date.now();
542
794
  try {
543
795
  if (!args.element_id || typeof args.element_id !== "string") {
544
796
  return {
@@ -546,32 +798,60 @@ async function handleGetVisual(args, browser) {
546
798
  isError: true
547
799
  };
548
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
805
+ };
806
+ }
549
807
  const isAvailable = await browser.isAvailable();
550
808
  if (!isAvailable) {
551
809
  return {
552
810
  content: [{ type: "text", text: "Error: Playwright is not installed. Install it with: npm install playwright" }],
553
- isError: true
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"]
554
814
  };
555
815
  }
556
816
  if (args.element_id === "root_0") {
557
817
  const page2 = await browser.getPage();
558
818
  const screenshotBuffer2 = await page2.screenshot({ type: "png", fullPage: false });
559
819
  const base64Image2 = screenshotBuffer2.toString("base64");
560
- return {
820
+ const result = {
561
821
  content: [
562
822
  { type: "image", data: base64Image2, mimeType: "image/png" },
563
823
  { type: "text", text: `Full page screenshot (${args.element_id})` }
564
- ]
824
+ ],
825
+ metadata: computeToolMetrics({ type: "full_page", element_id: args.element_id }, startTime)
565
826
  };
827
+ return result;
566
828
  }
567
829
  const selector = `[data-vsl-id="${args.element_id}"], #${args.element_id}, [id="${args.element_id}"]`;
568
- const elementExists = await browser.evaluate((sel) => {
830
+ let elementExists = await browser.evaluate((sel) => {
569
831
  return document.querySelector(sel) !== null;
570
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
+ }
571
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
+ ];
572
846
  return {
573
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).` }],
574
- isError: true
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
575
855
  };
576
856
  }
577
857
  const page = await browser.getPage();
@@ -592,11 +872,13 @@ async function handleGetVisual(args, browser) {
592
872
  clip: rect
593
873
  });
594
874
  const base64Image = screenshotBuffer.toString("base64");
875
+ const metricsData = { type: "element", element_id: args.element_id, width: rect.width, height: rect.height };
595
876
  return {
596
877
  content: [
597
878
  { type: "image", data: base64Image, mimeType: "image/png" },
598
879
  { type: "text", text: `Screenshot of element: ${args.element_id}` }
599
- ]
880
+ ],
881
+ metadata: computeToolMetrics(metricsData, startTime)
600
882
  };
601
883
  } catch (error) {
602
884
  return {
@@ -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,21 +1221,23 @@ 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) {
944
1243
  const stack = error instanceof Error ? error.stack : String(error);
@@ -1022,6 +1321,7 @@ async function extractVslFromPage(browser) {
1022
1321
 
1023
1322
  // src/tools/getFullJson.ts
1024
1323
  async function handleGetFullJson(_args, session) {
1324
+ const startTime = Date.now();
1025
1325
  try {
1026
1326
  if (!session.hasSnapshot()) {
1027
1327
  return {
@@ -1033,7 +1333,8 @@ async function handleGetFullJson(_args, session) {
1033
1333
  const snapshot = session.getSnapshot();
1034
1334
  return {
1035
1335
  status: "success",
1036
- data: snapshot
1336
+ data: snapshot,
1337
+ metadata: computeToolMetrics(snapshot, startTime)
1037
1338
  };
1038
1339
  } catch (error) {
1039
1340
  return {
@@ -1045,6 +1346,7 @@ async function handleGetFullJson(_args, session) {
1045
1346
 
1046
1347
  // src/tools/getTextBlock.ts
1047
1348
  async function handleGetTextBlock(args, session) {
1349
+ const startTime = Date.now();
1048
1350
  try {
1049
1351
  if (!args.block_id || typeof args.block_id !== "string") {
1050
1352
  return {
@@ -1072,12 +1374,14 @@ async function handleGetTextBlock(args, session) {
1072
1374
  error: `Text block not found: ${args.block_id}`
1073
1375
  };
1074
1376
  }
1377
+ const data = {
1378
+ block_id: args.block_id,
1379
+ text: fullText
1380
+ };
1075
1381
  return {
1076
1382
  status: "success",
1077
- data: {
1078
- block_id: args.block_id,
1079
- text: fullText
1080
- }
1383
+ data,
1384
+ metadata: computeToolMetrics(data, startTime)
1081
1385
  };
1082
1386
  } catch (error) {
1083
1387
  return {
@@ -1097,6 +1401,30 @@ async function handleDownload(args, browser, session) {
1097
1401
  error: "Either target_id (element to click) or value (URL to download) is required"
1098
1402
  };
1099
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
+ }
1100
1428
  if (args.target_id && !session.hasSnapshot()) {
1101
1429
  return {
1102
1430
  status: "error",
@@ -1162,6 +1490,12 @@ async function handleDownload(args, browser, session) {
1162
1490
  };
1163
1491
  }
1164
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
+ }
1165
1499
  const downloadId = latestDownload.downloadId;
1166
1500
  const timeout = args.timeout;
1167
1501
  const result = await browser.waitForDownload(downloadId, timeout);
@@ -1202,13 +1536,22 @@ async function handleDownload(args, browser, session) {
1202
1536
  var VSL_TOOLS = [
1203
1537
  {
1204
1538
  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.",
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.",
1206
1540
  inputSchema: {
1207
1541
  type: "object",
1208
1542
  properties: {
1209
1543
  url: {
1210
1544
  type: "string",
1211
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."
1212
1555
  }
1213
1556
  }
1214
1557
  }
@@ -1223,7 +1566,7 @@ var VSL_TOOLS = [
1223
1566
  },
1224
1567
  {
1225
1568
  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}.",
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.",
1227
1570
  inputSchema: {
1228
1571
  type: "object",
1229
1572
  properties: {
@@ -1238,6 +1581,10 @@ var VSL_TOOLS = [
1238
1581
  value: {
1239
1582
  type: "string",
1240
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."
1241
1588
  }
1242
1589
  },
1243
1590
  required: ["action", "target_id"]
@@ -1267,13 +1614,17 @@ var VSL_TOOLS = [
1267
1614
  },
1268
1615
  {
1269
1616
  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}.",
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.",
1271
1618
  inputSchema: {
1272
1619
  type: "object",
1273
1620
  properties: {
1274
1621
  element_id: {
1275
1622
  type: "string",
1276
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."
1277
1628
  }
1278
1629
  },
1279
1630
  required: ["element_id"]
@@ -1345,14 +1696,16 @@ var VSL_TOOLS = [
1345
1696
  }
1346
1697
  }
1347
1698
  ];
1348
- function registerTools(server, config, browser, session) {
1699
+ function registerTools(server, config, sessionManager) {
1349
1700
  server.setRequestHandler(ListToolsRequestSchema, async () => {
1350
1701
  return {
1351
1702
  tools: VSL_TOOLS
1352
1703
  };
1353
1704
  });
1354
1705
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
1355
- 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);
1356
1709
  try {
1357
1710
  let result;
1358
1711
  switch (name) {
@@ -1372,7 +1725,8 @@ function registerTools(server, config, browser, session) {
1372
1725
  result = await handleClearCache(session);
1373
1726
  break;
1374
1727
  case "vsl_get_visual":
1375
- return await handleGetVisual(args, browser);
1728
+ result = await handleGetVisual(args, browser, session);
1729
+ break;
1376
1730
  case "vsl_read_page":
1377
1731
  result = await handleReadPage(args, browser, session, config);
1378
1732
  break;
@@ -1441,7 +1795,7 @@ var VSL_RESOURCES = [
1441
1795
  mimeType: "application/json"
1442
1796
  }
1443
1797
  ];
1444
- function registerResources(server, _config, session) {
1798
+ function registerResources(server, _config, sessionManager) {
1445
1799
  server.setRequestHandler(ListResourcesRequestSchema, async () => {
1446
1800
  return {
1447
1801
  resources: VSL_RESOURCES
@@ -1449,6 +1803,9 @@ function registerResources(server, _config, session) {
1449
1803
  });
1450
1804
  server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
1451
1805
  const { uri } = request.params;
1806
+ const sessionId = request.params._meta?.sessionId ?? sessionManager.getDefaultSessionId();
1807
+ const { session } = sessionManager.getSession(sessionId);
1808
+ ensureSubscribed(sessionId, session);
1452
1809
  switch (uri) {
1453
1810
  case "vsl://current":
1454
1811
  try {
@@ -1517,14 +1874,19 @@ function registerResources(server, _config, session) {
1517
1874
  throw new Error(`Unknown resource: ${uri}`);
1518
1875
  }
1519
1876
  });
1520
- session.setOnSnapshotChange(() => {
1521
- server.sendResourceUpdated({ uri: "vsl://current" }).catch(() => {
1522
- });
1523
- if (session.getDiff()) {
1524
- 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(() => {
1525
1883
  });
1526
- }
1527
- });
1884
+ if (session.getDiff()) {
1885
+ server.sendResourceUpdated({ uri: "vsl://diff" }).catch(() => {
1886
+ });
1887
+ }
1888
+ });
1889
+ }
1528
1890
  }
1529
1891
 
1530
1892
  // src/browser/manager.ts
@@ -1619,6 +1981,7 @@ var BrowserManager = class {
1619
1981
  /**
1620
1982
  * Выполняет JavaScript в контексте страницы.
1621
1983
  */
1984
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1622
1985
  async evaluate(fn, ...args) {
1623
1986
  const page = await this.getPage();
1624
1987
  return page.evaluate(fn, ...args);
@@ -1708,7 +2071,8 @@ var BrowserManager = class {
1708
2071
  if (isAbsolute) {
1709
2072
  await download.saveAs(savePath);
1710
2073
  } else {
1711
- 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()));
1712
2076
  const resolvedSave = path2.resolve(resolvedBase, savePath);
1713
2077
  if (!resolvedSave.startsWith(resolvedBase + path2.sep) && resolvedSave !== resolvedBase) {
1714
2078
  throw new Error(`Path traversal detected: save_path '${savePath}' escapes downloads directory '${resolvedBase}'`);
@@ -1794,14 +2158,12 @@ var BrowserManager = class {
1794
2158
  };
1795
2159
 
1796
2160
  // src/session/serverSession.ts
1797
- import { VslSnapshotSession, diffVslDocuments } from "@thinkingos/vsl-sdk";
2161
+ import { diffVslDocuments, segmentTree, buildVslDocument } from "@thinkingos/vsl-sdk";
1798
2162
  var ServerSession = class {
1799
- sdkSession;
2163
+ currentDocument = null;
1800
2164
  previousDocument = null;
2165
+ version = 0;
1801
2166
  onSnapshotChange = null;
1802
- constructor() {
1803
- this.sdkSession = new VslSnapshotSession();
1804
- }
1805
2167
  /**
1806
2168
  * Регистрирует callback для уведомлений об изменении snapshot.
1807
2169
  * Вызывается при каждом вызове setSnapshot().
@@ -1810,58 +2172,63 @@ var ServerSession = class {
1810
2172
  this.onSnapshotChange = callback;
1811
2173
  }
1812
2174
  /**
1813
- * Устанавливает новый snapshot напрямую (VslDocument).
1814
- * Для обратной совместимости с кодом, который уже имеет готовый VslDocument.
1815
- * Предпочтительный способ: snapshotFromElements() для нового pipeline.
2175
+ * Устанавливает новый snapshot (VslDocument).
2176
+ * Сохраняет текущий документ как previousDocument для getDiff().
1816
2177
  */
1817
2178
  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;
2179
+ if (this.currentDocument) {
2180
+ this.previousDocument = this.currentDocument;
2181
+ }
2182
+ this.currentDocument = doc;
2183
+ this.version += 1;
1830
2184
  if (this.onSnapshotChange) {
1831
2185
  this.onSnapshotChange();
1832
2186
  }
1833
2187
  }
1834
2188
  /**
1835
2189
  * Делает snapshot из pre-extracted elements через SDK pipeline.
1836
- * Это ПРЕДПОЧТИТЕЛЬНЫЙ способ — использует полный pipeline SDK:
1837
- * segmentTree → buildVslDocument → cache → diff.
2190
+ * segmentTree → buildVslDocument → store as current document.
2191
+ * Возвращает VslDocument (первый вызов) или VslDiff (последующие).
1838
2192
  */
1839
2193
  snapshotFromElements(extractedElements, input) {
1840
- const result = this.sdkSession.snapshotFromElements(
1841
- extractedElements,
1842
- input
1843
- );
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;
1844
2206
  if (this.onSnapshotChange) {
1845
2207
  this.onSnapshotChange();
1846
2208
  }
1847
- return result;
2209
+ if (!this.previousDocument) {
2210
+ return doc;
2211
+ }
2212
+ return diffVslDocuments(this.previousDocument, doc, {
2213
+ diffVersion: this.version,
2214
+ baseVersion: this.version - 1
2215
+ });
1848
2216
  }
1849
2217
  /**
1850
2218
  * Возвращает текущий snapshot (последний полный документ).
1851
2219
  * @throws Error если snapshot не установлен
1852
2220
  */
1853
2221
  getSnapshot() {
1854
- const doc = this.sdkSession.getLastDocument();
1855
- if (!doc) {
2222
+ if (!this.currentDocument) {
1856
2223
  throw new Error("No snapshot available. Call vsl_get_snapshot first.");
1857
2224
  }
1858
- return doc;
2225
+ return this.currentDocument;
1859
2226
  }
1860
2227
  /**
1861
2228
  * Проверяет, есть ли текущий snapshot.
1862
2229
  */
1863
2230
  hasSnapshot() {
1864
- return this.sdkSession.getLastDocument() !== null;
2231
+ return this.currentDocument !== null;
1865
2232
  }
1866
2233
  /**
1867
2234
  * Вычисляет diff между текущим и предыдущим snapshot.
@@ -1869,27 +2236,152 @@ var ServerSession = class {
1869
2236
  * @returns VslDiff или null если нет предыдущего snapshot
1870
2237
  */
1871
2238
  getDiff() {
1872
- const currentDoc = this.sdkSession.getLastDocument();
1873
- if (!currentDoc || !this.previousDocument) {
2239
+ if (!this.currentDocument || !this.previousDocument) {
1874
2240
  return null;
1875
2241
  }
1876
- return diffVslDocuments(this.previousDocument, currentDoc, {
1877
- diffVersion: this.sdkSession.getVersion() + 1,
1878
- baseVersion: this.sdkSession.getVersion()
2242
+ return diffVslDocuments(this.previousDocument, this.currentDocument, {
2243
+ diffVersion: this.version,
2244
+ baseVersion: this.version - 1
1879
2245
  });
1880
2246
  }
1881
2247
  /**
1882
- * Сбрасывает сессию (кэш).
2248
+ * Сбрасывает сессию (состояние).
1883
2249
  */
1884
2250
  clear() {
1885
- this.sdkSession.clear();
2251
+ this.currentDocument = null;
2252
+ this.previousDocument = null;
2253
+ this.version = 0;
1886
2254
  }
1887
2255
  /**
1888
- * Возвращает базовую VslSnapshotSession из SDK.
1889
- * Для продвинутого использования (прямой доступ к SDK pipeline).
2256
+ * Возвращает текущую версию snapshot.
1890
2257
  */
1891
- getSession() {
1892
- return this.sdkSession;
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
+ }
1893
2385
  }
1894
2386
  };
1895
2387
 
@@ -1899,8 +2391,8 @@ var VSL_MCP_SERVER_VERSION = "0.1.0";
1899
2391
  // src/index.ts
1900
2392
  async function main() {
1901
2393
  const config = loadConfig();
1902
- const browser = new BrowserManager(config.browser);
1903
- const session = new ServerSession();
2394
+ const defaultSessionId = process.env.VSL_SESSION_ID || "default";
2395
+ const sessionManager = new SessionManager(config.browser, { defaultSessionId });
1904
2396
  const server = new Server(
1905
2397
  {
1906
2398
  name: "vsl-mcp-server",
@@ -1913,12 +2405,21 @@ async function main() {
1913
2405
  }
1914
2406
  }
1915
2407
  );
1916
- registerTools(server, config, browser, session);
1917
- registerResources(server, config, session);
2408
+ registerTools(server, config, sessionManager);
2409
+ registerResources(server, config, sessionManager);
1918
2410
  const transport = new StdioServerTransport();
1919
2411
  await server.connect(transport);
1920
2412
  console.error(`[VSL MCP Server] v${VSL_MCP_SERVER_VERSION} started (stdio transport)`);
1921
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);
1922
2423
  }
1923
2424
  main().catch((error) => {
1924
2425
  console.error("[VSL MCP Server] Fatal error:", error);