@thinkingos/vsl-mcp-server 1.4.6 → 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
@@ -12,6 +12,12 @@ var __export = (target, all) => {
12
12
  // src/utils/domStabilization.ts
13
13
  async function waitForDomStable(target, options = {}) {
14
14
  const opts = { ...DEFAULT_DOM_STABILIZATION_OPTIONS, ...options };
15
+ if (opts.waitForNetworkIdle && typeof target.waitForLoadState === "function") {
16
+ try {
17
+ await target.waitForLoadState("networkidle", { timeout: opts.networkIdleTimeout });
18
+ } catch {
19
+ }
20
+ }
15
21
  await target.evaluate(
16
22
  ({ stablePeriod, pollInterval, timeout }) => {
17
23
  return new Promise((resolve) => {
@@ -498,6 +504,11 @@ async function injectVslIdsIntoFrame(browser, frame, objects, semanticMap = /* @
498
504
  }
499
505
 
500
506
  // src/utils/idMapper.ts
507
+ function computeIdSignature(obj) {
508
+ const txt = obj.txt ? obj.txt.slice(0, 64) : "";
509
+ const act = obj.act ? obj.act.join(",") : "";
510
+ return `${obj.t ?? ""}|${obj.r ?? ""}|${txt}|${act}`;
511
+ }
501
512
  var TAG_PREFIXES = {
502
513
  button: "btn",
503
514
  input: "inp",
@@ -556,9 +567,9 @@ function extractTag(longId) {
556
567
  function toBase36(n) {
557
568
  return n.toString(36);
558
569
  }
559
- function buildIdMap(objects, previousReverseIdMap) {
570
+ function buildIdMap(objects, previousReverseIdMap, state) {
560
571
  const map = /* @__PURE__ */ new Map();
561
- const counters = /* @__PURE__ */ new Map();
572
+ const counters = state?.counters ?? /* @__PURE__ */ new Map();
562
573
  const assignedShortIds = /* @__PURE__ */ new Set();
563
574
  const elementsWithPrefix = [];
564
575
  function collect(obj, framePrefix) {
@@ -585,14 +596,22 @@ function buildIdMap(objects, previousReverseIdMap) {
585
596
  if (oldShortId && !assignedShortIds.has(oldShortId)) {
586
597
  const expectedPrefix = framePrefix ? `${framePrefix}:` : "";
587
598
  if (oldShortId.startsWith(expectedPrefix) || !framePrefix && !oldShortId.includes(":")) {
588
- map.set(oldShortId, obj.id);
589
- assignedShortIds.add(oldShortId);
599
+ if (state?.signatures) {
600
+ const oldSignature = state.signatures.get(obj.id);
601
+ const newSignature = computeIdSignature(obj);
602
+ if (oldSignature === newSignature) {
603
+ map.set(oldShortId, obj.id);
604
+ assignedShortIds.add(oldShortId);
605
+ }
606
+ } else {
607
+ map.set(oldShortId, obj.id);
608
+ assignedShortIds.add(oldShortId);
609
+ }
590
610
  }
591
611
  }
592
612
  }
593
613
  }
594
614
  for (const { obj, framePrefix } of elementsWithPrefix) {
595
- if (map.has(framePrefix ? `${framePrefix}:${obj.id}` : obj.id)) continue;
596
615
  const alreadyAssigned = Array.from(map.entries()).some(([_, longId]) => longId === obj.id);
597
616
  if (alreadyAssigned) continue;
598
617
  const tag = extractTag(obj.id);
@@ -606,17 +625,12 @@ function buildIdMap(objects, previousReverseIdMap) {
606
625
  counters.set(prefix, counter);
607
626
  assignedShortIds.add(shortId);
608
627
  map.set(shortId, obj.id);
628
+ if (state?.signatures) {
629
+ state.signatures.set(obj.id, computeIdSignature(obj));
630
+ }
609
631
  }
610
632
  return map;
611
633
  }
612
- function buildReverseIdMap(objects, previousReverseIdMap) {
613
- const forward = buildIdMap(objects, previousReverseIdMap);
614
- const reverse = /* @__PURE__ */ new Map();
615
- for (const [shortId, longId] of forward) {
616
- reverse.set(longId, shortId);
617
- }
618
- return reverse;
619
- }
620
634
  function replaceIdsInDocument(document2, longToShort) {
621
635
  if (!document2.objects) return document2;
622
636
  function replaceObj(obj) {
@@ -664,7 +678,10 @@ function replaceIdsInModifiedObject(obj, reverseIdMap) {
664
678
  if (obj.p !== void 0) result.p = obj.p;
665
679
  if (obj.s !== void 0) result.s = obj.s;
666
680
  if (obj.t !== void 0) result.t = obj.t;
681
+ if (obj.r !== void 0) result.r = obj.r;
682
+ if (obj.st !== void 0) result.st = obj.st;
667
683
  if (obj.txt !== void 0) result.txt = obj.txt;
684
+ if (obj.val !== void 0) result.val = obj.val;
668
685
  if (obj.act !== void 0) result.act = obj.act;
669
686
  return result;
670
687
  }
@@ -721,6 +738,10 @@ var CONTAINER_TYPES = /* @__PURE__ */ new Set([
721
738
  "iframe"
722
739
  // M2.1: iframe objects contain sub-VSL documents
723
740
  ]);
741
+ var CONTENT_TYPES = /* @__PURE__ */ new Set([
742
+ "text",
743
+ "heading"
744
+ ]);
724
745
  function filterObjectsByDetailLevel(objects, level, options) {
725
746
  if (level === "high") return objects;
726
747
  const shouldStripStyles = options?.stripStyles ?? true;
@@ -745,7 +766,7 @@ function filterObjectsByDetailLevel(objects, level, options) {
745
766
  return obj;
746
767
  }
747
768
  if (level === "medium") {
748
- if (INTERACTIVE_TYPES.has(type) || CONTAINER_TYPES.has(type)) {
769
+ if (INTERACTIVE_TYPES.has(type) || CONTAINER_TYPES.has(type) || CONTENT_TYPES.has(type)) {
749
770
  if (obj.ch && obj.ch.length > 0) {
750
771
  const filteredChildren = obj.ch.map(filterRecursive).filter((child) => child !== null);
751
772
  const result = { ...obj, ch: filteredChildren };
@@ -792,6 +813,20 @@ function filterDiffByDetailLevel(diff, nextDoc, level, options) {
792
813
  }
793
814
  };
794
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
+ }
795
830
 
796
831
  // src/utils/viewportFilter.ts
797
832
  function computeVisibleWindow(viewport, scroll) {
@@ -941,6 +976,35 @@ function extractDomTreeInBrowser() {
941
976
  }
942
977
  return raw.replace(/\s+/g, " ").trim();
943
978
  }
979
+ function readFieldValue(el) {
980
+ const tag = el.tagName.toLowerCase();
981
+ if (tag !== "input" && tag !== "textarea" && tag !== "select") return null;
982
+ const type = el.type?.toLowerCase() || "";
983
+ if (type === "password" || type === "checkbox" || type === "radio" || type === "file") return null;
984
+ return el.value || null;
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
+ }
944
1008
  function extractAttributes(el) {
945
1009
  const attributes = {};
946
1010
  for (const attr of Array.from(el.attributes)) {
@@ -1008,14 +1072,19 @@ function extractDomTreeInBrowser() {
1008
1072
  const children = collectVisibleChildren(child, path3);
1009
1073
  const vslId = `${tag}_${path3.join("_")}`;
1010
1074
  child.setAttribute("data-vsl-id", vslId);
1075
+ const native = readNativeState(child);
1011
1076
  result.push({
1012
1077
  tag,
1013
1078
  indexPath: path3,
1014
1079
  rect,
1015
1080
  text: ownText(child) || null,
1081
+ value: readFieldValue(child),
1016
1082
  attributes,
1017
1083
  css,
1018
1084
  children,
1085
+ // Нативные состояния формы из DOM-СВОЙСТВ (D5, DEC-047)
1086
+ checked: native.checked,
1087
+ disabled: native.disabled,
1019
1088
  // Semantic attributes for fallback selectors
1020
1089
  role: attributes["role"],
1021
1090
  ariaLabel: attributes["aria-label"],
@@ -1895,6 +1964,52 @@ async function performHumanClick(mouse, from, target, options = {}) {
1895
1964
 
1896
1965
  // src/tools/executeAction.ts
1897
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
1898
2013
  var VALID_ACTIONS = [
1899
2014
  "click",
1900
2015
  "type",
@@ -2291,7 +2406,7 @@ async function handleExecuteAction(args, browser, session, sessionId) {
2291
2406
  if (!args.value) {
2292
2407
  return {
2293
2408
  status: "error",
2294
- error: "value is required for type action"
2409
+ error: 'value is required for type/fill action (use action "clear" to empty a field)'
2295
2410
  };
2296
2411
  }
2297
2412
  if (humanization.enabled && !targetFrame) {
@@ -2388,25 +2503,45 @@ async function handleExecuteAction(args, browser, session, sessionId) {
2388
2503
  scrollResult.metadata = computeToolMetrics(scrollResult.data, startTime);
2389
2504
  return scrollResult;
2390
2505
  }
2391
- case "select":
2506
+ case "select": {
2392
2507
  if (!args.value) {
2393
2508
  return {
2394
2509
  status: "error",
2395
2510
  error: "value is required for select action"
2396
2511
  };
2397
2512
  }
2398
- if (targetFrame) {
2399
- await browser.evaluateInFrame(targetFrame, ({ sel, val }) => {
2400
- const el = document.querySelector(sel);
2401
- if (el) el.value = val;
2402
- }, sessionId, { sel: selector, val: args.value });
2403
- } else {
2404
- await browser.evaluate(({ sel, val }) => {
2405
- const el = document.querySelector(sel);
2406
- if (el) el.value = val;
2407
- }, sessionId, { sel: selector, val: args.value });
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;
2408
2542
  }
2409
2543
  break;
2544
+ }
2410
2545
  case "hover":
2411
2546
  if (humanization.enabled && !targetFrame) {
2412
2547
  const blockedHover = rateGate();
@@ -2634,25 +2769,7 @@ async function handleExecuteAction(args, browser, session, sessionId) {
2634
2769
  return result2;
2635
2770
  }
2636
2771
  case "clear": {
2637
- if (targetFrame) {
2638
- await browser.evaluateInFrame(targetFrame, (sel) => {
2639
- const el = document.querySelector(sel);
2640
- if (el) {
2641
- el.value = "";
2642
- el.dispatchEvent(new Event("input", { bubbles: true }));
2643
- el.dispatchEvent(new Event("change", { bubbles: true }));
2644
- }
2645
- }, sessionId, selector);
2646
- } else {
2647
- await browser.evaluate((sel) => {
2648
- const el = document.querySelector(sel);
2649
- if (el) {
2650
- el.value = "";
2651
- el.dispatchEvent(new Event("input", { bubbles: true }));
2652
- el.dispatchEvent(new Event("change", { bubbles: true }));
2653
- }
2654
- }, sessionId, selector);
2655
- }
2772
+ await target.locator(selector).fill("", { timeout: 1e3 });
2656
2773
  break;
2657
2774
  }
2658
2775
  case "drag": {
@@ -2940,7 +3057,7 @@ async function handleExecuteAction(args, browser, session, sessionId) {
2940
3057
  if (navigationOccurred || contextDestroyed) {
2941
3058
  try {
2942
3059
  await page.waitForLoadState("domcontentloaded", { timeout: 5e3 });
2943
- await waitForDomStabilization(page, { waitForNetworkIdle: true, timeout: 2e3 });
3060
+ await waitForDomStabilization(page, { waitForNetworkIdle: true, timeout: 5e3, stablePeriod: 300, networkIdleTimeout: 2e3 });
2944
3061
  } catch (waitError) {
2945
3062
  console.warn("[vsl_execute_action] Navigation detected but waitForLoadState failed:", waitError);
2946
3063
  }
@@ -3359,6 +3476,14 @@ function buildVslFromDom(html, options = {}) {
3359
3476
  const idGenerator = createIdGenerator();
3360
3477
  const LAZY_TEXT_THRESHOLD = 200;
3361
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
+ }
3362
3487
  function extractElement(element) {
3363
3488
  if (!element || element.type !== "tag") return null;
3364
3489
  const $el = $(element);
@@ -3374,9 +3499,11 @@ function buildVslFromDom(html, options = {}) {
3374
3499
  const ariaDisabled = $el.attr("aria-disabled");
3375
3500
  const type = determineElementType(tag, role, $el);
3376
3501
  let state;
3377
- 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";
3378
3505
  else if (ariaExpanded === "true") state = "expanded";
3379
- else if (ariaPressed === "true") state = "pressed";
3506
+ else if (ariaDisabled === "true" || $el.attr("disabled") !== void 0) state = "disabled";
3380
3507
  const text = ariaLabel || $el.clone().children().remove().end().text().trim();
3381
3508
  const children = [];
3382
3509
  $el.children().each((_, child) => {
@@ -3396,20 +3523,27 @@ function buildVslFromDom(html, options = {}) {
3396
3523
  if (text) {
3397
3524
  if (text.length > LAZY_TEXT_THRESHOLD) {
3398
3525
  obj.txt_preview = text.slice(0, LAZY_TEXT_PREVIEW_LENGTH) + "\u2026";
3399
- const refId = `tb_${String(textBlockCounter++).padStart(3, "0")}`;
3400
- obj.txt_ref = refId;
3401
- textBlocks.set(refId, text);
3526
+ obj.txt_ref = storeTextBlock(text);
3402
3527
  } else {
3403
3528
  obj.txt = text;
3404
3529
  }
3405
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
+ }
3406
3540
  const actions = determineActions(type, state, $el);
3407
3541
  if (actions) obj.act = actions;
3408
3542
  if (children.length > 0) obj.ch = children;
3409
3543
  const attributes = {};
3410
- for (const [key, value] of Object.entries($el.attr() || {})) {
3544
+ for (const [key, value2] of Object.entries($el.attr() || {})) {
3411
3545
  if (key.startsWith("data-") || key.startsWith("aria-")) {
3412
- attributes[key] = value;
3546
+ attributes[key] = value2;
3413
3547
  }
3414
3548
  }
3415
3549
  if (Object.keys(attributes).length > 0) {
@@ -3520,6 +3654,26 @@ function determineActions(type, state, $el) {
3520
3654
  return void 0;
3521
3655
  }
3522
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
+ }
3523
3677
 
3524
3678
  // src/tools/readPage.ts
3525
3679
  async function handleReadPage(args, browser, session, _config, sessionId) {
@@ -3549,18 +3703,26 @@ async function handleReadPage(args, browser, session, _config, sessionId) {
3549
3703
  error: "readable must be a boolean (true or false)"
3550
3704
  };
3551
3705
  }
3706
+ if (args.use_browser !== void 0 && typeof args.use_browser !== "boolean") {
3707
+ return {
3708
+ status: "error",
3709
+ error: "use_browser must be a boolean (true or false)"
3710
+ };
3711
+ }
3552
3712
  const detailLevel = args.detail_level || "medium";
3553
3713
  try {
3554
3714
  const readable = args.readable ?? false;
3555
- let detectedMode = "http";
3715
+ let detectedMode = args.use_browser === true ? "render" : "http";
3556
3716
  let httpResult = null;
3557
- try {
3558
- httpResult = await extractViaHttp(args.url, { readable });
3559
- if (httpResult.isSpa) {
3717
+ if (args.use_browser !== true) {
3718
+ try {
3719
+ httpResult = await extractViaHttp(args.url, { readable });
3720
+ if (httpResult.isSpa) {
3721
+ detectedMode = "render";
3722
+ }
3723
+ } catch {
3560
3724
  detectedMode = "render";
3561
3725
  }
3562
- } catch {
3563
- detectedMode = "render";
3564
3726
  }
3565
3727
  if (detectedMode === "render") {
3566
3728
  const isAvailable = await browser.isAvailable();
@@ -3612,7 +3774,8 @@ async function handleReadPage(args, browser, session, _config, sessionId) {
3612
3774
  url: args.url,
3613
3775
  mode: "render",
3614
3776
  content,
3615
- vslDocument: replaceIdsInDocument(rawSnapshot2, reverseIdMap2),
3777
+ // D3: полный набор объектов, но sty снят так же, как в snapshot (DEC-029)
3778
+ vslDocument: replaceIdsInDocument(stripStylesInDocument(rawSnapshot2, detailLevel), reverseIdMap2),
3616
3779
  snapshot: finalSnapshot2,
3617
3780
  diff: finalDiff2,
3618
3781
  hasDiff: hasDiff2,
@@ -3658,7 +3821,11 @@ async function handleReadPage(args, browser, session, _config, sessionId) {
3658
3821
  url: args.url,
3659
3822
  mode: "http",
3660
3823
  content: httpResult.textContent,
3661
- vslDocument: replaceIdsInDocument(rawSnapshot, reverseIdMap),
3824
+ // D3: полный набор объектов, но sty снят так же, как в snapshot (DEC-029)
3825
+ vslDocument: replaceIdsInDocument(
3826
+ stripStylesInDocument(rawSnapshot, detailLevel),
3827
+ reverseIdMap
3828
+ ),
3662
3829
  snapshot: finalSnapshot,
3663
3830
  diff: finalDiff,
3664
3831
  hasDiff,
@@ -4903,6 +5070,21 @@ async function computeMatched(browser, sessionId, successSelector, successUrlPat
4903
5070
  }
4904
5071
  return false;
4905
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
+ }
4906
5088
  async function waitForLogin(browser, sessionId, args, deadlineAt, pollIntervalMs) {
4907
5089
  for (; ; ) {
4908
5090
  const matched = await computeMatched(browser, sessionId, args.success_selector, args.success_url_pattern);
@@ -4950,7 +5132,12 @@ async function handleManualLogin(args, browser, _session, sessionManager, config
4950
5132
  const timeoutMs = resolveTimeoutMs(args.timeout_ms ?? config.browser.manualLogin?.timeoutMs);
4951
5133
  const pollIntervalMs = config.browser.manualLogin?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
4952
5134
  const deadlineAt = Date.now() + timeoutMs;
4953
- 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
+ });
4954
5141
  const loginUrl = sanitizeUrl(args.url);
4955
5142
  const data = {
4956
5143
  action: "open",
@@ -4992,6 +5179,13 @@ async function handleManualLogin(args, browser, _session, sessionManager, config
4992
5179
  }
4993
5180
  const href = await browser.evaluate(() => window.location.href, sessionId);
4994
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
+ );
4995
5189
  const data = {
4996
5190
  action: "status",
4997
5191
  browser_mode: mode,
@@ -4999,16 +5193,29 @@ async function handleManualLogin(args, browser, _session, sessionManager, config
4999
5193
  restarted: false,
5000
5194
  current_url: sanitizeUrl(typeof href === "string" ? href : ""),
5001
5195
  cookie_count: await browser.getCookieCount(),
5002
- matched: await computeMatched(browser, sessionId, args.success_selector, args.success_url_pattern),
5196
+ matched,
5003
5197
  waiting: state !== void 0 && state.deadlineAt > Date.now()
5004
5198
  };
5005
- 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;
5006
5207
  }
5007
5208
  if (action === "finish") {
5008
5209
  const href = await browser.evaluate(() => window.location.href, sessionId);
5009
5210
  const currentUrl = sanitizeUrl(typeof href === "string" ? href : "");
5010
5211
  const cookieCount = await browser.getCookieCount();
5011
- 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
+ );
5012
5219
  const restore = args.restore_headless ?? config.browser.manualLogin?.restoreHeadless ?? false;
5013
5220
  let restarted = false;
5014
5221
  let browserMode;
@@ -5031,16 +5238,25 @@ async function handleManualLogin(args, browser, _session, sessionManager, config
5031
5238
  cookie_count: cookieCount,
5032
5239
  matched,
5033
5240
  waiting: false,
5034
- instructions: "Manual login finished. Cookies and localStorage are stored in the VSL browser profile, so all subsequent VSL tools and sessions are already signed in."
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)."
5035
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
+ }
5036
5247
  const result = {
5037
5248
  status: "success",
5038
5249
  data,
5039
5250
  metadata: computeToolMetrics(data, startTime)
5040
5251
  };
5252
+ const warnings = [];
5253
+ if (signalWarning) warnings.push(signalWarning);
5041
5254
  if (restore) {
5042
- 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
+ );
5043
5258
  }
5259
+ if (warnings.length > 0) result.warning = warnings.join(" ");
5044
5260
  return result;
5045
5261
  }
5046
5262
  return { status: "error", error: `Unknown action: ${String(action)}` };
@@ -5064,7 +5280,7 @@ async function handleManualLogin(args, browser, _session, sessionManager, config
5064
5280
  var VSL_TOOLS = [
5065
5281
  {
5066
5282
  name: "vsl_get_snapshot",
5067
- description: "Get the current VSL snapshot of the page. Returns a VSL JSON with the semantic structure of elements. VSL (Visual Scene Language) is a JSON representation of the page where each element has: id (unique identifier, e.g. btn_123), type (button/input/link/text/image), text (text content), bbox ([x,y,width,height]), children (nested elements). Example: { viewport:{width:1920,height:1080}, objects:[{id:btn_1,type:button,text:Sign in,bbox:[100,200,80,30]},{id:inp_2,type:input,text:,bbox:[100,250,200,30]}] }. Usage: get the snapshot, find the desired element by id, then use vsl_execute_action to interact. Lazy text loading (DEC-026): texts longer than 200 characters are automatically replaced with txt_preview (first ~50 characters) + txt_ref (reference like tb_001). Full texts are stored in the text_blocks map. Use vsl_get_text_block to retrieve the full text. Parameters: detail_level (low/medium/high) for object filtering, ttl (ms) for caching.",
5283
+ description: "Get the current VSL snapshot of the page. Returns a VSL JSON with the semantic structure of elements. VSL (Visual Scene Language) is a JSON representation of the page where each element has: id (unique identifier, e.g. btn_123), type (button/input/link/text/image), text (text content), bbox ([x,y,width,height]), children (nested elements). Example: { viewport:{width:1920,height:1080}, objects:[{id:btn_1,type:button,text:Sign in,bbox:[100,200,80,30]},{id:inp_2,type:input,text:,bbox:[100,250,200,30]}] }. Usage: get the snapshot, find the desired element by id, then use vsl_execute_action to interact. Lazy text loading (DEC-026): texts longer than 200 characters are automatically replaced with txt_preview (first ~50 characters) + txt_ref (reference like tb_001). Full texts are stored in the text_blocks map. Use vsl_get_text_block to retrieve the full text. Parameters: detail_level (low/medium/high) for object filtering, ttl (ms) for caching. BROWSER tool: reads the live page in the VSL browser, so the signed-in profile cookies apply (unlike the default HTTP path of vsl_read_page).",
5068
5284
  inputSchema: {
5069
5285
  type: "object",
5070
5286
  properties: {
@@ -5090,13 +5306,13 @@ var VSL_TOOLS = [
5090
5306
  },
5091
5307
  {
5092
5308
  name: "vsl_execute_action",
5093
- description: 'Execute an action on a VSL element. Find the element by id in the snapshot (vsl_get_snapshot), then call this action. Supported actions: click (click on element), type (enter text, requires value), fill (alias for type, enter text, requires value), scroll (scroll, format: "up", "down", "left", "right" or "dir:amount", e.g. "down:300"), select (select option, requires value), hover, focus, blur, check, uncheck, press (press a keyboard key, requires value \u2014 key name, e.g. "Enter", "Tab", "Escape", "ArrowDown", "ArrowUp", "Space", "Backspace". Used for submitting forms via Enter, navigating via Tab, closing modals via Escape, etc.), upload (file upload, requires value \u2014 file path or comma-separated list of paths). Example: {action:click, target_id:btn_1} or {action:type, target_id:inp_2, value:hello@mail.com} or {action:fill, target_id:inp_2, value:hello@mail.com} or {action:press, target_id:inp_1, value:Enter} or {action:upload, target_id:file_input_0, value:/path/to/file.pdf}. Parameter return_state=true returns diff and snapshot after the action.',
5309
+ description: `Execute an action on a VSL element. Find the element by id in the snapshot (vsl_get_snapshot), then call this action. Supported actions: ${VALID_ACTIONS.join(", ")}. BROWSER tool: acts in the VSL browser with the signed-in profile cookies.`,
5094
5310
  inputSchema: {
5095
5311
  type: "object",
5096
5312
  properties: {
5097
5313
  action: {
5098
5314
  type: "string",
5099
- description: "Action name (click, type, fill, scroll, select, etc.)"
5315
+ description: `Action name (${VALID_ACTIONS.join(", ")}). Note: fill is an alias for type and requires a non-empty value; use action "clear" to empty a field.`
5100
5316
  },
5101
5317
  target_id: {
5102
5318
  type: "string",
@@ -5146,7 +5362,7 @@ var VSL_TOOLS = [
5146
5362
  },
5147
5363
  {
5148
5364
  name: "vsl_get_visual",
5149
- description: "Get a visual fragment (screenshot) of an element in base64 WebP format. Use for elements that are hard to classify by text alone (icons, charts, custom widgets). Returns {mediaType:image/webp, data:base64data}. Example: {element_id: img_5}. Supports iframe elements: use composite ID format iframe_N:element_Y (e.g. iframe_0:btn_1) to screenshot elements inside iframes. Parameter auto_refresh=true automatically refreshes the snapshot before searching for the element. IMPORTANT: works only with IDs from vsl_get_snapshot (browser DOM). Does NOT work with IDs from vsl_read_page (semantic IDs) \u2014 use vsl_get_snapshot to get compatible IDs.",
5365
+ description: "Get a visual fragment (screenshot) of an element in base64 WebP format. Use for elements that are hard to classify by text alone (icons, charts, custom widgets). Returns {mediaType:image/webp, data:base64data}. Example: {element_id: img_5}. Supports iframe elements: use composite ID format iframe_N:element_Y (e.g. iframe_0:btn_1) to screenshot elements inside iframes. Parameter auto_refresh=true automatically refreshes the snapshot before searching for the element. IMPORTANT: works only with IDs from vsl_get_snapshot (browser DOM). Does NOT work with IDs from vsl_read_page (semantic IDs) \u2014 use vsl_get_snapshot to get compatible IDs. BROWSER tool: screenshots the live page in the VSL browser with the signed-in profile cookies.",
5150
5366
  inputSchema: {
5151
5367
  type: "object",
5152
5368
  properties: {
@@ -5164,7 +5380,7 @@ var VSL_TOOLS = [
5164
5380
  },
5165
5381
  {
5166
5382
  name: "vsl_read_page",
5167
- description: 'Read web pages. Automatically determines the strategy: static pages are read via HTTP (fast), SPAs are rendered via browser. readable=true filters noise (navigation, footers, cookie banners) for clean content. On repeated calls, returns diff (changes) instead of full content. Parameter detail_level (low/medium/high) filters objects in the snapshot: low \u2014 interactive elements only (buttons, links, inputs), medium \u2014 interactive + containers (default), high \u2014 all objects. Metadata includes vsl_estimated_tokens \u2014 the number of tokens in the VSL snapshot for context estimation. Example: {url:"https://example.com", readable:true, detail_level:"medium"}. Returns snapshot and diff automatically.',
5383
+ description: 'Read web pages. TWO PATHS: (1) HTTP path (default, fast) \u2014 a plain Node fetch WITHOUT the browser: it sends NO cookies, so it reads as an ANONYMOUS visitor (the user sign-in is NOT used) and the visible browser tab does NOT change; (2) BROWSER path \u2014 renders the page in the VSL browser using the signed-in profile cookies, and the page really opens in the agent tab. By default the strategy is automatic: static pages go via HTTP, SPAs are rendered via browser, and a failed HTTP request (403/404/timeout) falls back to the browser. Set use_browser=true to FORCE the browser path \u2014 required for pages that need sign-in (after vsl_manual_login) or when the user should see the navigation. The response contains data.mode ("http" or "render") \u2014 check it to know which path was actually used. readable=true filters noise (navigation, footers, cookie banners) for clean content. On repeated calls, returns diff (changes) instead of full content. Parameter detail_level (low/medium/high) filters objects in the snapshot: low \u2014 interactive elements only (buttons, links, inputs), medium \u2014 interactive + containers (default), high \u2014 all objects. Metadata includes vsl_estimated_tokens \u2014 the number of tokens in the VSL snapshot for context estimation. Example: {url:"https://example.com", readable:true, detail_level:"medium"} or {url:"https://example.com/account", use_browser:true}. Returns snapshot and diff automatically.',
5168
5384
  inputSchema: {
5169
5385
  type: "object",
5170
5386
  properties: {
@@ -5175,6 +5391,15 @@ var VSL_TOOLS = [
5175
5391
  readable: {
5176
5392
  type: "boolean",
5177
5393
  description: "Readable mode: filter noise (nav, footer, cookie banners) for clean content"
5394
+ },
5395
+ detail_level: {
5396
+ type: "string",
5397
+ enum: ["low", "medium", "high"],
5398
+ description: "Snapshot detail level (default medium): low \u2014 interactive elements only, medium \u2014 interactive + containers, high \u2014 all objects"
5399
+ },
5400
+ use_browser: {
5401
+ type: "boolean",
5402
+ description: "Force the BROWSER path (default false). true \u2014 render the page in the VSL browser with the signed-in profile cookies (the page opens in the agent tab) and skip the HTTP request entirely. Use it for pages that require sign-in or when the user must see the navigation. Without it the HTTP path is used when possible: NO cookies (anonymous) and NO change in the visible browser tab."
5178
5403
  }
5179
5404
  },
5180
5405
  required: ["url"]
@@ -5227,7 +5452,7 @@ var VSL_TOOLS = [
5227
5452
  },
5228
5453
  {
5229
5454
  name: "vsl_manual_login",
5230
- description: 'Open a VISIBLE window of the SAME VSL browser profile (~/.vsl/browser-profile) so the user can sign in MANUALLY. Captcha, 2FA and anti-bot challenges are solved by the human \u2014 no automatic captcha bypass. Actions: open (open the login page in a visible window and return the link to the user; url is required for this action), status (check the sign-in signal without exposing secrets), finish (save the result and invalidate snapshot caches of all sessions). Cookies and localStorage stay in the shared profile, so all subsequent VSL tools and sessions are already signed in. Example: {action: "open", url: "https://example.com/login"}.',
5455
+ description: 'Open a VISIBLE window of the SAME VSL browser profile (~/.vsl/browser-profile) so the user can sign in MANUALLY. Captcha, 2FA and anti-bot challenges are solved by the human \u2014 no automatic captcha bypass. Actions: open (open the login page in a visible window and return the link to the user; url is required for this action), status (check the sign-in signal without exposing secrets), finish (save the result and invalidate snapshot caches of all sessions). Cookies and localStorage stay in the shared profile, so all BROWSER tools (vsl_navigate, vsl_get_snapshot, vsl_execute_action, vsl_get_visual, vsl_click_coordinates) in all sessions are signed in after the user logs in. IMPORTANT: vsl_read_page is NOT signed in by default \u2014 its HTTP path sends no cookies and reads as an anonymous visitor; call vsl_read_page with {use_browser:true} to read as the signed-in user. Example: {action: "open", url: "https://example.com/login"}.',
5231
5456
  inputSchema: {
5232
5457
  type: "object",
5233
5458
  properties: {
@@ -5464,6 +5689,17 @@ function registerResources(server, _config, sessionManager) {
5464
5689
 
5465
5690
  // src/session/serverSession.ts
5466
5691
  import { diffVslDocuments, segmentTree, buildVslDocument } from "@thinkingos/vsl-sdk";
5692
+ function collectLongIds(objects, into) {
5693
+ for (const obj of objects) {
5694
+ into.add(obj.id);
5695
+ if (obj.ch) {
5696
+ collectLongIds(obj.ch, into);
5697
+ }
5698
+ if (obj.iframe?.vsl?.objects) {
5699
+ collectLongIds(obj.iframe.vsl.objects, into);
5700
+ }
5701
+ }
5702
+ }
5467
5703
  var ServerSession = class {
5468
5704
  currentDocument = null;
5469
5705
  previousDocument = null;
@@ -5475,6 +5711,8 @@ var ServerSession = class {
5475
5711
  idMap = /* @__PURE__ */ new Map();
5476
5712
  /** Обратная карта longId → shortId для замены ID в выдаче LLM. */
5477
5713
  reverseIdMap = /* @__PURE__ */ new Map();
5714
+ /** Состояние маппера ID для сохранения идентичности коротких ID между снапшотами (E5/D5). */
5715
+ idMapperState = { signatures: /* @__PURE__ */ new Map(), counters: /* @__PURE__ */ new Map() };
5478
5716
  /**
5479
5717
  * Регистрирует callback для уведомлений об изменении snapshot.
5480
5718
  * Вызывается при каждом вызове setSnapshot().
@@ -5495,16 +5733,9 @@ var ServerSession = class {
5495
5733
  this.scrollContext = null;
5496
5734
  const currentObjects = doc.objects ?? [];
5497
5735
  const previousObjects = this.previousDocument?.objects ?? [];
5498
- const unionObjects = [...currentObjects, ...previousObjects];
5499
- if (currentObjects.length > 0) {
5500
- this.idMap = buildIdMap(currentObjects);
5501
- } else {
5502
- this.idMap = /* @__PURE__ */ new Map();
5503
- }
5504
- if (unionObjects.length > 0) {
5505
- this.reverseIdMap = buildReverseIdMap(unionObjects);
5506
- } else {
5507
- this.reverseIdMap = /* @__PURE__ */ new Map();
5736
+ this.buildMaps(currentObjects, previousObjects, this.idMapperState);
5737
+ for (const obj of currentObjects) {
5738
+ this.updateIdSignature(obj);
5508
5739
  }
5509
5740
  if (this.onSnapshotChange) {
5510
5741
  this.onSnapshotChange();
@@ -5529,20 +5760,9 @@ var ServerSession = class {
5529
5760
  this.currentDocument = doc;
5530
5761
  this.version += 1;
5531
5762
  this.scrollContext = input.scroll ? { ...input.scroll } : null;
5532
- const prevReverseIdMap = this.reverseIdMap;
5533
5763
  const currentObjects = doc.objects ?? [];
5534
5764
  const previousObjects = this.previousDocument?.objects ?? [];
5535
- const unionObjects = [...currentObjects, ...previousObjects];
5536
- if (currentObjects.length > 0) {
5537
- this.idMap = buildIdMap(currentObjects, prevReverseIdMap);
5538
- } else {
5539
- this.idMap = /* @__PURE__ */ new Map();
5540
- }
5541
- if (unionObjects.length > 0) {
5542
- this.reverseIdMap = buildReverseIdMap(unionObjects, prevReverseIdMap);
5543
- } else {
5544
- this.reverseIdMap = /* @__PURE__ */ new Map();
5545
- }
5765
+ this.buildMaps(currentObjects, previousObjects);
5546
5766
  if (this.onSnapshotChange) {
5547
5767
  this.onSnapshotChange();
5548
5768
  }
@@ -5601,6 +5821,7 @@ var ServerSession = class {
5601
5821
  this.scrollContext = null;
5602
5822
  this.idMap = /* @__PURE__ */ new Map();
5603
5823
  this.reverseIdMap = /* @__PURE__ */ new Map();
5824
+ this.idMapperState = { signatures: /* @__PURE__ */ new Map(), counters: /* @__PURE__ */ new Map() };
5604
5825
  }
5605
5826
  /**
5606
5827
  * Возвращает текущую версию snapshot.
@@ -5636,6 +5857,46 @@ var ServerSession = class {
5636
5857
  getReverseIdMap() {
5637
5858
  return this.reverseIdMap;
5638
5859
  }
5860
+ /**
5861
+ * Вычисляет и сохраняет подпись идентичности для объекта в состоянии маппера.
5862
+ * Используется для детекции семантических изменений элемента между снапшотами.
5863
+ */
5864
+ updateIdSignature(obj) {
5865
+ this.idMapperState.signatures.set(obj.id, computeIdSignature(obj));
5866
+ }
5867
+ /**
5868
+ * Строит ОБЕ карты маппинга ID за ОДНУ аллокацию коротких ID.
5869
+ *
5870
+ * Аллокация идёт по union (current + previous): текущие объекты первыми
5871
+ * получают младшие счётчики, удалённые объекты из previous — следом либо
5872
+ * восстанавливают прежние ID из предыдущей reverse-карты.
5873
+ * idMap (short→long) — только объекты текущего документа (резолвинг ID агента),
5874
+ * reverseIdMap (long→short) — весь union (короткие ID для removed/unchanged_refs).
5875
+ *
5876
+ * Один вызов buildIdMap вместо двух обязателен: два вызова с общим
5877
+ * state.counters давали расхождение карт (btn_0 в idMap против btn_1 в
5878
+ * reverseIdMap), так как первый вызов уже поднимал монотонные счётчики.
5879
+ */
5880
+ buildMaps(currentObjects, previousObjects, state) {
5881
+ if (currentObjects.length === 0 && previousObjects.length === 0) {
5882
+ this.idMap = /* @__PURE__ */ new Map();
5883
+ this.reverseIdMap = /* @__PURE__ */ new Map();
5884
+ return;
5885
+ }
5886
+ const forward = buildIdMap([...currentObjects, ...previousObjects], this.reverseIdMap, state);
5887
+ const currentLongIds = /* @__PURE__ */ new Set();
5888
+ collectLongIds(currentObjects, currentLongIds);
5889
+ const idMap = /* @__PURE__ */ new Map();
5890
+ const reverseIdMap = /* @__PURE__ */ new Map();
5891
+ for (const [shortId, longId] of forward) {
5892
+ reverseIdMap.set(longId, shortId);
5893
+ if (currentLongIds.has(longId)) {
5894
+ idMap.set(shortId, longId);
5895
+ }
5896
+ }
5897
+ this.idMap = idMap;
5898
+ this.reverseIdMap = reverseIdMap;
5899
+ }
5639
5900
  /**
5640
5901
  * Перестраивает карты маппинга ID (idMap и reverseIdMap) на основе текущего документа.
5641
5902
  * Используется после добавления iframe объектов в currentDoc.objects,
@@ -5649,16 +5910,9 @@ var ServerSession = class {
5649
5910
  if (!this.currentDocument) return;
5650
5911
  const currentObjects = this.currentDocument.objects ?? [];
5651
5912
  const previousObjects = this.previousDocument?.objects ?? [];
5652
- const unionObjects = [...currentObjects, ...previousObjects];
5653
- if (currentObjects.length > 0) {
5654
- this.idMap = buildIdMap(currentObjects);
5655
- } else {
5656
- this.idMap = /* @__PURE__ */ new Map();
5657
- }
5658
- if (unionObjects.length > 0) {
5659
- this.reverseIdMap = buildReverseIdMap(unionObjects);
5660
- } else {
5661
- this.reverseIdMap = /* @__PURE__ */ new Map();
5913
+ this.buildMaps(currentObjects, previousObjects, this.idMapperState);
5914
+ for (const obj of currentObjects) {
5915
+ this.updateIdSignature(obj);
5662
5916
  }
5663
5917
  }
5664
5918
  };
@@ -5816,7 +6070,7 @@ var SessionManager = class {
5816
6070
  };
5817
6071
 
5818
6072
  // src/version.ts
5819
- var VSL_MCP_SERVER_VERSION = "1.4.6";
6073
+ var VSL_MCP_SERVER_VERSION = "1.4.9";
5820
6074
 
5821
6075
  // src/index.ts
5822
6076
  async function main() {