@thinkingos/vsl-mcp-server 1.4.7 → 1.4.9

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
@@ -738,6 +738,10 @@ var CONTAINER_TYPES = /* @__PURE__ */ new Set([
738
738
  "iframe"
739
739
  // M2.1: iframe objects contain sub-VSL documents
740
740
  ]);
741
+ var CONTENT_TYPES = /* @__PURE__ */ new Set([
742
+ "text",
743
+ "heading"
744
+ ]);
741
745
  function filterObjectsByDetailLevel(objects, level, options) {
742
746
  if (level === "high") return objects;
743
747
  const shouldStripStyles = options?.stripStyles ?? true;
@@ -762,7 +766,7 @@ function filterObjectsByDetailLevel(objects, level, options) {
762
766
  return obj;
763
767
  }
764
768
  if (level === "medium") {
765
- if (INTERACTIVE_TYPES.has(type) || CONTAINER_TYPES.has(type)) {
769
+ if (INTERACTIVE_TYPES.has(type) || CONTAINER_TYPES.has(type) || CONTENT_TYPES.has(type)) {
766
770
  if (obj.ch && obj.ch.length > 0) {
767
771
  const filteredChildren = obj.ch.map(filterRecursive).filter((child) => child !== null);
768
772
  const result = { ...obj, ch: filteredChildren };
@@ -809,6 +813,20 @@ function filterDiffByDetailLevel(diff, nextDoc, level, options) {
809
813
  }
810
814
  };
811
815
  }
816
+ function stripStylesInDocument(document2, level) {
817
+ if (level === "high") return document2;
818
+ const objects = document2.objects;
819
+ if (!objects || !Array.isArray(objects)) return document2;
820
+ return { ...document2, objects: stripStylesRecursive(objects) };
821
+ }
822
+ function stripStylesRecursive(objects) {
823
+ return objects.map((obj) => {
824
+ const { sty: _sty, ...rest } = obj;
825
+ const result = rest;
826
+ if (obj.ch && obj.ch.length > 0) result.ch = stripStylesRecursive(obj.ch);
827
+ return result;
828
+ });
829
+ }
812
830
 
813
831
  // src/utils/viewportFilter.ts
814
832
  function computeVisibleWindow(viewport, scroll) {
@@ -965,6 +983,28 @@ function extractDomTreeInBrowser() {
965
983
  if (type === "password" || type === "checkbox" || type === "radio" || type === "file") return null;
966
984
  return el.value || null;
967
985
  }
986
+ const DISABLEABLE_TAGS = /* @__PURE__ */ new Set([
987
+ "input",
988
+ "button",
989
+ "select",
990
+ "textarea",
991
+ "option",
992
+ "optgroup",
993
+ "fieldset"
994
+ ]);
995
+ function readNativeState(el) {
996
+ const state = {};
997
+ const tag = el.tagName.toLowerCase();
998
+ if (tag === "input") {
999
+ const input = el;
1000
+ const type = input.type.toLowerCase();
1001
+ if (type === "checkbox" || type === "radio") state.checked = input.checked;
1002
+ }
1003
+ if (DISABLEABLE_TAGS.has(tag) && el.disabled) {
1004
+ state.disabled = true;
1005
+ }
1006
+ return state;
1007
+ }
968
1008
  function extractAttributes(el) {
969
1009
  const attributes = {};
970
1010
  for (const attr of Array.from(el.attributes)) {
@@ -1032,6 +1072,7 @@ function extractDomTreeInBrowser() {
1032
1072
  const children = collectVisibleChildren(child, path3);
1033
1073
  const vslId = `${tag}_${path3.join("_")}`;
1034
1074
  child.setAttribute("data-vsl-id", vslId);
1075
+ const native = readNativeState(child);
1035
1076
  result.push({
1036
1077
  tag,
1037
1078
  indexPath: path3,
@@ -1041,6 +1082,9 @@ function extractDomTreeInBrowser() {
1041
1082
  attributes,
1042
1083
  css,
1043
1084
  children,
1085
+ // Нативные состояния формы из DOM-СВОЙСТВ (D5, DEC-047)
1086
+ checked: native.checked,
1087
+ disabled: native.disabled,
1044
1088
  // Semantic attributes for fallback selectors
1045
1089
  role: attributes["role"],
1046
1090
  ariaLabel: attributes["aria-label"],
@@ -1920,6 +1964,52 @@ async function performHumanClick(mouse, from, target, options = {}) {
1920
1964
 
1921
1965
  // src/tools/executeAction.ts
1922
1966
  init_domStabilization();
1967
+
1968
+ // src/utils/selectError.ts
1969
+ var MISSING_OPTION_PATTERNS = [
1970
+ /did not find some options/i,
1971
+ /did not find option/i,
1972
+ /option[s]? .*not found/i
1973
+ ];
1974
+ var NOT_SELECT_PATTERNS = [
1975
+ /not a select/i,
1976
+ /element is not a <select>/i,
1977
+ /not a <select>/i
1978
+ ];
1979
+ function isMissingOptionError(message) {
1980
+ return MISSING_OPTION_PATTERNS.some((re) => re.test(message));
1981
+ }
1982
+ function isNotSelectError(message) {
1983
+ return NOT_SELECT_PATTERNS.some((re) => re.test(message));
1984
+ }
1985
+ var MAX_OPTIONS_IN_ERROR = 20;
1986
+ function formatMissingOptionError(requested, targetId, options) {
1987
+ const head = `Option "${requested}" not found in select ${targetId}.`;
1988
+ if (!options || options.length === 0) {
1989
+ return `${head} Could not read available options (empty select or element is not readable).`;
1990
+ }
1991
+ const shown = options.slice(0, MAX_OPTIONS_IN_ERROR);
1992
+ const list = shown.map((o) => o.label && o.label !== o.value ? `${o.value} ("${o.label}")` : o.value).join(", ");
1993
+ const rest = options.length > shown.length ? ` \u2026 and ${options.length - shown.length} more` : "";
1994
+ return `${head} Available options: ${list}${rest}. Use one of these values or the visible option text.`;
1995
+ }
1996
+ function formatNotSelectError(targetId) {
1997
+ return `Action "select" requires a <select> target, but ${targetId} is not a <select> element.`;
1998
+ }
1999
+ function normalizeSelectOptions(raw) {
2000
+ if (!Array.isArray(raw)) return null;
2001
+ const options = [];
2002
+ for (const item of raw) {
2003
+ if (!item || typeof item !== "object") continue;
2004
+ const record = item;
2005
+ if (typeof record.value !== "string") continue;
2006
+ const label = typeof record.label === "string" ? record.label : record.value;
2007
+ options.push({ value: record.value, label: label.trim() });
2008
+ }
2009
+ return options;
2010
+ }
2011
+
2012
+ // src/tools/executeAction.ts
1923
2013
  var VALID_ACTIONS = [
1924
2014
  "click",
1925
2015
  "type",
@@ -2413,15 +2503,45 @@ async function handleExecuteAction(args, browser, session, sessionId) {
2413
2503
  scrollResult.metadata = computeToolMetrics(scrollResult.data, startTime);
2414
2504
  return scrollResult;
2415
2505
  }
2416
- case "select":
2506
+ case "select": {
2417
2507
  if (!args.value) {
2418
2508
  return {
2419
2509
  status: "error",
2420
2510
  error: "value is required for select action"
2421
2511
  };
2422
2512
  }
2423
- await target.locator(selector).selectOption(args.value, { timeout: 1e3 });
2513
+ const requestedOption = args.value;
2514
+ try {
2515
+ await target.locator(selector).selectOption(requestedOption, { timeout: 1e3 });
2516
+ } catch (selectError) {
2517
+ const rawMessage = selectError instanceof Error ? selectError.message : String(selectError);
2518
+ if (isNotSelectError(rawMessage)) {
2519
+ return { status: "error", error: formatNotSelectError(args.target_id) };
2520
+ }
2521
+ if (isMissingOptionError(rawMessage)) {
2522
+ let options = null;
2523
+ try {
2524
+ const rawOptions = await target.evaluate((sel) => {
2525
+ const el = document.querySelector(sel);
2526
+ if (!el || el.tagName.toLowerCase() !== "select") return null;
2527
+ return Array.from(el.options).map((o) => ({
2528
+ value: o.value,
2529
+ label: o.textContent ?? ""
2530
+ }));
2531
+ }, selector);
2532
+ options = normalizeSelectOptions(rawOptions);
2533
+ } catch {
2534
+ options = null;
2535
+ }
2536
+ return {
2537
+ status: "error",
2538
+ error: formatMissingOptionError(requestedOption, args.target_id, options)
2539
+ };
2540
+ }
2541
+ throw selectError;
2542
+ }
2424
2543
  break;
2544
+ }
2425
2545
  case "hover":
2426
2546
  if (humanization.enabled && !targetFrame) {
2427
2547
  const blockedHover = rateGate();
@@ -3356,6 +3476,14 @@ function buildVslFromDom(html, options = {}) {
3356
3476
  const idGenerator = createIdGenerator();
3357
3477
  const LAZY_TEXT_THRESHOLD = 200;
3358
3478
  const LAZY_TEXT_PREVIEW_LENGTH = 50;
3479
+ function storeTextBlock(text) {
3480
+ for (const [refId2, existing] of textBlocks) {
3481
+ if (existing === text) return refId2;
3482
+ }
3483
+ const refId = `tb_${String(textBlockCounter++).padStart(3, "0")}`;
3484
+ textBlocks.set(refId, text);
3485
+ return refId;
3486
+ }
3359
3487
  function extractElement(element) {
3360
3488
  if (!element || element.type !== "tag") return null;
3361
3489
  const $el = $(element);
@@ -3371,9 +3499,11 @@ function buildVslFromDom(html, options = {}) {
3371
3499
  const ariaDisabled = $el.attr("aria-disabled");
3372
3500
  const type = determineElementType(tag, role, $el);
3373
3501
  let state;
3374
- if (ariaDisabled === "true") state = "disabled";
3502
+ const inputType = ($el.attr("type") || "").toLowerCase();
3503
+ const nativeChecked = tag === "input" && (inputType === "checkbox" || inputType === "radio") && $el.attr("checked") !== void 0;
3504
+ if (ariaPressed === "true" || nativeChecked) state = "checked";
3375
3505
  else if (ariaExpanded === "true") state = "expanded";
3376
- else if (ariaPressed === "true") state = "pressed";
3506
+ else if (ariaDisabled === "true" || $el.attr("disabled") !== void 0) state = "disabled";
3377
3507
  const text = ariaLabel || $el.clone().children().remove().end().text().trim();
3378
3508
  const children = [];
3379
3509
  $el.children().each((_, child) => {
@@ -3393,20 +3523,27 @@ function buildVslFromDom(html, options = {}) {
3393
3523
  if (text) {
3394
3524
  if (text.length > LAZY_TEXT_THRESHOLD) {
3395
3525
  obj.txt_preview = text.slice(0, LAZY_TEXT_PREVIEW_LENGTH) + "\u2026";
3396
- const refId = `tb_${String(textBlockCounter++).padStart(3, "0")}`;
3397
- obj.txt_ref = refId;
3398
- textBlocks.set(refId, text);
3526
+ obj.txt_ref = storeTextBlock(text);
3399
3527
  } else {
3400
3528
  obj.txt = text;
3401
3529
  }
3402
3530
  }
3531
+ const value = readHttpFieldValue(tag, $el);
3532
+ if (value !== null) {
3533
+ if (value.length > LAZY_TEXT_THRESHOLD) {
3534
+ obj.val_preview = value.slice(0, LAZY_TEXT_PREVIEW_LENGTH) + "\u2026";
3535
+ obj.val_ref = storeTextBlock(value);
3536
+ } else {
3537
+ obj.val = value;
3538
+ }
3539
+ }
3403
3540
  const actions = determineActions(type, state, $el);
3404
3541
  if (actions) obj.act = actions;
3405
3542
  if (children.length > 0) obj.ch = children;
3406
3543
  const attributes = {};
3407
- for (const [key, value] of Object.entries($el.attr() || {})) {
3544
+ for (const [key, value2] of Object.entries($el.attr() || {})) {
3408
3545
  if (key.startsWith("data-") || key.startsWith("aria-")) {
3409
- attributes[key] = value;
3546
+ attributes[key] = value2;
3410
3547
  }
3411
3548
  }
3412
3549
  if (Object.keys(attributes).length > 0) {
@@ -3517,6 +3654,26 @@ function determineActions(type, state, $el) {
3517
3654
  return void 0;
3518
3655
  }
3519
3656
  }
3657
+ function readHttpFieldValue(tag, $el) {
3658
+ if (tag === "textarea") {
3659
+ return $el.text().trim() || null;
3660
+ }
3661
+ if (tag === "select") {
3662
+ const selected = $el.find("option[selected]").first();
3663
+ const option = selected.length > 0 ? selected : $el.find("option").first();
3664
+ if (option.length === 0) return null;
3665
+ const value = option.attr("value");
3666
+ return (value !== void 0 ? value : option.text().trim()) || null;
3667
+ }
3668
+ if (tag === "input") {
3669
+ const type = ($el.attr("type") || "text").toLowerCase();
3670
+ if (type === "password" || type === "checkbox" || type === "radio" || type === "file") {
3671
+ return null;
3672
+ }
3673
+ return $el.attr("value") || null;
3674
+ }
3675
+ return null;
3676
+ }
3520
3677
 
3521
3678
  // src/tools/readPage.ts
3522
3679
  async function handleReadPage(args, browser, session, _config, sessionId) {
@@ -3617,7 +3774,8 @@ async function handleReadPage(args, browser, session, _config, sessionId) {
3617
3774
  url: args.url,
3618
3775
  mode: "render",
3619
3776
  content,
3620
- vslDocument: replaceIdsInDocument(rawSnapshot2, reverseIdMap2),
3777
+ // D3: полный набор объектов, но sty снят так же, как в snapshot (DEC-029)
3778
+ vslDocument: replaceIdsInDocument(stripStylesInDocument(rawSnapshot2, detailLevel), reverseIdMap2),
3621
3779
  snapshot: finalSnapshot2,
3622
3780
  diff: finalDiff2,
3623
3781
  hasDiff: hasDiff2,
@@ -3663,7 +3821,11 @@ async function handleReadPage(args, browser, session, _config, sessionId) {
3663
3821
  url: args.url,
3664
3822
  mode: "http",
3665
3823
  content: httpResult.textContent,
3666
- vslDocument: replaceIdsInDocument(rawSnapshot, reverseIdMap),
3824
+ // D3: полный набор объектов, но sty снят так же, как в snapshot (DEC-029)
3825
+ vslDocument: replaceIdsInDocument(
3826
+ stripStylesInDocument(rawSnapshot, detailLevel),
3827
+ reverseIdMap
3828
+ ),
3667
3829
  snapshot: finalSnapshot,
3668
3830
  diff: finalDiff,
3669
3831
  hasDiff,
@@ -4908,6 +5070,21 @@ async function computeMatched(browser, sessionId, successSelector, successUrlPat
4908
5070
  }
4909
5071
  return false;
4910
5072
  }
5073
+ function resolveSuccessCriteria(args, state) {
5074
+ return {
5075
+ selector: args.success_selector ?? state?.successSelector,
5076
+ urlPattern: args.success_url_pattern ?? state?.successUrlPattern
5077
+ };
5078
+ }
5079
+ function loginSignalWarning(criteria, matched) {
5080
+ if (!criteria.selector && !criteria.urlPattern) {
5081
+ return "No success signal is configured (success_selector / success_url_pattern), so matched:false is NOT proof that the user is signed out. Pass a signal to verify the sign-in.";
5082
+ }
5083
+ if (!matched) {
5084
+ return 'Sign-in signal did NOT match \u2014 the login is not confirmed. Keep the window open, finish the manual sign-in and call vsl_manual_login with {action:"status"} again.';
5085
+ }
5086
+ return void 0;
5087
+ }
4911
5088
  async function waitForLogin(browser, sessionId, args, deadlineAt, pollIntervalMs) {
4912
5089
  for (; ; ) {
4913
5090
  const matched = await computeMatched(browser, sessionId, args.success_selector, args.success_url_pattern);
@@ -4955,7 +5132,12 @@ async function handleManualLogin(args, browser, _session, sessionManager, config
4955
5132
  const timeoutMs = resolveTimeoutMs(args.timeout_ms ?? config.browser.manualLogin?.timeoutMs);
4956
5133
  const pollIntervalMs = config.browser.manualLogin?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
4957
5134
  const deadlineAt = Date.now() + timeoutMs;
4958
- loginState.set(sessionId, { loginUrl: args.url, deadlineAt });
5135
+ loginState.set(sessionId, {
5136
+ loginUrl: args.url,
5137
+ deadlineAt,
5138
+ successSelector: args.success_selector,
5139
+ successUrlPattern: args.success_url_pattern
5140
+ });
4959
5141
  const loginUrl = sanitizeUrl(args.url);
4960
5142
  const data = {
4961
5143
  action: "open",
@@ -4997,6 +5179,13 @@ async function handleManualLogin(args, browser, _session, sessionManager, config
4997
5179
  }
4998
5180
  const href = await browser.evaluate(() => window.location.href, sessionId);
4999
5181
  const state = loginState.get(sessionId);
5182
+ const criteria = resolveSuccessCriteria(args, state);
5183
+ const matched = await computeMatched(
5184
+ browser,
5185
+ sessionId,
5186
+ criteria.selector,
5187
+ criteria.urlPattern
5188
+ );
5000
5189
  const data = {
5001
5190
  action: "status",
5002
5191
  browser_mode: mode,
@@ -5004,16 +5193,29 @@ async function handleManualLogin(args, browser, _session, sessionManager, config
5004
5193
  restarted: false,
5005
5194
  current_url: sanitizeUrl(typeof href === "string" ? href : ""),
5006
5195
  cookie_count: await browser.getCookieCount(),
5007
- matched: await computeMatched(browser, sessionId, args.success_selector, args.success_url_pattern),
5196
+ matched,
5008
5197
  waiting: state !== void 0 && state.deadlineAt > Date.now()
5009
5198
  };
5010
- return { status: "success", data, metadata: computeToolMetrics(data, startTime) };
5199
+ const result = {
5200
+ status: "success",
5201
+ data,
5202
+ metadata: computeToolMetrics(data, startTime)
5203
+ };
5204
+ const signalWarning = loginSignalWarning(criteria, matched);
5205
+ if (signalWarning) result.warning = signalWarning;
5206
+ return result;
5011
5207
  }
5012
5208
  if (action === "finish") {
5013
5209
  const href = await browser.evaluate(() => window.location.href, sessionId);
5014
5210
  const currentUrl = sanitizeUrl(typeof href === "string" ? href : "");
5015
5211
  const cookieCount = await browser.getCookieCount();
5016
- const matched = await computeMatched(browser, sessionId, args.success_selector, args.success_url_pattern);
5212
+ const criteria = resolveSuccessCriteria(args, loginState.get(sessionId));
5213
+ const matched = await computeMatched(
5214
+ browser,
5215
+ sessionId,
5216
+ criteria.selector,
5217
+ criteria.urlPattern
5218
+ );
5017
5219
  const restore = args.restore_headless ?? config.browser.manualLogin?.restoreHeadless ?? false;
5018
5220
  let restarted = false;
5019
5221
  let browserMode;
@@ -5038,14 +5240,23 @@ async function handleManualLogin(args, browser, _session, sessionManager, config
5038
5240
  waiting: false,
5039
5241
  instructions: "Manual login finished. Cookies and localStorage are stored in the VSL browser profile, so all BROWSER tools (vsl_navigate, vsl_get_snapshot, vsl_execute_action, vsl_get_visual, vsl_click_coordinates) in all sessions are signed in. IMPORTANT: vsl_read_page is NOT signed in by default \u2014 its HTTP path sends no cookies and reads as an anonymous visitor; call vsl_read_page with {use_browser:true} to read as the signed-in user (the actual path is reported in data.mode)."
5040
5242
  };
5243
+ const signalWarning = loginSignalWarning(criteria, matched);
5244
+ if (signalWarning && !matched && (criteria.selector || criteria.urlPattern)) {
5245
+ data.instructions = "Sign-in was NOT confirmed (matched:false) \u2014 the profile may still be anonymous. " + (data.instructions ?? "");
5246
+ }
5041
5247
  const result = {
5042
5248
  status: "success",
5043
5249
  data,
5044
5250
  metadata: computeToolMetrics(data, startTime)
5045
5251
  };
5252
+ const warnings = [];
5253
+ if (signalWarning) warnings.push(signalWarning);
5046
5254
  if (restore) {
5047
- result.warning = "Headless restart closes the login tab: sessionStorage and session-only cookies may be lost.";
5255
+ warnings.push(
5256
+ "Headless restart closes the login tab: sessionStorage and session-only cookies may be lost."
5257
+ );
5048
5258
  }
5259
+ if (warnings.length > 0) result.warning = warnings.join(" ");
5049
5260
  return result;
5050
5261
  }
5051
5262
  return { status: "error", error: `Unknown action: ${String(action)}` };
@@ -5859,7 +6070,7 @@ var SessionManager = class {
5859
6070
  };
5860
6071
 
5861
6072
  // src/version.ts
5862
- var VSL_MCP_SERVER_VERSION = "1.4.7";
6073
+ var VSL_MCP_SERVER_VERSION = "1.4.9";
5863
6074
 
5864
6075
  // src/index.ts
5865
6076
  async function main() {