@qontinui/ui-bridge 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/ai/index.d.mts +893 -0
  2. package/dist/ai/index.d.ts +893 -0
  3. package/dist/ai/index.js +3897 -0
  4. package/dist/ai/index.js.map +1 -0
  5. package/dist/ai/index.mjs +3839 -0
  6. package/dist/ai/index.mjs.map +1 -0
  7. package/dist/control/index.d.mts +5 -4
  8. package/dist/control/index.d.ts +5 -4
  9. package/dist/core/index.d.mts +6 -4
  10. package/dist/core/index.d.ts +6 -4
  11. package/dist/core/index.js +581 -4
  12. package/dist/core/index.js.map +1 -1
  13. package/dist/core/index.mjs +581 -4
  14. package/dist/core/index.mjs.map +1 -1
  15. package/dist/debug/index.d.mts +3 -3
  16. package/dist/debug/index.d.ts +3 -3
  17. package/dist/index.d.mts +7 -5
  18. package/dist/index.d.ts +7 -5
  19. package/dist/index.js +4112 -12
  20. package/dist/index.js.map +1 -1
  21. package/dist/index.mjs +4056 -13
  22. package/dist/index.mjs.map +1 -1
  23. package/dist/{metrics-QCnK0EFw.d.ts → metrics-C9XRi_mL.d.ts} +2 -2
  24. package/dist/{metrics-BCG7z7Aq.d.mts → metrics-NC3csD0R.d.mts} +2 -2
  25. package/dist/react/index.d.mts +6 -5
  26. package/dist/react/index.d.ts +6 -5
  27. package/dist/react/index.js +587 -10
  28. package/dist/react/index.js.map +1 -1
  29. package/dist/react/index.mjs +587 -10
  30. package/dist/react/index.mjs.map +1 -1
  31. package/dist/{registry-CT6BVVKr.d.mts → registry-CIEDjbQ9.d.ts} +22 -1
  32. package/dist/{registry-D4mQ01B3.d.ts → registry-SsSDq46X.d.mts} +22 -1
  33. package/dist/render-log/index.d.mts +1 -1
  34. package/dist/render-log/index.d.ts +1 -1
  35. package/dist/types-BvCfFuEV.d.ts +534 -0
  36. package/dist/types-CFT3Dnx4.d.mts +534 -0
  37. package/dist/{types-BpvpStn3.d.mts → types-CPMbN_Iw.d.mts} +8 -0
  38. package/dist/{types-BpvpStn3.d.ts → types-CPMbN_Iw.d.ts} +8 -0
  39. package/dist/{types-DdJD9yw5.d.mts → types-Dr6tH-bm.d.mts} +1 -1
  40. package/dist/{types-BDkXy5si.d.ts → types-oCTrRxSw.d.ts} +1 -1
  41. package/dist/{websocket-client-DupH0X7B.d.ts → websocket-client-CX4QJesI.d.ts} +1 -1
  42. package/dist/{websocket-client-B2LC9CYc.d.mts → websocket-client-C_Na0OSp.d.mts} +1 -1
  43. package/package.json +6 -1
package/dist/index.mjs CHANGED
@@ -220,6 +220,583 @@ function elementMatchesIdentifier(element, identifier) {
220
220
  return identifier.uiId && element.getAttribute("data-ui-id") === identifier.uiId || identifier.testId && element.getAttribute("data-testid") === identifier.testId || identifier.awasId && element.getAttribute("data-awas-element") === identifier.awasId || identifier.htmlId && element.id === identifier.htmlId || false;
221
221
  }
222
222
 
223
+ // src/ai/fuzzy-matcher.ts
224
+ var DEFAULT_FUZZY_CONFIG = {
225
+ threshold: 0.7,
226
+ levenshteinWeight: 0.3,
227
+ jaroWinklerWeight: 0.4,
228
+ ngramWeight: 0.3,
229
+ ngramSize: 2,
230
+ caseSensitive: false,
231
+ ignoreWhitespace: true
232
+ };
233
+ function levenshteinDistance(s1, s2) {
234
+ const len1 = s1.length;
235
+ const len2 = s2.length;
236
+ const matrix = Array(len1 + 1).fill(null).map(() => Array(len2 + 1).fill(0));
237
+ for (let i = 0; i <= len1; i++) matrix[i][0] = i;
238
+ for (let j = 0; j <= len2; j++) matrix[0][j] = j;
239
+ for (let i = 1; i <= len1; i++) {
240
+ for (let j = 1; j <= len2; j++) {
241
+ const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;
242
+ matrix[i][j] = Math.min(
243
+ matrix[i - 1][j] + 1,
244
+ // deletion
245
+ matrix[i][j - 1] + 1,
246
+ // insertion
247
+ matrix[i - 1][j - 1] + cost
248
+ // substitution
249
+ );
250
+ }
251
+ }
252
+ return matrix[len1][len2];
253
+ }
254
+ function levenshteinSimilarity(s1, s2) {
255
+ if (s1.length === 0 && s2.length === 0) return 1;
256
+ if (s1.length === 0 || s2.length === 0) return 0;
257
+ const distance = levenshteinDistance(s1, s2);
258
+ const maxLength = Math.max(s1.length, s2.length);
259
+ return 1 - distance / maxLength;
260
+ }
261
+ function jaroSimilarity(s1, s2) {
262
+ if (s1.length === 0 && s2.length === 0) return 1;
263
+ if (s1.length === 0 || s2.length === 0) return 0;
264
+ const matchDistance = Math.floor(Math.max(s1.length, s2.length) / 2) - 1;
265
+ const s1Matches = new Array(s1.length).fill(false);
266
+ const s2Matches = new Array(s2.length).fill(false);
267
+ let matches = 0;
268
+ let transpositions = 0;
269
+ for (let i = 0; i < s1.length; i++) {
270
+ const start = Math.max(0, i - matchDistance);
271
+ const end = Math.min(i + matchDistance + 1, s2.length);
272
+ for (let j = start; j < end; j++) {
273
+ if (s2Matches[j] || s1[i] !== s2[j]) continue;
274
+ s1Matches[i] = true;
275
+ s2Matches[j] = true;
276
+ matches++;
277
+ break;
278
+ }
279
+ }
280
+ if (matches === 0) return 0;
281
+ let k = 0;
282
+ for (let i = 0; i < s1.length; i++) {
283
+ if (!s1Matches[i]) continue;
284
+ while (!s2Matches[k]) k++;
285
+ if (s1[i] !== s2[k]) transpositions++;
286
+ k++;
287
+ }
288
+ return (matches / s1.length + matches / s2.length + (matches - transpositions / 2) / matches) / 3;
289
+ }
290
+ function jaroWinklerSimilarity(s1, s2, prefixScale = 0.1) {
291
+ const jaroSim = jaroSimilarity(s1, s2);
292
+ let prefixLength = 0;
293
+ const maxPrefix = Math.min(4, Math.min(s1.length, s2.length));
294
+ for (let i = 0; i < maxPrefix; i++) {
295
+ if (s1[i] === s2[i]) {
296
+ prefixLength++;
297
+ } else {
298
+ break;
299
+ }
300
+ }
301
+ return jaroSim + prefixLength * prefixScale * (1 - jaroSim);
302
+ }
303
+ function generateNgrams(s, n) {
304
+ const ngrams = /* @__PURE__ */ new Set();
305
+ if (s.length < n) {
306
+ ngrams.add(s);
307
+ return ngrams;
308
+ }
309
+ for (let i = 0; i <= s.length - n; i++) {
310
+ ngrams.add(s.substring(i, i + n));
311
+ }
312
+ return ngrams;
313
+ }
314
+ function ngramSimilarity(s1, s2, n = 2) {
315
+ if (s1.length === 0 && s2.length === 0) return 1;
316
+ if (s1.length === 0 || s2.length === 0) return 0;
317
+ const ngrams1 = generateNgrams(s1, n);
318
+ const ngrams2 = generateNgrams(s2, n);
319
+ let intersection = 0;
320
+ for (const ngram of ngrams1) {
321
+ if (ngrams2.has(ngram)) {
322
+ intersection++;
323
+ }
324
+ }
325
+ const union = ngrams1.size + ngrams2.size - intersection;
326
+ return union === 0 ? 0 : intersection / union;
327
+ }
328
+ function normalizeString(s, config = {}) {
329
+ let normalized = s;
330
+ if (!config.caseSensitive) {
331
+ normalized = normalized.toLowerCase();
332
+ }
333
+ if (config.ignoreWhitespace !== false) {
334
+ normalized = normalized.replace(/\s+/g, " ").trim();
335
+ }
336
+ return normalized;
337
+ }
338
+ function fuzzyMatch(source, target, config = {}) {
339
+ const finalConfig = { ...DEFAULT_FUZZY_CONFIG, ...config };
340
+ const normalizedSource = normalizeString(source, finalConfig);
341
+ const normalizedTarget = normalizeString(target, finalConfig);
342
+ const levenshteinScore = levenshteinSimilarity(normalizedSource, normalizedTarget);
343
+ const jaroWinklerScore = jaroWinklerSimilarity(normalizedSource, normalizedTarget);
344
+ const ngramScore = ngramSimilarity(normalizedSource, normalizedTarget, finalConfig.ngramSize);
345
+ const similarity = levenshteinScore * finalConfig.levenshteinWeight + jaroWinklerScore * finalConfig.jaroWinklerWeight + ngramScore * finalConfig.ngramWeight;
346
+ return {
347
+ similarity,
348
+ isMatch: similarity >= finalConfig.threshold,
349
+ scores: {
350
+ levenshtein: levenshteinScore,
351
+ jaroWinkler: jaroWinklerScore,
352
+ ngram: ngramScore
353
+ },
354
+ normalizedSource,
355
+ normalizedTarget
356
+ };
357
+ }
358
+ function findBestMatch(source, candidates, config = {}) {
359
+ if (candidates.length === 0) {
360
+ return { match: null, index: -1, result: null };
361
+ }
362
+ let bestMatch = null;
363
+ let bestIndex = -1;
364
+ let bestResult = null;
365
+ for (let i = 0; i < candidates.length; i++) {
366
+ const result = fuzzyMatch(source, candidates[i], config);
367
+ if (result.isMatch && (!bestResult || result.similarity > bestResult.similarity)) {
368
+ bestMatch = candidates[i];
369
+ bestIndex = i;
370
+ bestResult = result;
371
+ }
372
+ }
373
+ return { match: bestMatch, index: bestIndex, result: bestResult };
374
+ }
375
+ function findAllMatches(source, candidates, config = {}) {
376
+ const matches = [];
377
+ for (let i = 0; i < candidates.length; i++) {
378
+ const result = fuzzyMatch(source, candidates[i], config);
379
+ if (result.isMatch) {
380
+ matches.push({ candidate: candidates[i], index: i, result });
381
+ }
382
+ }
383
+ matches.sort((a, b) => b.result.similarity - a.result.similarity);
384
+ return matches;
385
+ }
386
+ function fuzzyContains(source, target, config = {}) {
387
+ const finalConfig = { ...DEFAULT_FUZZY_CONFIG, ...config };
388
+ const normalizedSource = normalizeString(source, finalConfig);
389
+ const normalizedTarget = normalizeString(target, finalConfig);
390
+ if (normalizedSource.includes(normalizedTarget)) {
391
+ return true;
392
+ }
393
+ const sourceWords = normalizedSource.split(/\s+/);
394
+ const targetWords = normalizedTarget.split(/\s+/);
395
+ for (const targetWord of targetWords) {
396
+ const hasMatch = sourceWords.some((sourceWord) => {
397
+ const result = fuzzyMatch(sourceWord, targetWord, { ...finalConfig, threshold: 0.8 });
398
+ return result.isMatch;
399
+ });
400
+ if (!hasMatch) {
401
+ return false;
402
+ }
403
+ }
404
+ return true;
405
+ }
406
+ function wordSimilarity(s1, s2, config = {}) {
407
+ const finalConfig = { ...DEFAULT_FUZZY_CONFIG, ...config };
408
+ const words1 = normalizeString(s1, finalConfig).split(/\s+/);
409
+ const words2 = normalizeString(s2, finalConfig).split(/\s+/);
410
+ if (words1.length === 0 && words2.length === 0) return 1;
411
+ if (words1.length === 0 || words2.length === 0) return 0;
412
+ let totalSimilarity = 0;
413
+ let matchCount = 0;
414
+ for (const word1 of words1) {
415
+ let bestSim = 0;
416
+ for (const word2 of words2) {
417
+ const result = fuzzyMatch(word1, word2, finalConfig);
418
+ if (result.similarity > bestSim) {
419
+ bestSim = result.similarity;
420
+ }
421
+ }
422
+ totalSimilarity += bestSim;
423
+ if (bestSim >= finalConfig.threshold) {
424
+ matchCount++;
425
+ }
426
+ }
427
+ const avgSimilarity = totalSimilarity / words1.length;
428
+ const matchRatio = matchCount / Math.max(words1.length, words2.length);
429
+ return avgSimilarity * 0.5 + matchRatio * 0.5;
430
+ }
431
+ function tokenize(s) {
432
+ return s.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[_-]/g, " ").replace(/\s+/g, " ").trim().toLowerCase().split(" ").filter((token) => token.length > 0);
433
+ }
434
+ function tokenSimilarity(s1, s2) {
435
+ const tokens1 = tokenize(s1);
436
+ const tokens2 = tokenize(s2);
437
+ if (tokens1.length === 0 && tokens2.length === 0) return 1;
438
+ if (tokens1.length === 0 || tokens2.length === 0) return 0;
439
+ const set1 = new Set(tokens1);
440
+ const set2 = new Set(tokens2);
441
+ let intersection = 0;
442
+ for (const token of set1) {
443
+ if (set2.has(token)) {
444
+ intersection++;
445
+ }
446
+ }
447
+ const union = set1.size + set2.size - intersection;
448
+ return union === 0 ? 0 : intersection / union;
449
+ }
450
+
451
+ // src/ai/alias-generator.ts
452
+ var DEFAULT_ALIAS_CONFIG = {
453
+ includeText: true,
454
+ includeAriaLabel: true,
455
+ includePlaceholder: true,
456
+ includeTitle: true,
457
+ includeSynonyms: true,
458
+ maxAliases: 20,
459
+ minLength: 2,
460
+ maxLength: 50
461
+ };
462
+ var SYNONYMS = {
463
+ // Submit-related
464
+ submit: ["send", "go", "confirm", "ok", "apply", "save", "done", "finish"],
465
+ send: ["submit", "deliver", "post"],
466
+ save: ["submit", "store", "keep", "apply"],
467
+ cancel: ["close", "dismiss", "abort", "back", "exit", "quit", "nevermind"],
468
+ close: ["cancel", "dismiss", "exit", "x"],
469
+ delete: ["remove", "trash", "erase", "clear", "destroy"],
470
+ remove: ["delete", "clear", "discard"],
471
+ edit: ["modify", "change", "update", "alter"],
472
+ update: ["edit", "modify", "save", "refresh"],
473
+ add: ["create", "new", "plus", "insert"],
474
+ create: ["add", "new", "make"],
475
+ search: ["find", "lookup", "query", "filter"],
476
+ find: ["search", "locate", "lookup"],
477
+ login: ["signin", "sign in", "log in", "authenticate", "enter"],
478
+ logout: ["signout", "sign out", "log out", "exit"],
479
+ register: ["signup", "sign up", "join", "create account"],
480
+ next: ["continue", "forward", "proceed", "advance"],
481
+ previous: ["back", "backward", "return", "prior"],
482
+ back: ["previous", "return", "backward"],
483
+ start: ["begin", "launch", "initiate", "run", "execute"],
484
+ stop: ["end", "halt", "pause", "terminate"],
485
+ enable: ["activate", "turn on", "switch on"],
486
+ disable: ["deactivate", "turn off", "switch off"],
487
+ show: ["display", "reveal", "view", "open"],
488
+ hide: ["conceal", "collapse", "close"],
489
+ expand: ["open", "show", "unfold", "reveal"],
490
+ collapse: ["close", "hide", "fold", "minimize"],
491
+ yes: ["ok", "confirm", "agree", "accept"],
492
+ no: ["cancel", "decline", "reject", "deny"],
493
+ help: ["support", "assistance", "info", "information", "faq"],
494
+ settings: ["preferences", "options", "config", "configuration"],
495
+ profile: ["account", "user", "me"],
496
+ download: ["export", "save", "get"],
497
+ upload: ["import", "load", "attach"],
498
+ refresh: ["reload", "update", "sync"],
499
+ copy: ["duplicate", "clone"],
500
+ paste: ["insert"],
501
+ select: ["choose", "pick"],
502
+ toggle: ["switch", "flip"],
503
+ // Form fields
504
+ email: ["e-mail", "mail"],
505
+ password: ["pass", "pwd", "secret"],
506
+ username: ["user", "login", "account", "name"],
507
+ firstname: ["first name", "given name", "forename"],
508
+ lastname: ["last name", "surname", "family name"],
509
+ fullname: ["full name", "name", "complete name"],
510
+ phone: ["telephone", "tel", "mobile", "cell"],
511
+ address: ["location", "street"],
512
+ city: ["town"],
513
+ country: ["nation"],
514
+ zip: ["zipcode", "postal", "postal code", "postcode"],
515
+ // Navigation
516
+ home: ["main", "start", "dashboard"],
517
+ menu: ["navigation", "nav"],
518
+ sidebar: ["side bar", "side panel", "side menu"]
519
+ };
520
+ var ELEMENT_ACTION_WORDS = {
521
+ button: ["button", "btn", "click"],
522
+ input: ["input", "field", "textbox", "box"],
523
+ textarea: ["textarea", "text area", "text field", "multiline"],
524
+ select: ["select", "dropdown", "combo", "picker", "chooser"],
525
+ checkbox: ["checkbox", "check", "tick"],
526
+ radio: ["radio", "option", "choice"],
527
+ link: ["link", "anchor", "href"],
528
+ form: ["form"],
529
+ menu: ["menu"],
530
+ menuitem: ["menu item", "option"],
531
+ tab: ["tab"],
532
+ dialog: ["dialog", "modal", "popup"],
533
+ switch: ["switch", "toggle"],
534
+ slider: ["slider", "range"]
535
+ };
536
+ function normalizeAlias(text) {
537
+ return text.toLowerCase().replace(/[^\w\s]/g, " ").replace(/\s+/g, " ").trim();
538
+ }
539
+ function extractWords(text) {
540
+ const tokens = tokenize(text);
541
+ return tokens.filter((t) => t.length >= 2);
542
+ }
543
+ function generateTextAliases(text, config) {
544
+ if (!text || !config.includeText) return [];
545
+ const aliases = [];
546
+ const normalized = normalizeAlias(text);
547
+ if (normalized.length >= config.minLength && normalized.length <= config.maxLength) {
548
+ aliases.push(normalized);
549
+ }
550
+ const words = extractWords(text);
551
+ for (const word of words) {
552
+ if (word.length >= config.minLength) {
553
+ aliases.push(word);
554
+ }
555
+ }
556
+ if (words.length >= 2 && words.length <= 4) {
557
+ const twoWords = words.slice(0, 2).join(" ");
558
+ if (twoWords.length <= config.maxLength) {
559
+ aliases.push(twoWords);
560
+ }
561
+ if (words.length > 2) {
562
+ const lastTwo = words.slice(-2).join(" ");
563
+ if (lastTwo.length <= config.maxLength) {
564
+ aliases.push(lastTwo);
565
+ }
566
+ }
567
+ }
568
+ return aliases;
569
+ }
570
+ function generateSynonyms(aliases, config) {
571
+ if (!config.includeSynonyms) return [];
572
+ const synonyms = [];
573
+ for (const alias of aliases) {
574
+ const words = alias.toLowerCase().split(/\s+/);
575
+ for (const word of words) {
576
+ if (SYNONYMS[word]) {
577
+ for (const synonym of SYNONYMS[word]) {
578
+ const newAlias = alias.toLowerCase().replace(word, synonym);
579
+ if (newAlias !== alias.toLowerCase()) {
580
+ synonyms.push(newAlias);
581
+ }
582
+ if (synonym.length >= config.minLength) {
583
+ synonyms.push(synonym);
584
+ }
585
+ }
586
+ }
587
+ }
588
+ }
589
+ return synonyms;
590
+ }
591
+ function generateTypeAliases(elementType) {
592
+ const type = elementType.toLowerCase();
593
+ return ELEMENT_ACTION_WORDS[type] || [type];
594
+ }
595
+ function generateAliases(input, config = {}) {
596
+ const finalConfig = { ...DEFAULT_ALIAS_CONFIG, ...config };
597
+ const aliasSet = /* @__PURE__ */ new Set();
598
+ const addAlias = (alias) => {
599
+ const normalized = normalizeAlias(alias);
600
+ if (normalized.length >= finalConfig.minLength && normalized.length <= finalConfig.maxLength) {
601
+ aliasSet.add(normalized);
602
+ }
603
+ };
604
+ const addAliases = (aliases2) => {
605
+ for (const alias of aliases2) {
606
+ addAlias(alias);
607
+ }
608
+ };
609
+ if (finalConfig.includeText && input.textContent) {
610
+ addAliases(generateTextAliases(input.textContent, finalConfig));
611
+ }
612
+ if (finalConfig.includeAriaLabel && input.ariaLabel) {
613
+ addAliases(generateTextAliases(input.ariaLabel, finalConfig));
614
+ }
615
+ if (finalConfig.includeAriaLabel && input.ariaLabelledBy) {
616
+ addAliases(generateTextAliases(input.ariaLabelledBy, finalConfig));
617
+ }
618
+ if (finalConfig.includePlaceholder && input.placeholder) {
619
+ addAliases(generateTextAliases(input.placeholder, finalConfig));
620
+ }
621
+ if (finalConfig.includeTitle && input.title) {
622
+ addAliases(generateTextAliases(input.title, finalConfig));
623
+ }
624
+ if (input.labelText) {
625
+ addAliases(generateTextAliases(input.labelText, finalConfig));
626
+ }
627
+ if (input.id) {
628
+ addAliases(extractWords(input.id));
629
+ }
630
+ if (input.name) {
631
+ addAliases(extractWords(input.name));
632
+ }
633
+ if (input.value && (input.elementType === "button" || input.inputType === "submit" || input.inputType === "button")) {
634
+ addAliases(generateTextAliases(input.value, finalConfig));
635
+ }
636
+ if (input.elementType) {
637
+ addAliases(generateTypeAliases(input.elementType));
638
+ }
639
+ if (input.inputType) {
640
+ addAlias(input.inputType);
641
+ if (input.inputType === "email") {
642
+ addAliases(["email", "e-mail", "email address"]);
643
+ } else if (input.inputType === "password") {
644
+ addAliases(["password", "pass", "pwd"]);
645
+ } else if (input.inputType === "tel") {
646
+ addAliases(["phone", "telephone", "mobile"]);
647
+ } else if (input.inputType === "url") {
648
+ addAliases(["url", "website", "link", "address"]);
649
+ } else if (input.inputType === "search") {
650
+ addAliases(["search", "find", "query"]);
651
+ }
652
+ }
653
+ if (finalConfig.includeSynonyms) {
654
+ const currentAliases = Array.from(aliasSet);
655
+ addAliases(generateSynonyms(currentAliases, finalConfig));
656
+ }
657
+ let aliases = Array.from(aliasSet);
658
+ aliases.sort((a, b) => a.length - b.length);
659
+ if (aliases.length > finalConfig.maxAliases) {
660
+ aliases = aliases.slice(0, finalConfig.maxAliases);
661
+ }
662
+ return aliases;
663
+ }
664
+ function generateDescription(input) {
665
+ const parts = [];
666
+ let name = input.ariaLabel || input.labelText || input.textContent || input.placeholder || input.title || input.id || input.name;
667
+ if (name) {
668
+ name = name.trim();
669
+ if (name.length > 30) {
670
+ name = name.substring(0, 27) + "...";
671
+ }
672
+ parts.push(`"${name}"`);
673
+ }
674
+ const typeWords = ELEMENT_ACTION_WORDS[input.elementType || ""] || [input.elementType || "element"];
675
+ parts.push(typeWords[0]);
676
+ if (input.inputType && input.inputType !== "text") {
677
+ parts.push(`(${input.inputType})`);
678
+ }
679
+ return parts.join(" ");
680
+ }
681
+ function generatePurpose(input) {
682
+ const text = (input.textContent || input.ariaLabel || input.title || "").toLowerCase();
683
+ const type = input.elementType?.toLowerCase() || "";
684
+ const inputType = input.inputType?.toLowerCase() || "";
685
+ if (type === "button" || inputType === "submit") {
686
+ if (text.match(/submit|send|save|confirm|ok|done|finish|apply/)) {
687
+ return "Submits the form";
688
+ }
689
+ if (text.match(/cancel|close|dismiss|back|exit/)) {
690
+ return "Cancels or closes the current action";
691
+ }
692
+ if (text.match(/delete|remove|trash|clear/)) {
693
+ return "Deletes or removes an item";
694
+ }
695
+ if (text.match(/edit|modify|change|update/)) {
696
+ return "Edits or modifies an item";
697
+ }
698
+ if (text.match(/add|create|new|\+/)) {
699
+ return "Creates or adds a new item";
700
+ }
701
+ if (text.match(/search|find|lookup/)) {
702
+ return "Performs a search";
703
+ }
704
+ if (text.match(/login|sign.?in/)) {
705
+ return "Signs the user in";
706
+ }
707
+ if (text.match(/logout|sign.?out/)) {
708
+ return "Signs the user out";
709
+ }
710
+ if (text.match(/register|sign.?up|join/)) {
711
+ return "Creates a new account";
712
+ }
713
+ if (text.match(/next|continue|proceed/)) {
714
+ return "Proceeds to the next step";
715
+ }
716
+ if (text.match(/previous|back|return/)) {
717
+ return "Returns to the previous step";
718
+ }
719
+ }
720
+ if (type === "input" || type === "textarea") {
721
+ if (inputType === "email") return "Accepts email address input";
722
+ if (inputType === "password") return "Accepts password input";
723
+ if (inputType === "search") return "Accepts search query input";
724
+ if (inputType === "tel") return "Accepts phone number input";
725
+ if (inputType === "url") return "Accepts URL input";
726
+ if (inputType === "number") return "Accepts numeric input";
727
+ if (inputType === "date") return "Accepts date input";
728
+ if (inputType === "file") return "Accepts file upload";
729
+ }
730
+ if (type === "checkbox") {
731
+ return "Toggles an option on or off";
732
+ }
733
+ if (type === "radio") {
734
+ return "Selects one option from a group";
735
+ }
736
+ if (type === "select") {
737
+ return "Selects an option from a dropdown";
738
+ }
739
+ if (type === "link") {
740
+ return "Navigates to another page";
741
+ }
742
+ return void 0;
743
+ }
744
+ function generateSuggestedActions(input) {
745
+ const type = input.elementType?.toLowerCase() || "";
746
+ const inputType = input.inputType?.toLowerCase() || "";
747
+ const text = (input.textContent || input.ariaLabel || "").toLowerCase();
748
+ const actions = [];
749
+ switch (type) {
750
+ case "button":
751
+ actions.push(`click "${text || "this button"}"`);
752
+ break;
753
+ case "input":
754
+ if (inputType === "checkbox") {
755
+ actions.push("check to enable", "uncheck to disable");
756
+ } else if (inputType === "radio") {
757
+ actions.push("select this option");
758
+ } else {
759
+ actions.push(`type into "${text || "this field"}"`);
760
+ actions.push("clear the field");
761
+ }
762
+ break;
763
+ case "textarea":
764
+ actions.push(`type into "${text || "this text area"}"`);
765
+ actions.push("clear the content");
766
+ break;
767
+ case "select":
768
+ actions.push(`select an option from "${text || "this dropdown"}"`);
769
+ break;
770
+ case "checkbox":
771
+ actions.push("check to enable", "uncheck to disable");
772
+ break;
773
+ case "radio":
774
+ actions.push("select this option");
775
+ break;
776
+ case "link":
777
+ actions.push(`click to navigate to "${text || "the linked page"}"`);
778
+ break;
779
+ case "switch":
780
+ actions.push("toggle on", "toggle off");
781
+ break;
782
+ default:
783
+ actions.push("click");
784
+ }
785
+ return actions;
786
+ }
787
+ function getSynonyms(word) {
788
+ const normalized = word.toLowerCase().trim();
789
+ return SYNONYMS[normalized] || [];
790
+ }
791
+ function areSynonyms(word1, word2) {
792
+ const w1 = word1.toLowerCase().trim();
793
+ const w2 = word2.toLowerCase().trim();
794
+ if (w1 === w2) return true;
795
+ const synonyms1 = SYNONYMS[w1] || [];
796
+ const synonyms2 = SYNONYMS[w2] || [];
797
+ return synonyms1.includes(w2) || synonyms2.includes(w1);
798
+ }
799
+
223
800
  // src/core/registry.ts
224
801
  function getElementState(element) {
225
802
  const rect = element.getBoundingClientRect();
@@ -418,9 +995,13 @@ var UIBridgeRegistry = class {
418
995
  registerElement(id, element, options = {}) {
419
996
  const type = options.type ?? inferElementType(element);
420
997
  const actions = options.actions ?? inferActions(type);
421
- element.setAttribute("data-ui-id", id);
998
+ const existingUiId = element.getAttribute("data-ui-id");
999
+ const actualId = existingUiId || id;
1000
+ if (!existingUiId) {
1001
+ element.setAttribute("data-ui-id", actualId);
1002
+ }
422
1003
  const registered = {
423
- id,
1004
+ id: actualId,
424
1005
  element,
425
1006
  type,
426
1007
  label: options.label,
@@ -431,8 +1012,8 @@ var UIBridgeRegistry = class {
431
1012
  registeredAt: Date.now(),
432
1013
  mounted: true
433
1014
  };
434
- this.elements.set(id, registered);
435
- this.emit("element:registered", { id, type, label: options.label });
1015
+ this.elements.set(actualId, registered);
1016
+ this.emit("element:registered", { id: actualId, type, label: options.label });
436
1017
  return registered;
437
1018
  }
438
1019
  /**
@@ -472,6 +1053,209 @@ var UIBridgeRegistry = class {
472
1053
  }
473
1054
  return void 0;
474
1055
  }
1056
+ /**
1057
+ * Search for elements using AI search criteria
1058
+ */
1059
+ searchElements(criteria) {
1060
+ const results = [];
1061
+ const threshold = criteria.fuzzyThreshold ?? 0.7;
1062
+ for (const element of this.elements.values()) {
1063
+ if (!element.mounted) continue;
1064
+ const state = element.getState();
1065
+ if (!criteria.fuzzy && !state.visible) continue;
1066
+ const aliases = element.aliases ?? this.generateElementAliases(element);
1067
+ const textContent = state.textContent?.trim() || "";
1068
+ const label = element.label || "";
1069
+ let maxScore = 0;
1070
+ const matchReasons = [];
1071
+ const scores = {};
1072
+ if (criteria.text) {
1073
+ if (textContent.toLowerCase() === criteria.text.toLowerCase() || label.toLowerCase() === criteria.text.toLowerCase()) {
1074
+ maxScore = 1;
1075
+ matchReasons.push("exact text match");
1076
+ scores.text = 1;
1077
+ } else if (criteria.fuzzy !== false) {
1078
+ const textResult = fuzzyMatch(criteria.text, textContent, { threshold });
1079
+ const labelResult = fuzzyMatch(criteria.text, label, { threshold });
1080
+ const bestResult = textResult.similarity > labelResult.similarity ? textResult : labelResult;
1081
+ if (bestResult.isMatch) {
1082
+ scores.text = bestResult.similarity;
1083
+ if (bestResult.similarity > maxScore) {
1084
+ maxScore = bestResult.similarity;
1085
+ matchReasons.push(`text similarity: ${(bestResult.similarity * 100).toFixed(0)}%`);
1086
+ }
1087
+ }
1088
+ }
1089
+ }
1090
+ if (criteria.textContains) {
1091
+ if (textContent.toLowerCase().includes(criteria.textContains.toLowerCase()) || label.toLowerCase().includes(criteria.textContains.toLowerCase())) {
1092
+ const containsScore = 0.85;
1093
+ scores.text = Math.max(scores.text ?? 0, containsScore);
1094
+ if (containsScore > maxScore) {
1095
+ maxScore = containsScore;
1096
+ matchReasons.push("text contains");
1097
+ }
1098
+ }
1099
+ }
1100
+ if (criteria.accessibleName) {
1101
+ const ariaLabel = element.element.getAttribute("aria-label") || "";
1102
+ const accessibleName = ariaLabel || label || textContent;
1103
+ if (accessibleName.toLowerCase() === criteria.accessibleName.toLowerCase()) {
1104
+ scores.accessibility = 1;
1105
+ if (1 > maxScore) {
1106
+ maxScore = 1;
1107
+ matchReasons.push("accessible name match");
1108
+ }
1109
+ } else if (criteria.fuzzy !== false) {
1110
+ const result = fuzzyMatch(criteria.accessibleName, accessibleName, { threshold });
1111
+ if (result.isMatch) {
1112
+ scores.accessibility = result.similarity;
1113
+ if (result.similarity > maxScore) {
1114
+ maxScore = result.similarity;
1115
+ matchReasons.push(`accessible name similarity: ${(result.similarity * 100).toFixed(0)}%`);
1116
+ }
1117
+ }
1118
+ }
1119
+ }
1120
+ if (criteria.role) {
1121
+ const role = element.element.getAttribute("role") || this.inferRole(element.type);
1122
+ if (role?.toLowerCase() === criteria.role.toLowerCase()) {
1123
+ scores.role = 1;
1124
+ if (1 > maxScore) {
1125
+ maxScore = 1;
1126
+ matchReasons.push(`role: ${criteria.role}`);
1127
+ }
1128
+ }
1129
+ }
1130
+ if (criteria.type) {
1131
+ if (element.type === criteria.type) {
1132
+ const typeScore = 0.9;
1133
+ scores.role = Math.max(scores.role ?? 0, typeScore);
1134
+ if (typeScore > maxScore) {
1135
+ maxScore = typeScore;
1136
+ matchReasons.push(`type: ${criteria.type}`);
1137
+ }
1138
+ }
1139
+ }
1140
+ for (const alias of aliases) {
1141
+ const searchText = criteria.text || criteria.textContains || criteria.accessibleName;
1142
+ if (searchText) {
1143
+ if (alias.toLowerCase() === searchText.toLowerCase()) {
1144
+ scores.fuzzy = 1;
1145
+ if (1 > maxScore) {
1146
+ maxScore = 1;
1147
+ matchReasons.push(`alias: "${alias}"`);
1148
+ }
1149
+ } else if (criteria.fuzzy !== false) {
1150
+ const result = fuzzyMatch(searchText, alias, { threshold });
1151
+ if (result.isMatch && result.similarity > (scores.fuzzy ?? 0)) {
1152
+ scores.fuzzy = result.similarity;
1153
+ if (result.similarity > maxScore) {
1154
+ maxScore = result.similarity;
1155
+ matchReasons.push(`fuzzy alias: "${alias}"`);
1156
+ }
1157
+ }
1158
+ }
1159
+ }
1160
+ }
1161
+ if (maxScore >= threshold) {
1162
+ const aiElement = {
1163
+ id: element.id,
1164
+ type: element.type,
1165
+ label: element.label,
1166
+ tagName: element.element.tagName.toLowerCase(),
1167
+ role: element.element.getAttribute("role") || void 0,
1168
+ accessibleName: element.element.getAttribute("aria-label") || element.label,
1169
+ actions: element.actions,
1170
+ state,
1171
+ registered: true,
1172
+ description: element.description || generateDescription({
1173
+ textContent,
1174
+ ariaLabel: element.element.getAttribute("aria-label"),
1175
+ elementType: element.type,
1176
+ id: element.id,
1177
+ labelText: element.label
1178
+ }),
1179
+ aliases,
1180
+ purpose: element.purpose,
1181
+ suggestedActions: [],
1182
+ semanticType: element.semanticType
1183
+ };
1184
+ results.push({
1185
+ element: aiElement,
1186
+ confidence: maxScore,
1187
+ matchReasons,
1188
+ scores
1189
+ });
1190
+ }
1191
+ }
1192
+ results.sort((a, b) => b.confidence - a.confidence);
1193
+ return results;
1194
+ }
1195
+ /**
1196
+ * Find element by visible text
1197
+ */
1198
+ findByText(text, fuzzy = true) {
1199
+ const results = this.searchElements({ text, fuzzy, fuzzyThreshold: fuzzy ? 0.7 : 1 });
1200
+ if (results.length > 0) {
1201
+ return this.elements.get(results[0].element.id);
1202
+ }
1203
+ return void 0;
1204
+ }
1205
+ /**
1206
+ * Find element by accessible name
1207
+ */
1208
+ findByAccessibleName(name) {
1209
+ const results = this.searchElements({ accessibleName: name, fuzzy: true });
1210
+ if (results.length > 0) {
1211
+ return this.elements.get(results[0].element.id);
1212
+ }
1213
+ return void 0;
1214
+ }
1215
+ /**
1216
+ * Generate aliases for an element
1217
+ */
1218
+ generateElementAliases(element) {
1219
+ const state = element.getState();
1220
+ return generateAliases({
1221
+ textContent: state.textContent,
1222
+ ariaLabel: element.element.getAttribute("aria-label"),
1223
+ placeholder: element.element.getAttribute("placeholder"),
1224
+ title: element.element.getAttribute("title"),
1225
+ elementType: element.type,
1226
+ tagName: element.element.tagName.toLowerCase(),
1227
+ id: element.id,
1228
+ labelText: element.label
1229
+ });
1230
+ }
1231
+ /**
1232
+ * Infer ARIA role from element type
1233
+ */
1234
+ inferRole(type) {
1235
+ const roleMap = {
1236
+ button: "button",
1237
+ input: "textbox",
1238
+ select: "combobox",
1239
+ checkbox: "checkbox",
1240
+ radio: "radio",
1241
+ link: "link",
1242
+ form: void 0,
1243
+ textarea: "textbox",
1244
+ menu: "menu",
1245
+ menuitem: "menuitem",
1246
+ tab: "tab",
1247
+ dialog: "dialog",
1248
+ custom: void 0,
1249
+ switch: "switch",
1250
+ slider: "slider",
1251
+ combobox: "combobox",
1252
+ listbox: "listbox",
1253
+ option: "option",
1254
+ textbox: "textbox",
1255
+ generic: void 0
1256
+ };
1257
+ return roleMap[type];
1258
+ }
475
1259
  /**
476
1260
  * Register a component
477
1261
  */
@@ -3493,7 +4277,7 @@ function useUIBridge() {
3493
4277
  },
3494
4278
  [context]
3495
4279
  );
3496
- const getElementState5 = useCallback(
4280
+ const getElementState6 = useCallback(
3497
4281
  (id) => {
3498
4282
  const element = context?.registry.getElement(id);
3499
4283
  return element?.getState();
@@ -3542,7 +4326,7 @@ function useUIBridge() {
3542
4326
  runWorkflow,
3543
4327
  getElement,
3544
4328
  getComponent,
3545
- getElementState: getElementState5,
4329
+ getElementState: getElementState6,
3546
4330
  registerWorkflow,
3547
4331
  unregisterWorkflow,
3548
4332
  captureRenderLog,
@@ -4184,24 +4968,24 @@ function useAutoRegister(options = {}) {
4184
4968
  const type = inferElementType2(element);
4185
4969
  const actions = inferActions2(type);
4186
4970
  const label = getAccessibleLabel(element);
4187
- bridge.registry.registerElement(uniqueId, element, {
4971
+ const registered = bridge.registry.registerElement(uniqueId, element, {
4188
4972
  type,
4189
4973
  actions,
4190
4974
  label
4191
4975
  });
4192
- registeredElementsRef.current.set(element, uniqueId);
4193
- onRegister?.(uniqueId, element);
4976
+ registeredElementsRef.current.set(element, registered.id);
4977
+ onRegister?.(registered.id, element);
4194
4978
  } else {
4195
4979
  const type = inferElementType2(element);
4196
4980
  const actions = inferActions2(type);
4197
4981
  const label = getAccessibleLabel(element);
4198
- bridge.registry.registerElement(id, element, {
4982
+ const registered = bridge.registry.registerElement(id, element, {
4199
4983
  type,
4200
4984
  actions,
4201
4985
  label
4202
4986
  });
4203
- registeredElementsRef.current.set(element, id);
4204
- onRegister?.(id, element);
4987
+ registeredElementsRef.current.set(element, registered.id);
4988
+ onRegister?.(registered.id, element);
4205
4989
  }
4206
4990
  },
4207
4991
  [bridge, idStrategy, customGenerateId, onRegister]
@@ -4660,6 +5444,3265 @@ function Inspector({ getRegisteredElement, initialActive }) {
4660
5444
  ] });
4661
5445
  }
4662
5446
 
4663
- export { AutoRegisterProvider, DOMChangeObserver, DefaultActionExecutor, DefaultWorkflowEngine, ID_ATTRIBUTES, InMemoryRenderLogStorage, InfoPanel, Inspector, InspectorOverlay, MetricsCollector, RenderLogManager, UIBridgeProvider, UIBridgeRegistry, UIBridgeWSClient, captureDOMSnapshot, captureInteractiveElements, createActionExecutor, createElementIdentifier, createMetricsCollector, createRenderLogManager, createWSClient, createWorkflowEngine, elementMatchesIdentifier, findAllElementsByIdentifier, findElementByIdentifier, formatDuration, formatPercentage, generateCSSSelector, generateXPath, getBestIdentifier, getGlobalRegistry, resetGlobalRegistry, setGlobalRegistry, useActiveStates, useAutoRegister, useAvailableTransitions, useCanNavigateTo, useInspector, useNavigationPath, useStateSnapshot, useTransitions, useUIBridge, useUIBridgeContext, useUIBridgeOptional, useUIBridgeRequired, useUIComponent, useUIComponentAction, useUIElement, useUIElementRef, useUINavigation, useUIState, useUIStateGroup, useUITransition };
5447
+ // src/ai/search-engine.ts
5448
+ var DEFAULT_SEARCH_CONFIG = {
5449
+ fuzzyThreshold: 0.7,
5450
+ textWeight: 0.35,
5451
+ accessibilityWeight: 0.25,
5452
+ roleWeight: 0.15,
5453
+ spatialWeight: 0.1,
5454
+ aliasWeight: 0.15,
5455
+ maxResults: 20,
5456
+ includeHidden: false
5457
+ };
5458
+ var SearchEngine = class {
5459
+ // Cache valid for 100ms
5460
+ constructor(config = {}) {
5461
+ this.cachedElements = [];
5462
+ this.cacheTimestamp = 0;
5463
+ this.cacheValidityMs = 100;
5464
+ this.config = { ...DEFAULT_SEARCH_CONFIG, ...config };
5465
+ }
5466
+ /**
5467
+ * Update cached elements from various sources
5468
+ */
5469
+ updateElements(elements, getState) {
5470
+ this.cachedElements = elements.map((el) => this.toSearchable(el, getState));
5471
+ this.cacheTimestamp = Date.now();
5472
+ }
5473
+ /**
5474
+ * Convert an element to searchable format
5475
+ */
5476
+ toSearchable(element, getState) {
5477
+ let state;
5478
+ let textContent;
5479
+ let tagName;
5480
+ let role;
5481
+ let ariaLabel;
5482
+ let placeholder;
5483
+ let title;
5484
+ let labelText;
5485
+ let value;
5486
+ if ("getState" in element && typeof element.getState === "function") {
5487
+ state = getState ? getState(element) : element.getState();
5488
+ textContent = state.textContent || void 0;
5489
+ tagName = element.element.tagName.toLowerCase();
5490
+ role = element.element.getAttribute("role") || void 0;
5491
+ ariaLabel = element.element.getAttribute("aria-label") || void 0;
5492
+ placeholder = element.element.getAttribute("placeholder") || void 0;
5493
+ title = element.element.getAttribute("title") || void 0;
5494
+ if (element.element.id) {
5495
+ const labelEl = document.querySelector(`label[for="${element.element.id}"]`);
5496
+ labelText = labelEl?.textContent?.trim() || void 0;
5497
+ }
5498
+ if (element.element instanceof HTMLInputElement || element.element instanceof HTMLTextAreaElement || element.element instanceof HTMLSelectElement) {
5499
+ value = element.element.value || void 0;
5500
+ }
5501
+ } else {
5502
+ const discovered = element;
5503
+ state = discovered.state;
5504
+ textContent = state.textContent || void 0;
5505
+ tagName = discovered.tagName;
5506
+ role = discovered.role || void 0;
5507
+ ariaLabel = discovered.accessibleName || void 0;
5508
+ }
5509
+ const aliases = generateAliases({
5510
+ textContent,
5511
+ ariaLabel,
5512
+ placeholder,
5513
+ title,
5514
+ elementType: element.type,
5515
+ id: element.id,
5516
+ labelText,
5517
+ value
5518
+ });
5519
+ const description = generateDescription({
5520
+ textContent,
5521
+ ariaLabel,
5522
+ placeholder,
5523
+ title,
5524
+ elementType: element.type,
5525
+ id: element.id,
5526
+ labelText
5527
+ });
5528
+ return {
5529
+ id: element.id,
5530
+ element,
5531
+ state,
5532
+ textContent,
5533
+ ariaLabel,
5534
+ placeholder,
5535
+ title,
5536
+ role,
5537
+ tagName,
5538
+ type: element.type,
5539
+ aliases,
5540
+ description,
5541
+ rect: state.rect,
5542
+ labelText,
5543
+ value
5544
+ };
5545
+ }
5546
+ /**
5547
+ * Search for elements matching the criteria
5548
+ */
5549
+ search(criteria, elements) {
5550
+ const startTime = performance.now();
5551
+ if (elements) {
5552
+ this.updateElements(elements);
5553
+ }
5554
+ let searchableElements = this.cachedElements;
5555
+ if (!this.config.includeHidden && !criteria.fuzzy) {
5556
+ searchableElements = searchableElements.filter((el) => el.state.visible);
5557
+ }
5558
+ const results = [];
5559
+ for (const searchable of searchableElements) {
5560
+ const result = this.scoreElement(searchable, criteria);
5561
+ if (result.confidence >= (criteria.fuzzyThreshold ?? this.config.fuzzyThreshold)) {
5562
+ results.push(result);
5563
+ }
5564
+ }
5565
+ results.sort((a, b) => b.confidence - a.confidence);
5566
+ const limitedResults = results.slice(0, this.config.maxResults);
5567
+ return {
5568
+ results: limitedResults,
5569
+ bestMatch: limitedResults.length > 0 ? limitedResults[0] : null,
5570
+ scannedCount: searchableElements.length,
5571
+ durationMs: performance.now() - startTime,
5572
+ criteria,
5573
+ timestamp: Date.now()
5574
+ };
5575
+ }
5576
+ /**
5577
+ * Find the best matching element
5578
+ */
5579
+ findBest(criteria, elements) {
5580
+ const response = this.search(criteria, elements);
5581
+ return response.bestMatch;
5582
+ }
5583
+ /**
5584
+ * Find elements by text content
5585
+ */
5586
+ findByText(text, fuzzy = true, elements) {
5587
+ return this.search({ text, fuzzy }, elements).results;
5588
+ }
5589
+ /**
5590
+ * Find elements by role
5591
+ */
5592
+ findByRole(role, name, elements) {
5593
+ const criteria = { role };
5594
+ if (name) {
5595
+ criteria.accessibleName = name;
5596
+ }
5597
+ return this.search(criteria, elements).results;
5598
+ }
5599
+ /**
5600
+ * Find elements by accessible name
5601
+ */
5602
+ findByAccessibleName(name, elements) {
5603
+ return this.search({ accessibleName: name, fuzzy: true }, elements).results;
5604
+ }
5605
+ /**
5606
+ * Find elements near another element
5607
+ */
5608
+ findNear(referenceId, criteria, elements) {
5609
+ return this.search({ ...criteria, near: referenceId }, elements).results;
5610
+ }
5611
+ /**
5612
+ * Find elements within a container
5613
+ */
5614
+ findWithin(containerId, criteria, elements) {
5615
+ return this.search({ ...criteria, within: containerId }, elements).results;
5616
+ }
5617
+ /**
5618
+ * Score an element against search criteria
5619
+ */
5620
+ scoreElement(searchable, criteria) {
5621
+ const scores = {};
5622
+ const matchReasons = [];
5623
+ let totalWeight = 0;
5624
+ let weightedScore = 0;
5625
+ const fuzzyConfig = {
5626
+ ...DEFAULT_FUZZY_CONFIG,
5627
+ threshold: criteria.fuzzyThreshold ?? this.config.fuzzyThreshold
5628
+ };
5629
+ if (criteria.text) {
5630
+ const textScore = this.scoreTextMatch(searchable, criteria.text, criteria.fuzzy !== false, fuzzyConfig.threshold);
5631
+ scores.text = textScore.score;
5632
+ if (textScore.score > 0) {
5633
+ matchReasons.push(...textScore.reasons);
5634
+ }
5635
+ weightedScore += textScore.score * this.config.textWeight;
5636
+ totalWeight += this.config.textWeight;
5637
+ }
5638
+ if (criteria.textContains) {
5639
+ const containsScore = this.scoreContainsMatch(searchable, criteria.textContains, criteria.fuzzy !== false);
5640
+ scores.text = Math.max(scores.text || 0, containsScore.score);
5641
+ if (containsScore.score > 0 && containsScore.reasons.length > 0) {
5642
+ matchReasons.push(...containsScore.reasons);
5643
+ }
5644
+ weightedScore += containsScore.score * this.config.textWeight;
5645
+ totalWeight += this.config.textWeight;
5646
+ }
5647
+ if (criteria.accessibleName) {
5648
+ const accessibilityScore = this.scoreAccessibilityMatch(
5649
+ searchable,
5650
+ criteria.accessibleName,
5651
+ criteria.fuzzy !== false,
5652
+ fuzzyConfig.threshold
5653
+ );
5654
+ scores.accessibility = accessibilityScore.score;
5655
+ if (accessibilityScore.score > 0) {
5656
+ matchReasons.push(...accessibilityScore.reasons);
5657
+ }
5658
+ weightedScore += accessibilityScore.score * this.config.accessibilityWeight;
5659
+ totalWeight += this.config.accessibilityWeight;
5660
+ }
5661
+ if (criteria.role) {
5662
+ const roleScore = this.scoreRoleMatch(searchable, criteria.role);
5663
+ scores.role = roleScore.score;
5664
+ if (roleScore.score > 0) {
5665
+ matchReasons.push(...roleScore.reasons);
5666
+ }
5667
+ weightedScore += roleScore.score * this.config.roleWeight;
5668
+ totalWeight += this.config.roleWeight;
5669
+ }
5670
+ if (criteria.type) {
5671
+ const typeMatch = searchable.type.toLowerCase() === criteria.type.toLowerCase();
5672
+ if (typeMatch) {
5673
+ matchReasons.push(`type: ${criteria.type}`);
5674
+ weightedScore += 1 * this.config.roleWeight;
5675
+ totalWeight += this.config.roleWeight;
5676
+ }
5677
+ }
5678
+ if (criteria.near) {
5679
+ const spatialScore = this.scoreSpatialMatch(searchable, criteria.near);
5680
+ scores.spatial = spatialScore.score;
5681
+ if (spatialScore.score > 0) {
5682
+ matchReasons.push(...spatialScore.reasons);
5683
+ }
5684
+ weightedScore += spatialScore.score * this.config.spatialWeight;
5685
+ totalWeight += this.config.spatialWeight;
5686
+ }
5687
+ if (criteria.placeholder && searchable.placeholder) {
5688
+ const placeholderResult = fuzzyMatch(searchable.placeholder, criteria.placeholder, fuzzyConfig);
5689
+ if (placeholderResult.isMatch) {
5690
+ matchReasons.push(`placeholder matches`);
5691
+ weightedScore += placeholderResult.similarity * this.config.textWeight;
5692
+ totalWeight += this.config.textWeight;
5693
+ }
5694
+ }
5695
+ if (criteria.title && searchable.title) {
5696
+ const titleResult = fuzzyMatch(searchable.title, criteria.title, fuzzyConfig);
5697
+ if (titleResult.isMatch) {
5698
+ matchReasons.push(`title matches`);
5699
+ weightedScore += titleResult.similarity * this.config.textWeight;
5700
+ totalWeight += this.config.textWeight;
5701
+ }
5702
+ }
5703
+ if (criteria.idPattern) {
5704
+ const idMatch = this.matchPattern(searchable.id, criteria.idPattern);
5705
+ if (idMatch) {
5706
+ matchReasons.push(`id matches pattern`);
5707
+ weightedScore += 1 * this.config.textWeight;
5708
+ totalWeight += this.config.textWeight;
5709
+ }
5710
+ }
5711
+ const aliasScore = this.scoreAliasMatch(searchable, criteria, fuzzyConfig.threshold);
5712
+ if (aliasScore.score > 0) {
5713
+ scores.fuzzy = aliasScore.score;
5714
+ matchReasons.push(...aliasScore.reasons);
5715
+ weightedScore += aliasScore.score * this.config.aliasWeight;
5716
+ totalWeight += this.config.aliasWeight;
5717
+ }
5718
+ const confidence = totalWeight > 0 ? weightedScore / totalWeight : 0;
5719
+ const aiElement = this.toAIDiscoveredElement(searchable);
5720
+ return {
5721
+ element: aiElement,
5722
+ confidence,
5723
+ matchReasons,
5724
+ scores
5725
+ };
5726
+ }
5727
+ /**
5728
+ * Score text match
5729
+ */
5730
+ scoreTextMatch(searchable, text, fuzzy, threshold) {
5731
+ const reasons = [];
5732
+ let maxScore = 0;
5733
+ const textsToMatch = [
5734
+ searchable.textContent,
5735
+ searchable.labelText,
5736
+ searchable.value
5737
+ ].filter(Boolean);
5738
+ for (const targetText of textsToMatch) {
5739
+ if (targetText.toLowerCase() === text.toLowerCase()) {
5740
+ maxScore = Math.max(maxScore, 1);
5741
+ reasons.push("exact text match");
5742
+ continue;
5743
+ }
5744
+ if (fuzzy) {
5745
+ const result = fuzzyMatch(targetText, text, { threshold });
5746
+ if (result.isMatch && result.similarity > maxScore) {
5747
+ maxScore = result.similarity;
5748
+ reasons.push(`text similarity: ${(result.similarity * 100).toFixed(0)}%`);
5749
+ }
5750
+ const wordSim = wordSimilarity(targetText, text, { threshold });
5751
+ if (wordSim > maxScore && wordSim >= threshold) {
5752
+ maxScore = wordSim;
5753
+ reasons.push(`word match: ${(wordSim * 100).toFixed(0)}%`);
5754
+ }
5755
+ }
5756
+ }
5757
+ return { score: maxScore, reasons };
5758
+ }
5759
+ /**
5760
+ * Score contains match
5761
+ */
5762
+ scoreContainsMatch(searchable, text, fuzzy) {
5763
+ const reasons = [];
5764
+ let maxScore = 0;
5765
+ const textsToMatch = [
5766
+ searchable.textContent,
5767
+ searchable.labelText,
5768
+ searchable.ariaLabel
5769
+ ].filter(Boolean);
5770
+ for (const targetText of textsToMatch) {
5771
+ if (targetText.toLowerCase().includes(text.toLowerCase())) {
5772
+ maxScore = Math.max(maxScore, 0.9);
5773
+ reasons.push("text contains match");
5774
+ continue;
5775
+ }
5776
+ if (fuzzy && fuzzyContains(targetText, text)) {
5777
+ maxScore = Math.max(maxScore, 0.7);
5778
+ reasons.push("fuzzy contains match");
5779
+ }
5780
+ }
5781
+ return { score: maxScore, reasons };
5782
+ }
5783
+ /**
5784
+ * Score accessibility match
5785
+ */
5786
+ scoreAccessibilityMatch(searchable, name, fuzzy, threshold) {
5787
+ const reasons = [];
5788
+ let maxScore = 0;
5789
+ const accessibleNames = [
5790
+ searchable.ariaLabel,
5791
+ searchable.ariaLabelledBy,
5792
+ searchable.labelText,
5793
+ searchable.title
5794
+ ].filter(Boolean);
5795
+ for (const accessibleName of accessibleNames) {
5796
+ if (accessibleName.toLowerCase() === name.toLowerCase()) {
5797
+ maxScore = Math.max(maxScore, 1);
5798
+ reasons.push("exact accessible name match");
5799
+ continue;
5800
+ }
5801
+ if (fuzzy) {
5802
+ const result = fuzzyMatch(accessibleName, name, { threshold });
5803
+ if (result.isMatch && result.similarity > maxScore) {
5804
+ maxScore = result.similarity;
5805
+ reasons.push(`accessible name similarity: ${(result.similarity * 100).toFixed(0)}%`);
5806
+ }
5807
+ }
5808
+ }
5809
+ return { score: maxScore, reasons };
5810
+ }
5811
+ /**
5812
+ * Score role match
5813
+ */
5814
+ scoreRoleMatch(searchable, role) {
5815
+ const reasons = [];
5816
+ const normalizedRole = role.toLowerCase();
5817
+ if (searchable.role?.toLowerCase() === normalizedRole) {
5818
+ return { score: 1, reasons: [`role: ${role}`] };
5819
+ }
5820
+ const tagRoleMap = {
5821
+ button: ["button", "input[type=button]", "input[type=submit]"],
5822
+ textbox: ["input", "textarea"],
5823
+ checkbox: ["input[type=checkbox]"],
5824
+ radio: ["input[type=radio]"],
5825
+ link: ["a"],
5826
+ listbox: ["select"],
5827
+ combobox: ["select", "input[list]"],
5828
+ navigation: ["nav"],
5829
+ main: ["main"],
5830
+ heading: ["h1", "h2", "h3", "h4", "h5", "h6"]
5831
+ };
5832
+ const inferredRoles = tagRoleMap[normalizedRole] || [];
5833
+ if (inferredRoles.some((r) => searchable.tagName === r || searchable.type.toLowerCase() === normalizedRole)) {
5834
+ return { score: 0.8, reasons: [`inferred role: ${role}`] };
5835
+ }
5836
+ return { score: 0, reasons };
5837
+ }
5838
+ /**
5839
+ * Score spatial match (proximity to another element)
5840
+ */
5841
+ scoreSpatialMatch(searchable, nearId) {
5842
+ const reference = this.cachedElements.find((el) => el.id === nearId);
5843
+ if (!reference) {
5844
+ return { score: 0, reasons: [] };
5845
+ }
5846
+ const distance = this.calculateDistance(searchable.rect, reference.rect);
5847
+ const nearThreshold = 200;
5848
+ if (distance > nearThreshold * 3) {
5849
+ return { score: 0, reasons: [] };
5850
+ }
5851
+ const score = Math.max(0, 1 - distance / (nearThreshold * 3));
5852
+ return {
5853
+ score,
5854
+ reasons: [`${distance.toFixed(0)}px from ${nearId}`]
5855
+ };
5856
+ }
5857
+ /**
5858
+ * Calculate distance between two element rectangles
5859
+ */
5860
+ calculateDistance(rect1, rect2) {
5861
+ const center1 = {
5862
+ x: rect1.x + rect1.width / 2,
5863
+ y: rect1.y + rect1.height / 2
5864
+ };
5865
+ const center2 = {
5866
+ x: rect2.x + rect2.width / 2,
5867
+ y: rect2.y + rect2.height / 2
5868
+ };
5869
+ return Math.sqrt(Math.pow(center1.x - center2.x, 2) + Math.pow(center1.y - center2.y, 2));
5870
+ }
5871
+ /**
5872
+ * Score alias match
5873
+ */
5874
+ scoreAliasMatch(searchable, criteria, threshold) {
5875
+ const reasons = [];
5876
+ let maxScore = 0;
5877
+ const searchTerms = [];
5878
+ if (criteria.text) searchTerms.push(criteria.text);
5879
+ if (criteria.textContains) searchTerms.push(criteria.textContains);
5880
+ if (criteria.accessibleName) searchTerms.push(criteria.accessibleName);
5881
+ for (const searchTerm of searchTerms) {
5882
+ const termLower = searchTerm.toLowerCase();
5883
+ for (const alias of searchable.aliases) {
5884
+ if (alias === termLower) {
5885
+ maxScore = Math.max(maxScore, 1);
5886
+ reasons.push(`alias match: "${alias}"`);
5887
+ continue;
5888
+ }
5889
+ const searchWords = termLower.split(/\s+/);
5890
+ const aliasWords = alias.split(/\s+/);
5891
+ for (const searchWord of searchWords) {
5892
+ for (const aliasWord of aliasWords) {
5893
+ if (areSynonyms(searchWord, aliasWord)) {
5894
+ maxScore = Math.max(maxScore, 0.85);
5895
+ reasons.push(`synonym match: "${searchWord}" ~ "${aliasWord}"`);
5896
+ }
5897
+ }
5898
+ }
5899
+ const result = fuzzyMatch(alias, termLower, { threshold });
5900
+ if (result.isMatch && result.similarity > maxScore) {
5901
+ maxScore = result.similarity;
5902
+ reasons.push(`fuzzy alias: "${alias}" (${(result.similarity * 100).toFixed(0)}%)`);
5903
+ }
5904
+ const tokenSim = tokenSimilarity(alias, termLower);
5905
+ if (tokenSim > maxScore && tokenSim >= threshold) {
5906
+ maxScore = tokenSim;
5907
+ reasons.push(`token match: "${alias}"`);
5908
+ }
5909
+ }
5910
+ }
5911
+ return { score: maxScore, reasons };
5912
+ }
5913
+ /**
5914
+ * Match a string against a pattern (supports * wildcard)
5915
+ */
5916
+ matchPattern(str, pattern) {
5917
+ const regexPattern = pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, ".*");
5918
+ return new RegExp(`^${regexPattern}$`, "i").test(str);
5919
+ }
5920
+ /**
5921
+ * Convert searchable element to AI discovered element
5922
+ */
5923
+ toAIDiscoveredElement(searchable) {
5924
+ const discoveredBase = "getState" in searchable.element ? {
5925
+ id: searchable.id,
5926
+ type: searchable.type,
5927
+ label: searchable.element.label,
5928
+ tagName: searchable.tagName,
5929
+ role: searchable.role,
5930
+ accessibleName: searchable.ariaLabel,
5931
+ actions: searchable.element.actions,
5932
+ state: searchable.state,
5933
+ registered: true
5934
+ } : searchable.element;
5935
+ return {
5936
+ ...discoveredBase,
5937
+ description: searchable.description,
5938
+ aliases: searchable.aliases,
5939
+ purpose: generatePurpose({
5940
+ textContent: searchable.textContent,
5941
+ ariaLabel: searchable.ariaLabel,
5942
+ elementType: searchable.type,
5943
+ tagName: searchable.tagName
5944
+ }),
5945
+ parentContext: void 0,
5946
+ // Would need DOM traversal
5947
+ suggestedActions: generateSuggestedActions({
5948
+ textContent: searchable.textContent,
5949
+ ariaLabel: searchable.ariaLabel,
5950
+ elementType: searchable.type,
5951
+ tagName: searchable.tagName
5952
+ }),
5953
+ semanticType: this.inferSemanticType(searchable),
5954
+ labelText: searchable.labelText,
5955
+ placeholder: searchable.placeholder,
5956
+ title: searchable.title
5957
+ };
5958
+ }
5959
+ /**
5960
+ * Infer a semantic type for the element
5961
+ */
5962
+ inferSemanticType(searchable) {
5963
+ const text = (searchable.textContent || searchable.ariaLabel || "").toLowerCase();
5964
+ const type = searchable.type.toLowerCase();
5965
+ if (type === "input" || type === "textarea") {
5966
+ if (searchable.placeholder?.toLowerCase().includes("email") || text.includes("email")) {
5967
+ return "email-input";
5968
+ }
5969
+ if (searchable.placeholder?.toLowerCase().includes("password") || text.includes("password")) {
5970
+ return "password-input";
5971
+ }
5972
+ if (searchable.placeholder?.toLowerCase().includes("search") || text.includes("search")) {
5973
+ return "search-input";
5974
+ }
5975
+ return "text-input";
5976
+ }
5977
+ if (type === "button") {
5978
+ if (text.match(/submit|save|confirm|ok|done|apply/)) return "submit-button";
5979
+ if (text.match(/cancel|close|dismiss/)) return "cancel-button";
5980
+ if (text.match(/delete|remove|trash/)) return "delete-button";
5981
+ if (text.match(/add|create|new|\+/)) return "add-button";
5982
+ if (text.match(/edit|modify/)) return "edit-button";
5983
+ if (text.match(/next|continue/)) return "next-button";
5984
+ if (text.match(/back|previous/)) return "back-button";
5985
+ return "action-button";
5986
+ }
5987
+ if (type === "link") {
5988
+ if (text.match(/home|dashboard/)) return "home-link";
5989
+ if (text.match(/login|sign.?in/)) return "login-link";
5990
+ if (text.match(/logout|sign.?out/)) return "logout-link";
5991
+ return "navigation-link";
5992
+ }
5993
+ return type;
5994
+ }
5995
+ };
5996
+ function createSearchEngine(config) {
5997
+ return new SearchEngine(config);
5998
+ }
5999
+
6000
+ // src/ai/summary-generator.ts
6001
+ var DEFAULT_SUMMARY_CONFIG = {
6002
+ maxLength: 2e3,
6003
+ includeForms: true,
6004
+ includeElementCounts: true,
6005
+ includeModals: true,
6006
+ includeFocused: true,
6007
+ verbosity: "normal"
6008
+ };
6009
+ function generatePageSummary(elements, pageContext, config = {}) {
6010
+ const finalConfig = { ...DEFAULT_SUMMARY_CONFIG, ...config };
6011
+ const lines = [];
6012
+ if (pageContext) {
6013
+ if (pageContext.title) {
6014
+ lines.push(`Page: "${pageContext.title}"`);
6015
+ }
6016
+ if (pageContext.pageType && pageContext.pageType !== "unknown") {
6017
+ lines.push(`Type: ${formatPageType(pageContext.pageType)}`);
6018
+ }
6019
+ }
6020
+ if (finalConfig.includeElementCounts) {
6021
+ const counts = countElementTypes(elements);
6022
+ const countParts = [];
6023
+ if (counts.button > 0) countParts.push(`${counts.button} button${counts.button > 1 ? "s" : ""}`);
6024
+ if (counts.input > 0) countParts.push(`${counts.input} input${counts.input > 1 ? "s" : ""}`);
6025
+ if (counts.link > 0) countParts.push(`${counts.link} link${counts.link > 1 ? "s" : ""}`);
6026
+ if (counts.select > 0) countParts.push(`${counts.select} dropdown${counts.select > 1 ? "s" : ""}`);
6027
+ if (counts.checkbox > 0) countParts.push(`${counts.checkbox} checkbox${counts.checkbox > 1 ? "es" : ""}`);
6028
+ if (countParts.length > 0) {
6029
+ lines.push(`Contains: ${countParts.join(", ")}`);
6030
+ }
6031
+ }
6032
+ if (finalConfig.includeForms) {
6033
+ const forms = detectForms(elements);
6034
+ if (forms.length > 0) {
6035
+ lines.push("");
6036
+ lines.push("Forms:");
6037
+ for (const form of forms) {
6038
+ lines.push(generateFormSummary(form, finalConfig.verbosity));
6039
+ }
6040
+ }
6041
+ }
6042
+ if (finalConfig.includeModals && pageContext?.activeModals && pageContext.activeModals.length > 0) {
6043
+ lines.push("");
6044
+ lines.push(`Active modals: ${pageContext.activeModals.join(", ")}`);
6045
+ }
6046
+ if (finalConfig.includeFocused && pageContext?.focusedElement) {
6047
+ lines.push(`Focus: ${pageContext.focusedElement}`);
6048
+ }
6049
+ const keyElements = getKeyElements(elements);
6050
+ if (keyElements.length > 0) {
6051
+ lines.push("");
6052
+ lines.push("Key elements:");
6053
+ for (const el of keyElements) {
6054
+ lines.push(` - ${el.description}${el.state.enabled ? "" : " (disabled)"}`);
6055
+ }
6056
+ }
6057
+ let summary = lines.join("\n");
6058
+ if (summary.length > finalConfig.maxLength) {
6059
+ summary = summary.substring(0, finalConfig.maxLength - 3) + "...";
6060
+ }
6061
+ return summary;
6062
+ }
6063
+ function generateElementDescription(element) {
6064
+ const parts = [];
6065
+ const name = element.accessibleName || element.label || element.state.textContent?.trim();
6066
+ if (name) {
6067
+ parts.push(`"${truncate(name, 30)}"`);
6068
+ }
6069
+ parts.push(formatElementType(element.type));
6070
+ const stateIndicators = [];
6071
+ if (!element.state.visible) stateIndicators.push("hidden");
6072
+ if (!element.state.enabled) stateIndicators.push("disabled");
6073
+ if (element.state.focused) stateIndicators.push("focused");
6074
+ if (element.state.checked) stateIndicators.push("checked");
6075
+ if (stateIndicators.length > 0) {
6076
+ parts.push(`(${stateIndicators.join(", ")})`);
6077
+ }
6078
+ if (element.state.value && element.type !== "button") {
6079
+ const valuePreview = truncate(element.state.value, 20);
6080
+ parts.push(`value: "${valuePreview}"`);
6081
+ }
6082
+ return parts.join(" ");
6083
+ }
6084
+ function generateFormSummary(form, verbosity) {
6085
+ const lines = [];
6086
+ const formName = form.name || form.purpose || form.id;
6087
+ lines.push(` ${formName}:`);
6088
+ if (verbosity === "brief") {
6089
+ const fieldCount = form.fields.length;
6090
+ const filledCount = form.fields.filter((f) => f.value).length;
6091
+ lines.push(` ${filledCount}/${fieldCount} fields filled, ${form.isValid ? "valid" : "has errors"}`);
6092
+ } else {
6093
+ for (const field of form.fields) {
6094
+ let fieldLine = ` - ${field.label || field.id}`;
6095
+ if (field.value) {
6096
+ fieldLine += ` = "${truncate(field.value, 15)}"`;
6097
+ } else if (field.placeholder) {
6098
+ fieldLine += ` (${field.placeholder})`;
6099
+ } else {
6100
+ fieldLine += " (empty)";
6101
+ }
6102
+ if (!field.valid && field.error) {
6103
+ fieldLine += ` [ERROR: ${field.error}]`;
6104
+ } else if (field.required && !field.value) {
6105
+ fieldLine += " [required]";
6106
+ }
6107
+ lines.push(fieldLine);
6108
+ }
6109
+ if (form.submitButton) {
6110
+ lines.push(` Submit: ${form.submitButton}`);
6111
+ }
6112
+ }
6113
+ return lines.join("\n");
6114
+ }
6115
+ function generateSnapshotSummary(snapshot, config = {}) {
6116
+ const finalConfig = { ...DEFAULT_SUMMARY_CONFIG, ...config };
6117
+ const lines = [];
6118
+ lines.push(`Page: "${snapshot.page.title}"`);
6119
+ lines.push(`URL: ${snapshot.page.url}`);
6120
+ if (snapshot.page.pageType) {
6121
+ lines.push(`Type: ${formatPageType(snapshot.page.pageType)}`);
6122
+ }
6123
+ if (finalConfig.includeElementCounts) {
6124
+ const countParts = [];
6125
+ for (const [type, count] of Object.entries(snapshot.elementCounts)) {
6126
+ if (count > 0) {
6127
+ countParts.push(`${count} ${type}${count > 1 ? "s" : ""}`);
6128
+ }
6129
+ }
6130
+ if (countParts.length > 0) {
6131
+ lines.push(`Elements: ${countParts.join(", ")}`);
6132
+ }
6133
+ }
6134
+ if (finalConfig.includeForms && snapshot.forms.length > 0) {
6135
+ lines.push("");
6136
+ lines.push("Forms:");
6137
+ for (const form of snapshot.forms) {
6138
+ lines.push(generateFormStateSummary(form));
6139
+ }
6140
+ }
6141
+ if (finalConfig.includeModals && snapshot.activeModals.length > 0) {
6142
+ lines.push("");
6143
+ lines.push("Active dialogs:");
6144
+ for (const modal of snapshot.activeModals) {
6145
+ lines.push(` - ${modal.title || modal.id} (${modal.type})`);
6146
+ }
6147
+ }
6148
+ if (finalConfig.includeFocused && snapshot.focusedElement) {
6149
+ const focused = snapshot.elements.find((e) => e.id === snapshot.focusedElement);
6150
+ if (focused) {
6151
+ lines.push(`Focused: ${generateElementDescription(focused)}`);
6152
+ }
6153
+ }
6154
+ return lines.join("\n");
6155
+ }
6156
+ function generateFormStateSummary(form) {
6157
+ const lines = [];
6158
+ const formName = form.name || form.purpose || form.id;
6159
+ const filledCount = form.fields.filter((f) => f.value).length;
6160
+ const errorCount = form.fields.filter((f) => !f.valid).length;
6161
+ let statusLine = ` ${formName}: ${filledCount}/${form.fields.length} filled`;
6162
+ if (errorCount > 0) {
6163
+ statusLine += `, ${errorCount} error${errorCount > 1 ? "s" : ""}`;
6164
+ }
6165
+ if (form.isDirty) {
6166
+ statusLine += " (modified)";
6167
+ }
6168
+ lines.push(statusLine);
6169
+ for (const field of form.fields) {
6170
+ if (!field.valid && field.error) {
6171
+ lines.push(` ERROR: ${field.label}: ${field.error}`);
6172
+ }
6173
+ }
6174
+ return lines.join("\n");
6175
+ }
6176
+ function generateDiffSummary(appeared, disappeared, modified) {
6177
+ const lines = [];
6178
+ if (appeared.length > 0) {
6179
+ lines.push(`Appeared: ${appeared.join(", ")}`);
6180
+ }
6181
+ if (disappeared.length > 0) {
6182
+ lines.push(`Disappeared: ${disappeared.join(", ")}`);
6183
+ }
6184
+ if (modified.length > 0) {
6185
+ lines.push("Changed:");
6186
+ for (const mod of modified.slice(0, 5)) {
6187
+ lines.push(` - ${mod.description}: ${mod.property} changed from "${mod.from}" to "${mod.to}"`);
6188
+ }
6189
+ if (modified.length > 5) {
6190
+ lines.push(` ... and ${modified.length - 5} more changes`);
6191
+ }
6192
+ }
6193
+ if (lines.length === 0) {
6194
+ return "No changes detected";
6195
+ }
6196
+ return lines.join("\n");
6197
+ }
6198
+ function countElementTypes(elements) {
6199
+ const counts = {};
6200
+ for (const el of elements) {
6201
+ const type = el.type.toLowerCase();
6202
+ counts[type] = (counts[type] || 0) + 1;
6203
+ }
6204
+ return counts;
6205
+ }
6206
+ function detectForms(elements) {
6207
+ const formElements = elements.filter(
6208
+ (el) => el.type === "input" || el.type === "textarea" || el.type === "select" || el.type === "checkbox"
6209
+ );
6210
+ if (formElements.length === 0) return [];
6211
+ const forms = [];
6212
+ const submitButtons = elements.filter(
6213
+ (el) => el.type === "button" && (el.state.textContent?.toLowerCase().includes("submit") || el.state.textContent?.toLowerCase().includes("save") || el.state.textContent?.toLowerCase().includes("send") || el.semanticType === "submit-button")
6214
+ );
6215
+ const defaultForm = {
6216
+ id: "detected-form",
6217
+ purpose: inferFormPurpose(formElements),
6218
+ fields: formElements.map((el) => ({
6219
+ id: el.id,
6220
+ label: el.labelText || el.accessibleName || el.placeholder || el.id,
6221
+ type: el.type,
6222
+ value: el.state.value || "",
6223
+ valid: true,
6224
+ // Can't determine without validation state
6225
+ required: false,
6226
+ // Can't determine without DOM access
6227
+ placeholder: el.placeholder
6228
+ })),
6229
+ isValid: true,
6230
+ submitButton: submitButtons[0]?.id
6231
+ };
6232
+ if (defaultForm.fields.length > 0) {
6233
+ forms.push(defaultForm);
6234
+ }
6235
+ return forms;
6236
+ }
6237
+ function inferFormPurpose(fields) {
6238
+ const labels = fields.map(
6239
+ (f) => (f.labelText || f.accessibleName || f.placeholder || "").toLowerCase()
6240
+ );
6241
+ const allLabels = labels.join(" ");
6242
+ if (allLabels.includes("email") && allLabels.includes("password")) {
6243
+ if (allLabels.includes("confirm") || allLabels.includes("name")) {
6244
+ return "Registration form";
6245
+ }
6246
+ return "Login form";
6247
+ }
6248
+ if (allLabels.includes("search")) {
6249
+ return "Search form";
6250
+ }
6251
+ if (allLabels.includes("address") || allLabels.includes("city") || allLabels.includes("zip")) {
6252
+ return "Address form";
6253
+ }
6254
+ if (allLabels.includes("card") || allLabels.includes("cvv") || allLabels.includes("expir")) {
6255
+ return "Payment form";
6256
+ }
6257
+ if (allLabels.includes("contact") || allLabels.includes("message")) {
6258
+ return "Contact form";
6259
+ }
6260
+ return "Form";
6261
+ }
6262
+ function getKeyElements(elements) {
6263
+ const keyElements = [];
6264
+ const actionButtons = elements.filter(
6265
+ (el) => el.type === "button" && el.state.visible && (el.semanticType?.includes("submit") || el.semanticType?.includes("action") || el.semanticType?.includes("next"))
6266
+ );
6267
+ keyElements.push(...actionButtons.slice(0, 2));
6268
+ const primaryInputs = elements.filter(
6269
+ (el) => (el.type === "input" || el.type === "textarea") && el.state.visible
6270
+ );
6271
+ keyElements.push(...primaryInputs.slice(0, 3));
6272
+ const links = elements.filter((el) => el.type === "link" && el.state.visible);
6273
+ keyElements.push(...links.slice(0, 2));
6274
+ const unique = [...new Map(keyElements.map((e) => [e.id, e])).values()];
6275
+ return unique.slice(0, 8);
6276
+ }
6277
+ function formatPageType(pageType) {
6278
+ const typeLabels = {
6279
+ login: "Login page",
6280
+ dashboard: "Dashboard",
6281
+ form: "Form page",
6282
+ list: "List/table page",
6283
+ detail: "Detail page",
6284
+ search: "Search page",
6285
+ checkout: "Checkout page",
6286
+ settings: "Settings page",
6287
+ unknown: "Unknown"
6288
+ };
6289
+ return typeLabels[pageType || "unknown"] || "Page";
6290
+ }
6291
+ function formatElementType(type) {
6292
+ const typeLabels = {
6293
+ button: "button",
6294
+ input: "input field",
6295
+ textarea: "text area",
6296
+ select: "dropdown",
6297
+ checkbox: "checkbox",
6298
+ radio: "radio button",
6299
+ link: "link",
6300
+ form: "form",
6301
+ menu: "menu",
6302
+ menuitem: "menu item",
6303
+ tab: "tab",
6304
+ dialog: "dialog",
6305
+ switch: "switch",
6306
+ slider: "slider"
6307
+ };
6308
+ return typeLabels[type.toLowerCase()] || type;
6309
+ }
6310
+ function truncate(str, maxLength) {
6311
+ if (str.length <= maxLength) return str;
6312
+ return str.substring(0, maxLength - 3) + "...";
6313
+ }
6314
+ function inferPageType(url, title, elements) {
6315
+ const urlLower = url.toLowerCase();
6316
+ const titleLower = title.toLowerCase();
6317
+ if (urlLower.includes("login") || urlLower.includes("signin")) return "login";
6318
+ if (urlLower.includes("dashboard")) return "dashboard";
6319
+ if (urlLower.includes("search")) return "search";
6320
+ if (urlLower.includes("checkout") || urlLower.includes("payment")) return "checkout";
6321
+ if (urlLower.includes("settings") || urlLower.includes("preferences")) return "settings";
6322
+ if (titleLower.includes("login") || titleLower.includes("sign in")) return "login";
6323
+ if (titleLower.includes("dashboard")) return "dashboard";
6324
+ if (titleLower.includes("search")) return "search";
6325
+ const hasLoginForm = elements.some((el) => el.type === "input" && el.semanticType === "email-input") && elements.some((el) => el.type === "input" && el.semanticType === "password-input");
6326
+ if (hasLoginForm) return "login";
6327
+ const hasSearchInput = elements.some(
6328
+ (el) => el.type === "input" && el.semanticType === "search-input"
6329
+ );
6330
+ if (hasSearchInput) return "search";
6331
+ const inputCount = elements.filter(
6332
+ (el) => el.type === "input" || el.type === "textarea" || el.type === "select"
6333
+ ).length;
6334
+ if (inputCount >= 3) return "form";
6335
+ const hasTable = elements.some((el) => el.tagName === "table");
6336
+ const hasMany = elements.length > 20;
6337
+ if (hasTable || hasMany) return "list";
6338
+ return "unknown";
6339
+ }
6340
+
6341
+ // src/ai/nl-action-parser.ts
6342
+ var ACTION_PATTERNS = [
6343
+ // Click patterns
6344
+ {
6345
+ regex: /^click\s+(?:on\s+)?(?:the\s+)?(.+?)(?:\s+button)?$/i,
6346
+ action: "click",
6347
+ targetGroup: 1,
6348
+ confidence: 0.95
6349
+ },
6350
+ {
6351
+ regex: /^press\s+(?:the\s+)?(.+?)(?:\s+button)?$/i,
6352
+ action: "click",
6353
+ targetGroup: 1,
6354
+ confidence: 0.9
6355
+ },
6356
+ {
6357
+ regex: /^tap\s+(?:on\s+)?(?:the\s+)?(.+)$/i,
6358
+ action: "click",
6359
+ targetGroup: 1,
6360
+ confidence: 0.85
6361
+ },
6362
+ {
6363
+ regex: /^activate\s+(?:the\s+)?(.+)$/i,
6364
+ action: "click",
6365
+ targetGroup: 1,
6366
+ confidence: 0.8
6367
+ },
6368
+ // Double click patterns
6369
+ {
6370
+ regex: /^double[\s-]?click\s+(?:on\s+)?(?:the\s+)?(.+)$/i,
6371
+ action: "doubleClick",
6372
+ targetGroup: 1,
6373
+ confidence: 0.95
6374
+ },
6375
+ // Right click patterns
6376
+ {
6377
+ regex: /^right[\s-]?click\s+(?:on\s+)?(?:the\s+)?(.+)$/i,
6378
+ action: "rightClick",
6379
+ targetGroup: 1,
6380
+ confidence: 0.95
6381
+ },
6382
+ {
6383
+ regex: /^context\s+click\s+(?:on\s+)?(?:the\s+)?(.+)$/i,
6384
+ action: "rightClick",
6385
+ targetGroup: 1,
6386
+ confidence: 0.9
6387
+ },
6388
+ // Type patterns - "type X in Y"
6389
+ {
6390
+ regex: /^type\s+["'](.+?)["']\s+(?:in(?:to)?|on)\s+(?:the\s+)?(.+)$/i,
6391
+ action: "type",
6392
+ targetGroup: 2,
6393
+ valueGroup: 1,
6394
+ confidence: 0.95
6395
+ },
6396
+ {
6397
+ regex: /^type\s+(.+?)\s+(?:in(?:to)?|on)\s+(?:the\s+)?(.+)$/i,
6398
+ action: "type",
6399
+ targetGroup: 2,
6400
+ valueGroup: 1,
6401
+ confidence: 0.85
6402
+ },
6403
+ // Type patterns - "enter X in Y"
6404
+ {
6405
+ regex: /^enter\s+["'](.+?)["']\s+(?:in(?:to)?|on)\s+(?:the\s+)?(.+)$/i,
6406
+ action: "type",
6407
+ targetGroup: 2,
6408
+ valueGroup: 1,
6409
+ confidence: 0.95
6410
+ },
6411
+ {
6412
+ regex: /^enter\s+(.+?)\s+(?:in(?:to)?|on)\s+(?:the\s+)?(.+)$/i,
6413
+ action: "type",
6414
+ targetGroup: 2,
6415
+ valueGroup: 1,
6416
+ confidence: 0.85
6417
+ },
6418
+ // Type patterns - "input X into Y"
6419
+ {
6420
+ regex: /^input\s+["'](.+?)["']\s+(?:in(?:to)?)\s+(?:the\s+)?(.+)$/i,
6421
+ action: "type",
6422
+ targetGroup: 2,
6423
+ valueGroup: 1,
6424
+ confidence: 0.9
6425
+ },
6426
+ // Type patterns - "fill Y with X"
6427
+ {
6428
+ regex: /^fill\s+(?:in\s+)?(?:the\s+)?(.+?)\s+with\s+["'](.+?)["']$/i,
6429
+ action: "type",
6430
+ targetGroup: 1,
6431
+ valueGroup: 2,
6432
+ confidence: 0.95
6433
+ },
6434
+ {
6435
+ regex: /^fill\s+(?:in\s+)?(?:the\s+)?(.+?)\s+with\s+(.+)$/i,
6436
+ action: "type",
6437
+ targetGroup: 1,
6438
+ valueGroup: 2,
6439
+ confidence: 0.85
6440
+ },
6441
+ // Type patterns - "set Y to X"
6442
+ {
6443
+ regex: /^set\s+(?:the\s+)?(.+?)\s+to\s+["'](.+?)["']$/i,
6444
+ action: "type",
6445
+ targetGroup: 1,
6446
+ valueGroup: 2,
6447
+ confidence: 0.9
6448
+ },
6449
+ // Select patterns
6450
+ {
6451
+ regex: /^select\s+["'](.+?)["']\s+(?:from|in)\s+(?:the\s+)?(.+)$/i,
6452
+ action: "select",
6453
+ targetGroup: 2,
6454
+ valueGroup: 1,
6455
+ confidence: 0.95
6456
+ },
6457
+ {
6458
+ regex: /^choose\s+["'](.+?)["']\s+(?:from|in)\s+(?:the\s+)?(.+)$/i,
6459
+ action: "select",
6460
+ targetGroup: 2,
6461
+ valueGroup: 1,
6462
+ confidence: 0.9
6463
+ },
6464
+ {
6465
+ regex: /^pick\s+["'](.+?)["']\s+(?:from|in)\s+(?:the\s+)?(.+)$/i,
6466
+ action: "select",
6467
+ targetGroup: 2,
6468
+ valueGroup: 1,
6469
+ confidence: 0.85
6470
+ },
6471
+ // Check patterns
6472
+ {
6473
+ regex: /^check\s+(?:the\s+)?(.+?)(?:\s+checkbox)?$/i,
6474
+ action: "check",
6475
+ targetGroup: 1,
6476
+ confidence: 0.9
6477
+ },
6478
+ {
6479
+ regex: /^enable\s+(?:the\s+)?(.+)$/i,
6480
+ action: "check",
6481
+ targetGroup: 1,
6482
+ confidence: 0.8
6483
+ },
6484
+ {
6485
+ regex: /^tick\s+(?:the\s+)?(.+)$/i,
6486
+ action: "check",
6487
+ targetGroup: 1,
6488
+ confidence: 0.85
6489
+ },
6490
+ // Uncheck patterns
6491
+ {
6492
+ regex: /^uncheck\s+(?:the\s+)?(.+?)(?:\s+checkbox)?$/i,
6493
+ action: "uncheck",
6494
+ targetGroup: 1,
6495
+ confidence: 0.9
6496
+ },
6497
+ {
6498
+ regex: /^disable\s+(?:the\s+)?(.+)$/i,
6499
+ action: "uncheck",
6500
+ targetGroup: 1,
6501
+ confidence: 0.8
6502
+ },
6503
+ {
6504
+ regex: /^untick\s+(?:the\s+)?(.+)$/i,
6505
+ action: "uncheck",
6506
+ targetGroup: 1,
6507
+ confidence: 0.85
6508
+ },
6509
+ // Clear patterns
6510
+ {
6511
+ regex: /^clear\s+(?:the\s+)?(.+)$/i,
6512
+ action: "clear",
6513
+ targetGroup: 1,
6514
+ confidence: 0.9
6515
+ },
6516
+ {
6517
+ regex: /^erase\s+(?:the\s+)?(.+)$/i,
6518
+ action: "clear",
6519
+ targetGroup: 1,
6520
+ confidence: 0.85
6521
+ },
6522
+ {
6523
+ regex: /^empty\s+(?:the\s+)?(.+)$/i,
6524
+ action: "clear",
6525
+ targetGroup: 1,
6526
+ confidence: 0.8
6527
+ },
6528
+ // Hover patterns
6529
+ {
6530
+ regex: /^hover\s+(?:over\s+)?(?:the\s+)?(.+)$/i,
6531
+ action: "hover",
6532
+ targetGroup: 1,
6533
+ confidence: 0.9
6534
+ },
6535
+ {
6536
+ regex: /^mouse\s+over\s+(?:the\s+)?(.+)$/i,
6537
+ action: "hover",
6538
+ targetGroup: 1,
6539
+ confidence: 0.85
6540
+ },
6541
+ // Focus patterns
6542
+ {
6543
+ regex: /^focus\s+(?:on\s+)?(?:the\s+)?(.+)$/i,
6544
+ action: "focus",
6545
+ targetGroup: 1,
6546
+ confidence: 0.9
6547
+ },
6548
+ // Scroll patterns
6549
+ {
6550
+ regex: /^scroll\s+(up|down|left|right)$/i,
6551
+ action: "scroll",
6552
+ targetGroup: 1,
6553
+ confidence: 0.9
6554
+ },
6555
+ {
6556
+ regex: /^scroll\s+(?:the\s+)?(.+?)\s+(up|down|left|right)$/i,
6557
+ action: "scroll",
6558
+ targetGroup: 1,
6559
+ confidence: 0.85
6560
+ },
6561
+ {
6562
+ regex: /^scroll\s+to\s+(?:the\s+)?(.+)$/i,
6563
+ action: "scroll",
6564
+ targetGroup: 1,
6565
+ confidence: 0.85
6566
+ },
6567
+ // Wait patterns
6568
+ {
6569
+ regex: /^wait\s+(?:for\s+)?(?:the\s+)?(.+?)(?:\s+to\s+(?:be\s+)?(.+))?$/i,
6570
+ action: "wait",
6571
+ targetGroup: 1,
6572
+ confidence: 0.85
6573
+ },
6574
+ {
6575
+ regex: /^wait\s+until\s+(?:the\s+)?(.+?)(?:\s+(?:is|becomes)\s+(.+))?$/i,
6576
+ action: "wait",
6577
+ targetGroup: 1,
6578
+ confidence: 0.85
6579
+ },
6580
+ // Assert patterns
6581
+ {
6582
+ regex: /^(?:assert|verify|check)\s+(?:that\s+)?(?:the\s+)?(.+?)\s+(?:is\s+)?(visible|hidden|enabled|disabled|checked|unchecked|focused)$/i,
6583
+ action: "assert",
6584
+ targetGroup: 1,
6585
+ confidence: 0.9
6586
+ },
6587
+ {
6588
+ regex: /^(?:assert|verify|check)\s+(?:that\s+)?(?:the\s+)?(.+?)\s+(?:contains|has)\s+["'](.+?)["']$/i,
6589
+ action: "assert",
6590
+ targetGroup: 1,
6591
+ valueGroup: 2,
6592
+ confidence: 0.9
6593
+ },
6594
+ {
6595
+ regex: /^(?:the\s+)?(.+?)\s+should\s+(?:be\s+)?(visible|hidden|enabled|disabled|checked|unchecked|focused)$/i,
6596
+ action: "assert",
6597
+ targetGroup: 1,
6598
+ confidence: 0.85
6599
+ }
6600
+ ];
6601
+ var ASSERTION_TYPE_MAP = {
6602
+ visible: "visible",
6603
+ hidden: "hidden",
6604
+ enabled: "enabled",
6605
+ disabled: "disabled",
6606
+ checked: "checked",
6607
+ unchecked: "unchecked",
6608
+ focused: "focused",
6609
+ contains: "containsText",
6610
+ has: "hasText"
6611
+ };
6612
+ function parseNLInstruction(instruction) {
6613
+ const trimmed = instruction.trim();
6614
+ if (!trimmed) return null;
6615
+ for (const pattern of ACTION_PATTERNS) {
6616
+ const match = trimmed.match(pattern.regex);
6617
+ if (match) {
6618
+ const parsed = {
6619
+ action: pattern.action,
6620
+ targetDescription: cleanTargetDescription(match[pattern.targetGroup] || ""),
6621
+ rawInstruction: instruction,
6622
+ parseConfidence: pattern.confidence
6623
+ };
6624
+ if (pattern.valueGroup && match[pattern.valueGroup]) {
6625
+ parsed.value = match[pattern.valueGroup];
6626
+ }
6627
+ if (pattern.modifierExtractor) {
6628
+ parsed.modifiers = pattern.modifierExtractor(match);
6629
+ }
6630
+ if (pattern.action === "scroll") {
6631
+ const directionMatch = trimmed.match(/(up|down|left|right)/i);
6632
+ if (directionMatch) {
6633
+ parsed.scrollDirection = directionMatch[1].toLowerCase();
6634
+ }
6635
+ }
6636
+ if (pattern.action === "assert") {
6637
+ const assertMatch = trimmed.match(/(visible|hidden|enabled|disabled|checked|unchecked|focused|contains|has)/i);
6638
+ if (assertMatch) {
6639
+ parsed.assertionType = ASSERTION_TYPE_MAP[assertMatch[1].toLowerCase()];
6640
+ }
6641
+ }
6642
+ if (pattern.action === "wait") {
6643
+ const waitCondition = match[2];
6644
+ if (waitCondition) {
6645
+ parsed.waitCondition = waitCondition;
6646
+ }
6647
+ }
6648
+ return parsed;
6649
+ }
6650
+ }
6651
+ return inferAction(trimmed);
6652
+ }
6653
+ function cleanTargetDescription(target) {
6654
+ return target.trim().replace(/^(the|a|an)\s+/i, "").replace(/\s+(button|field|input|link|dropdown|checkbox|radio)$/i, "").trim();
6655
+ }
6656
+ function inferAction(instruction) {
6657
+ const lower = instruction.toLowerCase();
6658
+ if (lower.includes("click") || lower.includes("press") || lower.includes("tap")) {
6659
+ const target = instruction.replace(/click|press|tap|on|the/gi, "").trim();
6660
+ if (target) {
6661
+ return {
6662
+ action: "click",
6663
+ targetDescription: cleanTargetDescription(target),
6664
+ rawInstruction: instruction,
6665
+ parseConfidence: 0.6
6666
+ };
6667
+ }
6668
+ }
6669
+ if (lower.includes("type") || lower.includes("enter") || lower.includes("input")) {
6670
+ const quotedMatch = instruction.match(/["'](.+?)["']/);
6671
+ if (quotedMatch) {
6672
+ const target = instruction.replace(/type|enter|input|into|in|the|["'].*?["']/gi, "").trim();
6673
+ return {
6674
+ action: "type",
6675
+ targetDescription: cleanTargetDescription(target),
6676
+ value: quotedMatch[1],
6677
+ rawInstruction: instruction,
6678
+ parseConfidence: 0.5
6679
+ };
6680
+ }
6681
+ }
6682
+ return null;
6683
+ }
6684
+ function parseNLInstructions(instructions) {
6685
+ const parsed = [];
6686
+ for (const instruction of instructions) {
6687
+ const result = parseNLInstruction(instruction);
6688
+ if (result) {
6689
+ parsed.push(result);
6690
+ }
6691
+ }
6692
+ return parsed;
6693
+ }
6694
+ function splitCompoundInstruction(instruction) {
6695
+ const parts = instruction.split(/\s+(?:and|then|,\s*then|,\s*and|,)\s+/i);
6696
+ return parts.map((p) => p.trim()).filter((p) => p.length > 0);
6697
+ }
6698
+ function extractModifiers(instruction) {
6699
+ const modifiers = [];
6700
+ const lower = instruction.toLowerCase();
6701
+ if (lower.includes("shift") || lower.includes("with shift")) {
6702
+ modifiers.push("shift");
6703
+ }
6704
+ if (lower.includes("ctrl") || lower.includes("control") || lower.includes("with ctrl")) {
6705
+ modifiers.push("ctrl");
6706
+ }
6707
+ if (lower.includes("alt") || lower.includes("with alt") || lower.includes("option")) {
6708
+ modifiers.push("alt");
6709
+ }
6710
+ if (lower.includes("meta") || lower.includes("command") || lower.includes("cmd") || lower.includes("windows")) {
6711
+ modifiers.push("meta");
6712
+ }
6713
+ return modifiers.length > 0 ? modifiers : void 0;
6714
+ }
6715
+ function validateParsedAction(action) {
6716
+ const errors = [];
6717
+ if (!action.targetDescription && action.action !== "scroll") {
6718
+ errors.push("No target element specified");
6719
+ }
6720
+ if ((action.action === "type" || action.action === "select") && !action.value) {
6721
+ errors.push(`No value specified for ${action.action} action`);
6722
+ }
6723
+ if (action.parseConfidence < 0.5) {
6724
+ errors.push("Low confidence parsing - instruction may be ambiguous");
6725
+ }
6726
+ return {
6727
+ valid: errors.length === 0,
6728
+ errors
6729
+ };
6730
+ }
6731
+ function describeAction(action) {
6732
+ switch (action.action) {
6733
+ case "click":
6734
+ return `Click on "${action.targetDescription}"`;
6735
+ case "doubleClick":
6736
+ return `Double-click on "${action.targetDescription}"`;
6737
+ case "rightClick":
6738
+ return `Right-click on "${action.targetDescription}"`;
6739
+ case "type":
6740
+ return `Type "${action.value}" into "${action.targetDescription}"`;
6741
+ case "select":
6742
+ return `Select "${action.value}" from "${action.targetDescription}"`;
6743
+ case "check":
6744
+ return `Check "${action.targetDescription}"`;
6745
+ case "uncheck":
6746
+ return `Uncheck "${action.targetDescription}"`;
6747
+ case "clear":
6748
+ return `Clear "${action.targetDescription}"`;
6749
+ case "hover":
6750
+ return `Hover over "${action.targetDescription}"`;
6751
+ case "focus":
6752
+ return `Focus on "${action.targetDescription}"`;
6753
+ case "scroll":
6754
+ if (action.scrollDirection) {
6755
+ return `Scroll ${action.scrollDirection}`;
6756
+ }
6757
+ return `Scroll to "${action.targetDescription}"`;
6758
+ case "wait":
6759
+ return `Wait for "${action.targetDescription}"${action.waitCondition ? ` to be ${action.waitCondition}` : ""}`;
6760
+ case "assert":
6761
+ return `Assert "${action.targetDescription}" is ${action.assertionType || "valid"}`;
6762
+ default:
6763
+ return `${action.action} on "${action.targetDescription}"`;
6764
+ }
6765
+ }
6766
+
6767
+ // src/ai/error-context.ts
6768
+ function getElementState5(el) {
6769
+ if ("state" in el && el.state) {
6770
+ return el.state;
6771
+ }
6772
+ if ("getState" in el && typeof el.getState === "function") {
6773
+ try {
6774
+ return el.getState();
6775
+ } catch {
6776
+ return void 0;
6777
+ }
6778
+ }
6779
+ return void 0;
6780
+ }
6781
+ var ErrorCodes = {
6782
+ // Parsing errors
6783
+ PARSE_ERROR: "PARSE_ERROR",
6784
+ VALIDATION_ERROR: "VALIDATION_ERROR",
6785
+ // Element errors
6786
+ ELEMENT_NOT_FOUND: "ELEMENT_NOT_FOUND",
6787
+ ELEMENT_NOT_VISIBLE: "ELEMENT_NOT_VISIBLE",
6788
+ ELEMENT_DISABLED: "ELEMENT_DISABLED",
6789
+ ELEMENT_BLOCKED: "ELEMENT_BLOCKED",
6790
+ MULTIPLE_ELEMENTS: "MULTIPLE_ELEMENTS",
6791
+ // Search errors
6792
+ LOW_CONFIDENCE: "LOW_CONFIDENCE",
6793
+ AMBIGUOUS_MATCH: "AMBIGUOUS_MATCH",
6794
+ // Action errors
6795
+ ACTION_FAILED: "ACTION_FAILED",
6796
+ ACTION_TIMEOUT: "ACTION_TIMEOUT",
6797
+ UNSUPPORTED_ACTION: "UNSUPPORTED_ACTION",
6798
+ // State errors
6799
+ UNEXPECTED_STATE: "UNEXPECTED_STATE",
6800
+ STALE_ELEMENT: "STALE_ELEMENT",
6801
+ // Page errors
6802
+ PAGE_LOAD_ERROR: "PAGE_LOAD_ERROR",
6803
+ NAVIGATION_ERROR: "NAVIGATION_ERROR"
6804
+ };
6805
+ var ERROR_MESSAGES = {
6806
+ PARSE_ERROR: "Could not parse the natural language instruction",
6807
+ VALIDATION_ERROR: "The parsed action failed validation",
6808
+ ELEMENT_NOT_FOUND: "No element matching the description could be found",
6809
+ ELEMENT_NOT_VISIBLE: "The element exists but is not visible",
6810
+ ELEMENT_DISABLED: "The element is disabled and cannot be interacted with",
6811
+ ELEMENT_BLOCKED: "The element is blocked by another element",
6812
+ MULTIPLE_ELEMENTS: "Multiple elements match the description",
6813
+ LOW_CONFIDENCE: "The best match has low confidence",
6814
+ AMBIGUOUS_MATCH: "Multiple elements match with similar confidence",
6815
+ ACTION_FAILED: "The action could not be completed",
6816
+ ACTION_TIMEOUT: "The action timed out waiting for a condition",
6817
+ UNSUPPORTED_ACTION: "The requested action is not supported",
6818
+ UNEXPECTED_STATE: "The element is in an unexpected state",
6819
+ STALE_ELEMENT: "The element is no longer attached to the DOM",
6820
+ PAGE_LOAD_ERROR: "The page failed to load correctly",
6821
+ NAVIGATION_ERROR: "Navigation to the target page failed"
6822
+ };
6823
+ var ERROR_SUGGESTIONS = {
6824
+ PARSE_ERROR: [
6825
+ {
6826
+ action: 'Use a simpler instruction format like "click Submit button"',
6827
+ confidence: 0.8,
6828
+ priority: 1
6829
+ },
6830
+ {
6831
+ action: "Use specific element names visible on the page",
6832
+ confidence: 0.7,
6833
+ priority: 2
6834
+ }
6835
+ ],
6836
+ VALIDATION_ERROR: [
6837
+ {
6838
+ action: "Provide required parameters for the action",
6839
+ confidence: 0.9,
6840
+ priority: 1
6841
+ },
6842
+ {
6843
+ action: "Check the instruction format",
6844
+ confidence: 0.7,
6845
+ priority: 2
6846
+ }
6847
+ ],
6848
+ ELEMENT_NOT_FOUND: [
6849
+ {
6850
+ action: "Wait for the page to fully load",
6851
+ command: "wait for page to load",
6852
+ confidence: 0.7,
6853
+ priority: 1
6854
+ },
6855
+ {
6856
+ action: "Use a different description for the element",
6857
+ confidence: 0.8,
6858
+ priority: 2
6859
+ },
6860
+ {
6861
+ action: "Scroll the page to reveal the element",
6862
+ command: "scroll down",
6863
+ confidence: 0.6,
6864
+ priority: 3
6865
+ }
6866
+ ],
6867
+ ELEMENT_NOT_VISIBLE: [
6868
+ {
6869
+ action: "Scroll to make the element visible",
6870
+ command: "scroll to element",
6871
+ confidence: 0.9,
6872
+ priority: 1
6873
+ },
6874
+ {
6875
+ action: "Close any overlaying elements",
6876
+ confidence: 0.7,
6877
+ priority: 2
6878
+ },
6879
+ {
6880
+ action: "Wait for loading to complete",
6881
+ command: "wait for loading",
6882
+ confidence: 0.6,
6883
+ priority: 3
6884
+ }
6885
+ ],
6886
+ ELEMENT_DISABLED: [
6887
+ {
6888
+ action: "Fill in required fields first",
6889
+ confidence: 0.8,
6890
+ priority: 1
6891
+ },
6892
+ {
6893
+ action: "Complete prerequisite steps",
6894
+ confidence: 0.7,
6895
+ priority: 2
6896
+ },
6897
+ {
6898
+ action: "Wait for the element to become enabled",
6899
+ command: "wait for element to be enabled",
6900
+ confidence: 0.6,
6901
+ priority: 3
6902
+ }
6903
+ ],
6904
+ ELEMENT_BLOCKED: [
6905
+ {
6906
+ action: "Close the modal or popup",
6907
+ command: "click close button",
6908
+ confidence: 0.9,
6909
+ priority: 1
6910
+ },
6911
+ {
6912
+ action: "Dismiss the overlay",
6913
+ confidence: 0.8,
6914
+ priority: 2
6915
+ },
6916
+ {
6917
+ action: "Wait for the blocking element to disappear",
6918
+ confidence: 0.6,
6919
+ priority: 3
6920
+ }
6921
+ ],
6922
+ MULTIPLE_ELEMENTS: [
6923
+ {
6924
+ action: "Use a more specific description",
6925
+ confidence: 0.9,
6926
+ priority: 1
6927
+ },
6928
+ {
6929
+ action: "Include the element position (first, second, etc.)",
6930
+ confidence: 0.8,
6931
+ priority: 2
6932
+ },
6933
+ {
6934
+ action: "Use the element ID directly",
6935
+ confidence: 0.7,
6936
+ priority: 3
6937
+ }
6938
+ ],
6939
+ LOW_CONFIDENCE: [
6940
+ {
6941
+ action: "Use the exact text shown on the element",
6942
+ confidence: 0.9,
6943
+ priority: 1
6944
+ },
6945
+ {
6946
+ action: "Lower the confidence threshold if the match is correct",
6947
+ confidence: 0.7,
6948
+ priority: 2
6949
+ },
6950
+ {
6951
+ action: "Try a different way to describe the element",
6952
+ confidence: 0.6,
6953
+ priority: 3
6954
+ }
6955
+ ],
6956
+ AMBIGUOUS_MATCH: [
6957
+ {
6958
+ action: "Be more specific about which element you mean",
6959
+ confidence: 0.9,
6960
+ priority: 1
6961
+ },
6962
+ {
6963
+ action: "Include the section or form name",
6964
+ confidence: 0.8,
6965
+ priority: 2
6966
+ }
6967
+ ],
6968
+ ACTION_FAILED: [
6969
+ {
6970
+ action: "Check if the element is interactable",
6971
+ confidence: 0.7,
6972
+ priority: 1
6973
+ },
6974
+ {
6975
+ action: "Wait and retry the action",
6976
+ command: "wait 1 second then retry",
6977
+ confidence: 0.6,
6978
+ priority: 2
6979
+ }
6980
+ ],
6981
+ ACTION_TIMEOUT: [
6982
+ {
6983
+ action: "Increase the timeout duration",
6984
+ confidence: 0.8,
6985
+ priority: 1
6986
+ },
6987
+ {
6988
+ action: "Check if the condition can ever be met",
6989
+ confidence: 0.7,
6990
+ priority: 2
6991
+ }
6992
+ ],
6993
+ UNSUPPORTED_ACTION: [
6994
+ {
6995
+ action: "Use a different action type",
6996
+ confidence: 0.9,
6997
+ priority: 1
6998
+ },
6999
+ {
7000
+ action: "Break down into simpler actions",
7001
+ confidence: 0.7,
7002
+ priority: 2
7003
+ }
7004
+ ],
7005
+ UNEXPECTED_STATE: [
7006
+ {
7007
+ action: "Refresh the page state",
7008
+ command: "refresh",
7009
+ confidence: 0.7,
7010
+ priority: 1
7011
+ },
7012
+ {
7013
+ action: "Wait for state to stabilize",
7014
+ command: "wait 2 seconds",
7015
+ confidence: 0.6,
7016
+ priority: 2
7017
+ }
7018
+ ],
7019
+ STALE_ELEMENT: [
7020
+ {
7021
+ action: "Re-find the element",
7022
+ confidence: 0.9,
7023
+ priority: 1
7024
+ },
7025
+ {
7026
+ action: "Wait for page to stabilize",
7027
+ command: "wait 1 second",
7028
+ confidence: 0.7,
7029
+ priority: 2
7030
+ }
7031
+ ],
7032
+ PAGE_LOAD_ERROR: [
7033
+ {
7034
+ action: "Refresh the page",
7035
+ command: "refresh page",
7036
+ confidence: 0.8,
7037
+ priority: 1
7038
+ },
7039
+ {
7040
+ action: "Check network connectivity",
7041
+ confidence: 0.6,
7042
+ priority: 2
7043
+ }
7044
+ ],
7045
+ NAVIGATION_ERROR: [
7046
+ {
7047
+ action: "Try the navigation again",
7048
+ confidence: 0.7,
7049
+ priority: 1
7050
+ },
7051
+ {
7052
+ action: "Check if the URL is correct",
7053
+ confidence: 0.6,
7054
+ priority: 2
7055
+ }
7056
+ ]
7057
+ };
7058
+ function createErrorContext(errorCode, attemptedAction, availableElements, searchCriteria, nearestMatch) {
7059
+ const message = ERROR_MESSAGES[errorCode] || "An unknown error occurred";
7060
+ const baseSuggestions = ERROR_SUGGESTIONS[errorCode] || [];
7061
+ const possibleBlockers = detectPossibleBlockers(availableElements);
7062
+ const visibleElements = availableElements.filter((el) => {
7063
+ const state = getElementState5(el);
7064
+ return state?.visible ?? false;
7065
+ }).length;
7066
+ const suggestions = enhanceSuggestions(
7067
+ baseSuggestions,
7068
+ errorCode,
7069
+ nearestMatch,
7070
+ possibleBlockers
7071
+ );
7072
+ return {
7073
+ code: errorCode,
7074
+ message,
7075
+ attemptedAction,
7076
+ searchCriteria,
7077
+ searchResults: {
7078
+ candidatesFound: availableElements.length,
7079
+ nearestMatch: nearestMatch ? {
7080
+ element: nearestMatch.element,
7081
+ confidence: nearestMatch.confidence,
7082
+ whyNotSelected: determineWhyNotSelected(errorCode, nearestMatch)
7083
+ } : void 0
7084
+ },
7085
+ pageContext: {
7086
+ url: typeof window !== "undefined" ? window.location.href : "",
7087
+ title: typeof document !== "undefined" ? document.title : "",
7088
+ visibleElements,
7089
+ possibleBlockers
7090
+ },
7091
+ suggestions,
7092
+ timestamp: Date.now()
7093
+ };
7094
+ }
7095
+ function detectPossibleBlockers(elements) {
7096
+ const blockers = [];
7097
+ for (const el of elements) {
7098
+ const state = getElementState5(el);
7099
+ if (!state) continue;
7100
+ if (el.type === "dialog" && state.visible) {
7101
+ blockers.push(`Modal dialog: ${el.id}`);
7102
+ }
7103
+ if (state.computedStyles?.pointerEvents === "none") {
7104
+ continue;
7105
+ }
7106
+ }
7107
+ return blockers;
7108
+ }
7109
+ function enhanceSuggestions(baseSuggestions, errorCode, nearestMatch, possibleBlockers) {
7110
+ const suggestions = [...baseSuggestions];
7111
+ if (possibleBlockers && possibleBlockers.length > 0) {
7112
+ suggestions.unshift({
7113
+ action: `Close the blocking element: ${possibleBlockers[0]}`,
7114
+ command: "click close button",
7115
+ confidence: 0.85,
7116
+ priority: 0
7117
+ });
7118
+ }
7119
+ if (nearestMatch && errorCode === "LOW_CONFIDENCE") {
7120
+ suggestions.unshift({
7121
+ action: `Did you mean: "${nearestMatch.element.description}"?`,
7122
+ command: `click "${nearestMatch.element.description}"`,
7123
+ confidence: nearestMatch.confidence,
7124
+ priority: 0
7125
+ });
7126
+ }
7127
+ suggestions.sort((a, b) => a.priority - b.priority);
7128
+ return suggestions;
7129
+ }
7130
+ function determineWhyNotSelected(errorCode, nearestMatch) {
7131
+ switch (errorCode) {
7132
+ case "LOW_CONFIDENCE":
7133
+ return `Confidence (${(nearestMatch.confidence * 100).toFixed(0)}%) below threshold`;
7134
+ case "ELEMENT_NOT_VISIBLE":
7135
+ return "Element is not visible";
7136
+ case "ELEMENT_DISABLED":
7137
+ return "Element is disabled";
7138
+ case "AMBIGUOUS_MATCH":
7139
+ return "Multiple elements with similar confidence";
7140
+ default:
7141
+ return "Did not meet selection criteria";
7142
+ }
7143
+ }
7144
+ function formatErrorContext(context) {
7145
+ const lines = [];
7146
+ lines.push(`Error: ${context.code}`);
7147
+ lines.push(`Message: ${context.message}`);
7148
+ lines.push(`Attempted: ${context.attemptedAction}`);
7149
+ lines.push("");
7150
+ if (context.searchResults.nearestMatch) {
7151
+ const match = context.searchResults.nearestMatch;
7152
+ lines.push(`Nearest match: "${match.element.description}" (${(match.confidence * 100).toFixed(0)}% confidence)`);
7153
+ lines.push(`Why not used: ${match.whyNotSelected}`);
7154
+ lines.push("");
7155
+ }
7156
+ lines.push(`Page: ${context.pageContext.title || context.pageContext.url}`);
7157
+ lines.push(`Visible elements: ${context.pageContext.visibleElements}`);
7158
+ if (context.pageContext.possibleBlockers.length > 0) {
7159
+ lines.push(`Possible blockers: ${context.pageContext.possibleBlockers.join(", ")}`);
7160
+ }
7161
+ lines.push("");
7162
+ lines.push("Suggestions:");
7163
+ for (const suggestion of context.suggestions.slice(0, 3)) {
7164
+ lines.push(` - ${suggestion.action}`);
7165
+ if (suggestion.command) {
7166
+ lines.push(` Command: ${suggestion.command}`);
7167
+ }
7168
+ }
7169
+ return lines.join("\n");
7170
+ }
7171
+ function createSimpleError(code, message) {
7172
+ return {
7173
+ code,
7174
+ message: message || ERROR_MESSAGES[code] || "Unknown error"
7175
+ };
7176
+ }
7177
+ function isRecoverableError(code) {
7178
+ const unrecoverableErrors = [
7179
+ "UNSUPPORTED_ACTION",
7180
+ "PAGE_LOAD_ERROR",
7181
+ "NAVIGATION_ERROR"
7182
+ ];
7183
+ return !unrecoverableErrors.includes(code);
7184
+ }
7185
+ function getBestRecoverySuggestion(context) {
7186
+ if (context.suggestions.length === 0) return null;
7187
+ const sorted = [...context.suggestions].sort((a, b) => b.confidence - a.confidence);
7188
+ return sorted[0];
7189
+ }
7190
+
7191
+ // src/ai/nl-action-executor.ts
7192
+ var DEFAULT_EXECUTOR_CONFIG = {
7193
+ defaultConfidenceThreshold: 0.7,
7194
+ defaultTimeout: 5e3,
7195
+ maxAlternatives: 3,
7196
+ verbose: false
7197
+ };
7198
+ var NLActionExecutor = class {
7199
+ constructor(config = {}) {
7200
+ this.actionExecutor = null;
7201
+ this.elements = [];
7202
+ this.config = { ...DEFAULT_EXECUTOR_CONFIG, ...config };
7203
+ this.searchEngine = new SearchEngine(this.config.searchConfig);
7204
+ }
7205
+ /**
7206
+ * Set the action executor for performing DOM actions
7207
+ */
7208
+ setActionExecutor(executor) {
7209
+ this.actionExecutor = executor;
7210
+ }
7211
+ /**
7212
+ * Update available elements for search
7213
+ */
7214
+ updateElements(elements) {
7215
+ this.elements = elements;
7216
+ this.searchEngine.updateElements(elements);
7217
+ }
7218
+ /**
7219
+ * Execute a natural language instruction
7220
+ */
7221
+ async execute(request) {
7222
+ const startTime = performance.now();
7223
+ const threshold = request.confidenceThreshold ?? this.config.defaultConfidenceThreshold;
7224
+ const parsed = parseNLInstruction(request.instruction);
7225
+ if (!parsed) {
7226
+ return this.createFailureResponse(
7227
+ startTime,
7228
+ "PARSE_ERROR",
7229
+ `Could not parse instruction: "${request.instruction}"`,
7230
+ request.instruction,
7231
+ [],
7232
+ threshold
7233
+ );
7234
+ }
7235
+ const validation = validateParsedAction(parsed);
7236
+ if (!validation.valid) {
7237
+ return this.createFailureResponse(
7238
+ startTime,
7239
+ "VALIDATION_ERROR",
7240
+ validation.errors.join("; "),
7241
+ request.instruction,
7242
+ [],
7243
+ threshold
7244
+ );
7245
+ }
7246
+ const searchCriteria = this.buildSearchCriteria(parsed);
7247
+ const searchResponse = this.searchEngine.search(searchCriteria);
7248
+ if (!searchResponse.bestMatch) {
7249
+ return this.createFailureResponse(
7250
+ startTime,
7251
+ "ELEMENT_NOT_FOUND",
7252
+ `Could not find element matching: "${parsed.targetDescription}"`,
7253
+ request.instruction,
7254
+ searchResponse.results,
7255
+ threshold,
7256
+ searchCriteria
7257
+ );
7258
+ }
7259
+ if (searchResponse.bestMatch.confidence < threshold) {
7260
+ const alternatives = searchResponse.results.slice(0, this.config.maxAlternatives);
7261
+ return this.createFailureResponse(
7262
+ startTime,
7263
+ "LOW_CONFIDENCE",
7264
+ `Best match confidence (${(searchResponse.bestMatch.confidence * 100).toFixed(0)}%) is below threshold (${(threshold * 100).toFixed(0)}%)`,
7265
+ request.instruction,
7266
+ alternatives,
7267
+ threshold,
7268
+ searchCriteria,
7269
+ searchResponse.bestMatch
7270
+ );
7271
+ }
7272
+ try {
7273
+ const result = await this.performAction(
7274
+ parsed,
7275
+ searchResponse.bestMatch.element,
7276
+ request.timeout ?? this.config.defaultTimeout
7277
+ );
7278
+ return {
7279
+ success: true,
7280
+ executedAction: describeAction(parsed),
7281
+ elementUsed: searchResponse.bestMatch.element,
7282
+ confidence: searchResponse.bestMatch.confidence,
7283
+ elementState: result.elementState,
7284
+ durationMs: performance.now() - startTime,
7285
+ timestamp: Date.now()
7286
+ };
7287
+ } catch (error) {
7288
+ const errorMessage = error instanceof Error ? error.message : String(error);
7289
+ const alternatives = searchResponse.results.filter((r) => r !== searchResponse.bestMatch).slice(0, this.config.maxAlternatives);
7290
+ return this.createFailureResponse(
7291
+ startTime,
7292
+ "ACTION_FAILED",
7293
+ errorMessage,
7294
+ request.instruction,
7295
+ alternatives,
7296
+ threshold,
7297
+ searchCriteria,
7298
+ searchResponse.bestMatch
7299
+ );
7300
+ }
7301
+ }
7302
+ /**
7303
+ * Execute a parsed action directly (skip parsing)
7304
+ */
7305
+ async executeParsed(parsed, threshold) {
7306
+ const startTime = performance.now();
7307
+ const confidenceThreshold = threshold ?? this.config.defaultConfidenceThreshold;
7308
+ const searchCriteria = this.buildSearchCriteria(parsed);
7309
+ const searchResponse = this.searchEngine.search(searchCriteria);
7310
+ if (!searchResponse.bestMatch) {
7311
+ return this.createFailureResponse(
7312
+ startTime,
7313
+ "ELEMENT_NOT_FOUND",
7314
+ `Could not find element: "${parsed.targetDescription}"`,
7315
+ parsed.rawInstruction,
7316
+ [],
7317
+ confidenceThreshold,
7318
+ searchCriteria
7319
+ );
7320
+ }
7321
+ if (searchResponse.bestMatch.confidence < confidenceThreshold) {
7322
+ return this.createFailureResponse(
7323
+ startTime,
7324
+ "LOW_CONFIDENCE",
7325
+ `Best match confidence too low`,
7326
+ parsed.rawInstruction,
7327
+ searchResponse.results.slice(0, this.config.maxAlternatives),
7328
+ confidenceThreshold,
7329
+ searchCriteria,
7330
+ searchResponse.bestMatch
7331
+ );
7332
+ }
7333
+ try {
7334
+ const result = await this.performAction(
7335
+ parsed,
7336
+ searchResponse.bestMatch.element,
7337
+ this.config.defaultTimeout
7338
+ );
7339
+ return {
7340
+ success: true,
7341
+ executedAction: describeAction(parsed),
7342
+ elementUsed: searchResponse.bestMatch.element,
7343
+ confidence: searchResponse.bestMatch.confidence,
7344
+ elementState: result.elementState,
7345
+ durationMs: performance.now() - startTime,
7346
+ timestamp: Date.now()
7347
+ };
7348
+ } catch (error) {
7349
+ return this.createFailureResponse(
7350
+ startTime,
7351
+ "ACTION_FAILED",
7352
+ error instanceof Error ? error.message : String(error),
7353
+ parsed.rawInstruction,
7354
+ searchResponse.results.filter((r) => r !== searchResponse.bestMatch).slice(0, this.config.maxAlternatives),
7355
+ confidenceThreshold,
7356
+ searchCriteria,
7357
+ searchResponse.bestMatch
7358
+ );
7359
+ }
7360
+ }
7361
+ /**
7362
+ * Build search criteria from a parsed action
7363
+ */
7364
+ buildSearchCriteria(parsed) {
7365
+ const criteria = {
7366
+ text: parsed.targetDescription,
7367
+ fuzzy: true,
7368
+ fuzzyThreshold: this.config.defaultConfidenceThreshold
7369
+ };
7370
+ switch (parsed.action) {
7371
+ case "click":
7372
+ case "doubleClick":
7373
+ case "rightClick":
7374
+ break;
7375
+ case "type":
7376
+ case "clear":
7377
+ criteria.type = "input";
7378
+ break;
7379
+ case "select":
7380
+ criteria.type = "select";
7381
+ break;
7382
+ case "check":
7383
+ case "uncheck":
7384
+ criteria.type = "checkbox";
7385
+ break;
7386
+ }
7387
+ return criteria;
7388
+ }
7389
+ /**
7390
+ * Perform the actual action on an element
7391
+ */
7392
+ async performAction(parsed, element, timeout) {
7393
+ if (!this.actionExecutor) {
7394
+ throw new Error("No action executor configured");
7395
+ }
7396
+ const actionMap = {
7397
+ click: "click",
7398
+ doubleClick: "doubleClick",
7399
+ rightClick: "rightClick",
7400
+ type: "type",
7401
+ select: "select",
7402
+ check: "check",
7403
+ uncheck: "uncheck",
7404
+ scroll: "scroll",
7405
+ wait: null,
7406
+ // Special handling
7407
+ assert: null,
7408
+ // Special handling
7409
+ hover: "hover",
7410
+ focus: "focus",
7411
+ clear: "clear"
7412
+ };
7413
+ const standardAction = actionMap[parsed.action];
7414
+ if (!standardAction) {
7415
+ if (parsed.action === "wait") {
7416
+ const waitResult = await this.actionExecutor.waitFor(element.id, {
7417
+ visible: true,
7418
+ timeout
7419
+ });
7420
+ if (!waitResult.met) {
7421
+ throw new Error(waitResult.error || "Wait condition not met");
7422
+ }
7423
+ return { elementState: waitResult.state };
7424
+ }
7425
+ if (parsed.action === "assert") {
7426
+ throw new Error("Use the assertions module for assert actions");
7427
+ }
7428
+ throw new Error(`Unsupported action: ${parsed.action}`);
7429
+ }
7430
+ const actionRequest = {
7431
+ action: standardAction,
7432
+ waitOptions: {
7433
+ visible: true,
7434
+ enabled: true,
7435
+ timeout
7436
+ }
7437
+ };
7438
+ if (standardAction === "type" && parsed.value) {
7439
+ actionRequest.params = { text: parsed.value };
7440
+ } else if (standardAction === "select" && parsed.value) {
7441
+ actionRequest.params = { value: parsed.value };
7442
+ } else if (standardAction === "scroll" && parsed.scrollDirection) {
7443
+ actionRequest.params = { direction: parsed.scrollDirection };
7444
+ }
7445
+ const response = await this.actionExecutor.executeAction(element.id, actionRequest);
7446
+ if (!response.success) {
7447
+ throw new Error(response.error || "Action failed");
7448
+ }
7449
+ return { elementState: response.elementState };
7450
+ }
7451
+ /**
7452
+ * Create a failure response with suggestions
7453
+ */
7454
+ createFailureResponse(startTime, errorCode, errorMessage, instruction, alternatives, threshold, searchCriteria, nearestMatch) {
7455
+ const suggestions = this.generateSuggestions(
7456
+ errorCode,
7457
+ instruction,
7458
+ alternatives,
7459
+ nearestMatch
7460
+ );
7461
+ const dummyElement = nearestMatch?.element || {
7462
+ id: "not-found",
7463
+ type: "unknown",
7464
+ tagName: "unknown",
7465
+ actions: [],
7466
+ state: {
7467
+ visible: false,
7468
+ enabled: false,
7469
+ focused: false,
7470
+ rect: { x: 0, y: 0, width: 0, height: 0, top: 0, right: 0, bottom: 0, left: 0 }
7471
+ },
7472
+ registered: false,
7473
+ description: "Element not found",
7474
+ aliases: [],
7475
+ suggestedActions: []
7476
+ };
7477
+ return {
7478
+ success: false,
7479
+ executedAction: instruction,
7480
+ elementUsed: dummyElement,
7481
+ confidence: nearestMatch?.confidence || 0,
7482
+ elementState: dummyElement.state,
7483
+ durationMs: performance.now() - startTime,
7484
+ timestamp: Date.now(),
7485
+ error: errorMessage,
7486
+ errorCode,
7487
+ suggestions,
7488
+ alternatives: alternatives.slice(0, this.config.maxAlternatives)
7489
+ };
7490
+ }
7491
+ /**
7492
+ * Generate recovery suggestions
7493
+ */
7494
+ generateSuggestions(errorCode, instruction, alternatives, nearestMatch) {
7495
+ const suggestions = [];
7496
+ switch (errorCode) {
7497
+ case "PARSE_ERROR":
7498
+ suggestions.push('Try using a simpler phrase like "click Submit button"');
7499
+ suggestions.push('Ensure the instruction follows patterns like "click X" or "type Y into X"');
7500
+ break;
7501
+ case "ELEMENT_NOT_FOUND":
7502
+ if (alternatives.length > 0) {
7503
+ suggestions.push(`Did you mean: "${alternatives[0].element.description}"?`);
7504
+ }
7505
+ suggestions.push("Check if the element is visible on the page");
7506
+ suggestions.push("Try using a more specific description");
7507
+ break;
7508
+ case "LOW_CONFIDENCE":
7509
+ if (nearestMatch) {
7510
+ suggestions.push(
7511
+ `Found "${nearestMatch.element.description}" with ${(nearestMatch.confidence * 100).toFixed(0)}% confidence`
7512
+ );
7513
+ }
7514
+ suggestions.push("Try using the exact text shown on the element");
7515
+ suggestions.push("Lower the confidence threshold if this match is correct");
7516
+ break;
7517
+ case "ACTION_FAILED":
7518
+ suggestions.push("Check if the element is enabled");
7519
+ suggestions.push("Wait for any loading to complete");
7520
+ suggestions.push("Ensure no modal or overlay is blocking the element");
7521
+ break;
7522
+ default:
7523
+ suggestions.push("Try a different approach or check the page state");
7524
+ }
7525
+ return suggestions;
7526
+ }
7527
+ /**
7528
+ * Get rich error context for debugging
7529
+ */
7530
+ getErrorContext(errorCode, instruction, searchCriteria, nearestMatch) {
7531
+ return createErrorContext(
7532
+ errorCode,
7533
+ instruction,
7534
+ this.elements,
7535
+ searchCriteria,
7536
+ nearestMatch
7537
+ );
7538
+ }
7539
+ };
7540
+ function createNLActionExecutor(config) {
7541
+ return new NLActionExecutor(config);
7542
+ }
7543
+
7544
+ // src/ai/assertions.ts
7545
+ var DEFAULT_ASSERTION_CONFIG = {
7546
+ defaultTimeout: 5e3,
7547
+ pollInterval: 100,
7548
+ fuzzyThreshold: 0.7,
7549
+ includeSuggestions: true
7550
+ };
7551
+ var AssertionExecutor = class {
7552
+ constructor(config = {}) {
7553
+ this.elements = [];
7554
+ this.config = { ...DEFAULT_ASSERTION_CONFIG, ...config };
7555
+ this.searchEngine = new SearchEngine({ fuzzyThreshold: this.config.fuzzyThreshold });
7556
+ }
7557
+ /**
7558
+ * Update available elements for assertions
7559
+ */
7560
+ updateElements(elements) {
7561
+ this.elements = elements;
7562
+ this.searchEngine.updateElements(elements);
7563
+ }
7564
+ /**
7565
+ * Execute a single assertion
7566
+ */
7567
+ async assert(request) {
7568
+ const startTime = performance.now();
7569
+ const timeout = request.timeout ?? this.config.defaultTimeout;
7570
+ const element = await this.findElement(request.target, request.fuzzy !== false);
7571
+ if (!element && request.type !== "notExists") {
7572
+ return this.createResult(
7573
+ false,
7574
+ typeof request.target === "string" ? request.target : JSON.stringify(request.target),
7575
+ "element not found",
7576
+ request.type === "exists" ? true : request.expected,
7577
+ null,
7578
+ "Element could not be found",
7579
+ this.config.includeSuggestions ? "Check if the element exists and is properly labeled" : void 0,
7580
+ startTime
7581
+ );
7582
+ }
7583
+ return this.executeAssertion(request, element, timeout, startTime);
7584
+ }
7585
+ /**
7586
+ * Execute multiple assertions
7587
+ */
7588
+ async assertBatch(request) {
7589
+ const startTime = performance.now();
7590
+ const results = [];
7591
+ let passedCount = 0;
7592
+ let failedCount = 0;
7593
+ for (const assertion of request.assertions) {
7594
+ const result = await this.assert(assertion);
7595
+ results.push(result);
7596
+ if (result.passed) {
7597
+ passedCount++;
7598
+ } else {
7599
+ failedCount++;
7600
+ if (request.stopOnFailure) {
7601
+ break;
7602
+ }
7603
+ }
7604
+ }
7605
+ const passed = request.mode === "all" ? failedCount === 0 : passedCount > 0;
7606
+ return {
7607
+ passed,
7608
+ results,
7609
+ passedCount,
7610
+ failedCount,
7611
+ durationMs: performance.now() - startTime,
7612
+ timestamp: Date.now()
7613
+ };
7614
+ }
7615
+ /**
7616
+ * Convenience method: assert element is visible
7617
+ */
7618
+ async assertVisible(target, timeout) {
7619
+ return this.assert({ target, type: "visible", timeout });
7620
+ }
7621
+ /**
7622
+ * Convenience method: assert element is hidden
7623
+ */
7624
+ async assertHidden(target, timeout) {
7625
+ return this.assert({ target, type: "hidden", timeout });
7626
+ }
7627
+ /**
7628
+ * Convenience method: assert element is enabled
7629
+ */
7630
+ async assertEnabled(target, timeout) {
7631
+ return this.assert({ target, type: "enabled", timeout });
7632
+ }
7633
+ /**
7634
+ * Convenience method: assert element is disabled
7635
+ */
7636
+ async assertDisabled(target, timeout) {
7637
+ return this.assert({ target, type: "disabled", timeout });
7638
+ }
7639
+ /**
7640
+ * Convenience method: assert element has text
7641
+ */
7642
+ async assertHasText(target, text, timeout) {
7643
+ return this.assert({ target, type: "hasText", expected: text, timeout });
7644
+ }
7645
+ /**
7646
+ * Convenience method: assert element contains text
7647
+ */
7648
+ async assertContainsText(target, text, timeout) {
7649
+ return this.assert({ target, type: "containsText", expected: text, timeout });
7650
+ }
7651
+ /**
7652
+ * Convenience method: assert element has value
7653
+ */
7654
+ async assertHasValue(target, value, timeout) {
7655
+ return this.assert({ target, type: "hasValue", expected: value, timeout });
7656
+ }
7657
+ /**
7658
+ * Convenience method: assert element exists
7659
+ */
7660
+ async assertExists(target, timeout) {
7661
+ return this.assert({ target, type: "exists", timeout });
7662
+ }
7663
+ /**
7664
+ * Convenience method: assert element does not exist
7665
+ */
7666
+ async assertNotExists(target, timeout) {
7667
+ return this.assert({ target, type: "notExists", timeout });
7668
+ }
7669
+ /**
7670
+ * Convenience method: assert checkbox is checked
7671
+ */
7672
+ async assertChecked(target, timeout) {
7673
+ return this.assert({ target, type: "checked", timeout });
7674
+ }
7675
+ /**
7676
+ * Convenience method: assert checkbox is unchecked
7677
+ */
7678
+ async assertUnchecked(target, timeout) {
7679
+ return this.assert({ target, type: "unchecked", timeout });
7680
+ }
7681
+ /**
7682
+ * Convenience method: assert element count
7683
+ */
7684
+ async assertCount(target, expectedCount, timeout) {
7685
+ return this.assert({ target, type: "count", expected: expectedCount, timeout });
7686
+ }
7687
+ /**
7688
+ * Find element by target (string or criteria)
7689
+ */
7690
+ async findElement(target, fuzzy = true) {
7691
+ const criteria = typeof target === "string" ? { text: target, fuzzy } : { ...target, fuzzy };
7692
+ const searchResult = this.searchEngine.findBest(criteria);
7693
+ if (searchResult && searchResult.confidence >= this.config.fuzzyThreshold) {
7694
+ return searchResult.element;
7695
+ }
7696
+ return null;
7697
+ }
7698
+ /**
7699
+ * Execute the actual assertion
7700
+ */
7701
+ async executeAssertion(request, element, timeout, startTime) {
7702
+ const targetStr = typeof request.target === "string" ? request.target : JSON.stringify(request.target);
7703
+ const elementDescription = element?.description || targetStr;
7704
+ switch (request.type) {
7705
+ case "visible":
7706
+ return this.assertVisibility(element, true, elementDescription, request.message, startTime);
7707
+ case "hidden":
7708
+ return this.assertVisibility(element, false, elementDescription, request.message, startTime);
7709
+ case "enabled":
7710
+ return this.assertEnabledState(element, true, elementDescription, request.message, startTime);
7711
+ case "disabled":
7712
+ return this.assertEnabledState(element, false, elementDescription, request.message, startTime);
7713
+ case "focused":
7714
+ return this.assertFocused(element, elementDescription, request.message, startTime);
7715
+ case "checked":
7716
+ return this.assertCheckedState(element, true, elementDescription, request.message, startTime);
7717
+ case "unchecked":
7718
+ return this.assertCheckedState(element, false, elementDescription, request.message, startTime);
7719
+ case "hasText":
7720
+ return this.assertTextMatch(
7721
+ element,
7722
+ request.expected,
7723
+ true,
7724
+ elementDescription,
7725
+ request.message,
7726
+ startTime
7727
+ );
7728
+ case "containsText":
7729
+ return this.assertTextMatch(
7730
+ element,
7731
+ request.expected,
7732
+ false,
7733
+ elementDescription,
7734
+ request.message,
7735
+ startTime
7736
+ );
7737
+ case "hasValue":
7738
+ return this.assertValue(
7739
+ element,
7740
+ request.expected,
7741
+ elementDescription,
7742
+ request.message,
7743
+ startTime
7744
+ );
7745
+ case "exists":
7746
+ return this.createResult(
7747
+ element !== null,
7748
+ targetStr,
7749
+ elementDescription,
7750
+ true,
7751
+ element !== null,
7752
+ element === null ? "Element does not exist" : void 0,
7753
+ void 0,
7754
+ startTime,
7755
+ element?.state
7756
+ );
7757
+ case "notExists":
7758
+ return this.createResult(
7759
+ element === null,
7760
+ targetStr,
7761
+ elementDescription,
7762
+ false,
7763
+ element === null,
7764
+ element !== null ? "Element exists but should not" : void 0,
7765
+ void 0,
7766
+ startTime,
7767
+ element?.state
7768
+ );
7769
+ case "count":
7770
+ return this.assertElementCount(
7771
+ request.target,
7772
+ request.expected,
7773
+ targetStr,
7774
+ request.message,
7775
+ startTime
7776
+ );
7777
+ case "attribute":
7778
+ return this.assertAttribute(
7779
+ element,
7780
+ request.attributeName,
7781
+ request.expected,
7782
+ elementDescription,
7783
+ request.message,
7784
+ startTime
7785
+ );
7786
+ case "hasClass":
7787
+ return this.assertHasClass(
7788
+ element,
7789
+ request.expected,
7790
+ elementDescription,
7791
+ request.message,
7792
+ startTime
7793
+ );
7794
+ case "cssProperty":
7795
+ return this.assertCssProperty(
7796
+ element,
7797
+ request.propertyName,
7798
+ request.expected,
7799
+ elementDescription,
7800
+ request.message,
7801
+ startTime
7802
+ );
7803
+ default:
7804
+ return this.createResult(
7805
+ false,
7806
+ targetStr,
7807
+ elementDescription,
7808
+ void 0,
7809
+ void 0,
7810
+ `Unknown assertion type: ${request.type}`,
7811
+ void 0,
7812
+ startTime
7813
+ );
7814
+ }
7815
+ }
7816
+ /**
7817
+ * Assert visibility state
7818
+ */
7819
+ assertVisibility(element, expectedVisible, description, message, startTime = performance.now()) {
7820
+ const isVisible3 = element.state.visible;
7821
+ const passed = isVisible3 === expectedVisible;
7822
+ return this.createResult(
7823
+ passed,
7824
+ element.id,
7825
+ description,
7826
+ expectedVisible,
7827
+ isVisible3,
7828
+ passed ? void 0 : message || `Element is ${isVisible3 ? "visible" : "hidden"} but expected ${expectedVisible ? "visible" : "hidden"}`,
7829
+ passed ? void 0 : "Check if element is covered by another element or has display:none",
7830
+ startTime,
7831
+ element.state
7832
+ );
7833
+ }
7834
+ /**
7835
+ * Assert enabled state
7836
+ */
7837
+ assertEnabledState(element, expectedEnabled, description, message, startTime = performance.now()) {
7838
+ const isEnabled = element.state.enabled;
7839
+ const passed = isEnabled === expectedEnabled;
7840
+ return this.createResult(
7841
+ passed,
7842
+ element.id,
7843
+ description,
7844
+ expectedEnabled,
7845
+ isEnabled,
7846
+ passed ? void 0 : message || `Element is ${isEnabled ? "enabled" : "disabled"} but expected ${expectedEnabled ? "enabled" : "disabled"}`,
7847
+ passed ? void 0 : "Check if the element has a disabled attribute or aria-disabled",
7848
+ startTime,
7849
+ element.state
7850
+ );
7851
+ }
7852
+ /**
7853
+ * Assert focused state
7854
+ */
7855
+ assertFocused(element, description, message, startTime = performance.now()) {
7856
+ const isFocused = element.state.focused;
7857
+ return this.createResult(
7858
+ isFocused,
7859
+ element.id,
7860
+ description,
7861
+ true,
7862
+ isFocused,
7863
+ isFocused ? void 0 : message || "Element is not focused",
7864
+ isFocused ? void 0 : "Click or focus the element first",
7865
+ startTime,
7866
+ element.state
7867
+ );
7868
+ }
7869
+ /**
7870
+ * Assert checked state
7871
+ */
7872
+ assertCheckedState(element, expectedChecked, description, message, startTime = performance.now()) {
7873
+ const isChecked = element.state.checked ?? false;
7874
+ const passed = isChecked === expectedChecked;
7875
+ return this.createResult(
7876
+ passed,
7877
+ element.id,
7878
+ description,
7879
+ expectedChecked,
7880
+ isChecked,
7881
+ passed ? void 0 : message || `Element is ${isChecked ? "checked" : "unchecked"} but expected ${expectedChecked ? "checked" : "unchecked"}`,
7882
+ passed ? void 0 : "Click the checkbox to change its state",
7883
+ startTime,
7884
+ element.state
7885
+ );
7886
+ }
7887
+ /**
7888
+ * Assert text content
7889
+ */
7890
+ assertTextMatch(element, expectedText, exact, description, message, startTime = performance.now()) {
7891
+ const actualText = element.state.textContent || "";
7892
+ const passed = exact ? actualText === expectedText : actualText.includes(expectedText);
7893
+ return this.createResult(
7894
+ passed,
7895
+ element.id,
7896
+ description,
7897
+ expectedText,
7898
+ actualText,
7899
+ passed ? void 0 : message || (exact ? `Text "${actualText}" does not match expected "${expectedText}"` : `Text "${actualText}" does not contain "${expectedText}"`),
7900
+ passed ? void 0 : "Verify the element contains the expected text",
7901
+ startTime,
7902
+ element.state
7903
+ );
7904
+ }
7905
+ /**
7906
+ * Assert input value
7907
+ */
7908
+ assertValue(element, expectedValue, description, message, startTime = performance.now()) {
7909
+ const actualValue = element.state.value || "";
7910
+ const passed = actualValue === expectedValue;
7911
+ return this.createResult(
7912
+ passed,
7913
+ element.id,
7914
+ description,
7915
+ expectedValue,
7916
+ actualValue,
7917
+ passed ? void 0 : message || `Value "${actualValue}" does not match expected "${expectedValue}"`,
7918
+ passed ? void 0 : "Type the expected value into the input",
7919
+ startTime,
7920
+ element.state
7921
+ );
7922
+ }
7923
+ /**
7924
+ * Assert element count
7925
+ */
7926
+ assertElementCount(criteria, expectedCount, targetStr, message, startTime = performance.now()) {
7927
+ const searchResponse = this.searchEngine.search(criteria);
7928
+ const actualCount = searchResponse.results.length;
7929
+ const passed = actualCount === expectedCount;
7930
+ return this.createResult(
7931
+ passed,
7932
+ targetStr,
7933
+ `${actualCount} elements matching criteria`,
7934
+ expectedCount,
7935
+ actualCount,
7936
+ passed ? void 0 : message || `Found ${actualCount} elements but expected ${expectedCount}`,
7937
+ passed ? void 0 : "Adjust search criteria or wait for elements to load",
7938
+ startTime
7939
+ );
7940
+ }
7941
+ /**
7942
+ * Assert attribute value (placeholder for DOM attribute assertions)
7943
+ */
7944
+ assertAttribute(element, attributeName, expectedValue, description, message, startTime = performance.now()) {
7945
+ let actualValue;
7946
+ switch (attributeName.toLowerCase()) {
7947
+ case "placeholder":
7948
+ actualValue = element.placeholder;
7949
+ break;
7950
+ case "title":
7951
+ actualValue = element.title;
7952
+ break;
7953
+ default:
7954
+ return this.createResult(
7955
+ false,
7956
+ element.id,
7957
+ description,
7958
+ expectedValue,
7959
+ void 0,
7960
+ `Cannot check attribute "${attributeName}" without DOM access`,
7961
+ "Use the server API to check element attributes",
7962
+ startTime,
7963
+ element.state
7964
+ );
7965
+ }
7966
+ const passed = actualValue === expectedValue;
7967
+ return this.createResult(
7968
+ passed,
7969
+ element.id,
7970
+ description,
7971
+ expectedValue,
7972
+ actualValue,
7973
+ passed ? void 0 : message || `Attribute "${attributeName}" is "${actualValue}" but expected "${expectedValue}"`,
7974
+ void 0,
7975
+ startTime,
7976
+ element.state
7977
+ );
7978
+ }
7979
+ /**
7980
+ * Assert element has CSS class
7981
+ */
7982
+ assertHasClass(element, className, description, message, startTime = performance.now()) {
7983
+ return this.createResult(
7984
+ false,
7985
+ element.id,
7986
+ description,
7987
+ className,
7988
+ void 0,
7989
+ "Cannot check CSS classes without DOM access",
7990
+ "Use the server API to check element classes",
7991
+ startTime,
7992
+ element.state
7993
+ );
7994
+ }
7995
+ /**
7996
+ * Assert CSS property value
7997
+ */
7998
+ assertCssProperty(element, propertyName, expectedValue, description, message, startTime = performance.now()) {
7999
+ const computedStyles = element.state.computedStyles;
8000
+ if (!computedStyles) {
8001
+ return this.createResult(
8002
+ false,
8003
+ element.id,
8004
+ description,
8005
+ expectedValue,
8006
+ void 0,
8007
+ "Computed styles not available",
8008
+ "Request element state with computed styles",
8009
+ startTime,
8010
+ element.state
8011
+ );
8012
+ }
8013
+ const styleKey = propertyName;
8014
+ const actualValue = computedStyles[styleKey];
8015
+ const passed = actualValue === expectedValue;
8016
+ return this.createResult(
8017
+ passed,
8018
+ element.id,
8019
+ description,
8020
+ expectedValue,
8021
+ actualValue,
8022
+ passed ? void 0 : message || `CSS property "${propertyName}" is "${actualValue}" but expected "${expectedValue}"`,
8023
+ void 0,
8024
+ startTime,
8025
+ element.state
8026
+ );
8027
+ }
8028
+ /**
8029
+ * Create an assertion result
8030
+ */
8031
+ createResult(passed, target, targetDescription, expected, actual, failureReason, suggestion, startTime = performance.now(), elementState) {
8032
+ return {
8033
+ passed,
8034
+ target,
8035
+ targetDescription,
8036
+ expected,
8037
+ actual,
8038
+ failureReason,
8039
+ suggestion: this.config.includeSuggestions ? suggestion : void 0,
8040
+ elementState,
8041
+ durationMs: performance.now() - startTime,
8042
+ timestamp: Date.now()
8043
+ };
8044
+ }
8045
+ };
8046
+ function createAssertionExecutor(config) {
8047
+ return new AssertionExecutor(config);
8048
+ }
8049
+
8050
+ // src/ai/semantic-snapshot.ts
8051
+ var DEFAULT_SNAPSHOT_CONFIG = {
8052
+ analyzeForms: true,
8053
+ detectModals: true,
8054
+ inferPageType: true,
8055
+ generateDescriptions: true,
8056
+ maxElements: 500
8057
+ };
8058
+ var SemanticSnapshotManager = class {
8059
+ constructor(config = {}) {
8060
+ this.history = [];
8061
+ this.maxHistorySize = 10;
8062
+ this.snapshotCounter = 0;
8063
+ this.config = { ...DEFAULT_SNAPSHOT_CONFIG, ...config };
8064
+ this.searchEngine = new SearchEngine();
8065
+ }
8066
+ /**
8067
+ * Create a semantic snapshot from a control snapshot
8068
+ */
8069
+ createSnapshot(controlSnapshot, pageContext) {
8070
+ const snapshotId = `snapshot-${++this.snapshotCounter}-${Date.now()}`;
8071
+ const aiElements = this.convertElements(controlSnapshot.elements);
8072
+ this.searchEngine.updateElements(aiElements);
8073
+ const fullPageContext = this.buildPageContext(aiElements, pageContext);
8074
+ const forms = this.config.analyzeForms ? this.analyzeForms(aiElements) : [];
8075
+ const modals = this.config.detectModals ? this.detectModals(aiElements) : [];
8076
+ const elementCounts = this.countElementTypes(aiElements);
8077
+ const summary = generatePageSummary(aiElements, fullPageContext);
8078
+ const focusedElement = aiElements.find((el) => el.state.focused)?.id;
8079
+ const snapshot = {
8080
+ timestamp: Date.now(),
8081
+ snapshotId,
8082
+ page: fullPageContext,
8083
+ elements: aiElements.slice(0, this.config.maxElements),
8084
+ forms,
8085
+ activeModals: modals,
8086
+ focusedElement,
8087
+ summary,
8088
+ elementCounts
8089
+ };
8090
+ this.addToHistory(snapshot);
8091
+ return snapshot;
8092
+ }
8093
+ /**
8094
+ * Get the last snapshot
8095
+ */
8096
+ getLastSnapshot() {
8097
+ if (this.history.length === 0) return null;
8098
+ return this.history[this.history.length - 1].snapshot;
8099
+ }
8100
+ /**
8101
+ * Get snapshot by ID
8102
+ */
8103
+ getSnapshot(snapshotId) {
8104
+ const entry = this.history.find((h) => h.snapshot.snapshotId === snapshotId);
8105
+ return entry?.snapshot || null;
8106
+ }
8107
+ /**
8108
+ * Get snapshot history
8109
+ */
8110
+ getHistory() {
8111
+ return this.history.map((h) => h.snapshot);
8112
+ }
8113
+ /**
8114
+ * Clear history
8115
+ */
8116
+ clearHistory() {
8117
+ this.history = [];
8118
+ }
8119
+ /**
8120
+ * Convert control snapshot elements to AI elements
8121
+ */
8122
+ convertElements(elements) {
8123
+ return elements.map((el) => this.convertElement(el));
8124
+ }
8125
+ /**
8126
+ * Convert a single element to AI element
8127
+ */
8128
+ convertElement(element) {
8129
+ const aliases = generateAliases({
8130
+ textContent: element.state.textContent,
8131
+ elementType: element.type,
8132
+ id: element.id,
8133
+ labelText: element.label
8134
+ });
8135
+ const description = this.config.generateDescriptions ? generateDescription({
8136
+ textContent: element.state.textContent,
8137
+ elementType: element.type,
8138
+ id: element.id,
8139
+ labelText: element.label
8140
+ }) : element.label || element.id;
8141
+ const purpose = generatePurpose({
8142
+ textContent: element.state.textContent,
8143
+ elementType: element.type
8144
+ });
8145
+ const suggestedActions = generateSuggestedActions({
8146
+ textContent: element.state.textContent,
8147
+ elementType: element.type
8148
+ });
8149
+ return {
8150
+ id: element.id,
8151
+ type: element.type,
8152
+ label: element.label,
8153
+ tagName: this.inferTagName(element.type),
8154
+ role: this.inferRole(element.type),
8155
+ accessibleName: element.label || element.state.textContent?.trim(),
8156
+ actions: element.actions,
8157
+ state: element.state,
8158
+ registered: true,
8159
+ description,
8160
+ aliases,
8161
+ purpose,
8162
+ suggestedActions,
8163
+ semanticType: this.inferSemanticType(element)
8164
+ };
8165
+ }
8166
+ /**
8167
+ * Build full page context
8168
+ */
8169
+ buildPageContext(elements, partial) {
8170
+ const url = partial?.url || (typeof window !== "undefined" ? window.location.href : "");
8171
+ const title = partial?.title || (typeof document !== "undefined" ? document.title : "");
8172
+ const pageType = this.config.inferPageType ? inferPageType(url, title, elements) : partial?.pageType || "unknown";
8173
+ const activeModals = elements.filter((el) => el.type === "dialog" && el.state.visible).map((el) => el.id);
8174
+ return {
8175
+ url,
8176
+ title,
8177
+ pageType,
8178
+ activeModals: partial?.activeModals || activeModals,
8179
+ focusedElement: partial?.focusedElement || elements.find((el) => el.state.focused)?.id,
8180
+ navigation: partial?.navigation
8181
+ };
8182
+ }
8183
+ /**
8184
+ * Analyze forms in the snapshot
8185
+ */
8186
+ analyzeForms(elements) {
8187
+ const forms = [];
8188
+ const formElements = elements.filter((el) => el.type === "form");
8189
+ if (formElements.length === 0) {
8190
+ const implicitForm = this.detectImplicitForm(elements);
8191
+ if (implicitForm) {
8192
+ forms.push(implicitForm);
8193
+ }
8194
+ } else {
8195
+ for (const form of formElements) {
8196
+ const formState = this.analyzeForm(form, elements);
8197
+ if (formState) {
8198
+ forms.push(formState);
8199
+ }
8200
+ }
8201
+ }
8202
+ return forms;
8203
+ }
8204
+ /**
8205
+ * Detect implicit form from inputs
8206
+ */
8207
+ detectImplicitForm(elements) {
8208
+ const inputs = elements.filter(
8209
+ (el) => el.type === "input" || el.type === "textarea" || el.type === "select" || el.type === "checkbox"
8210
+ );
8211
+ if (inputs.length === 0) return null;
8212
+ const submitButton = elements.find(
8213
+ (el) => el.type === "button" && el.state.visible && (el.semanticType === "submit-button" || el.state.textContent?.toLowerCase().match(/submit|save|send|continue/))
8214
+ );
8215
+ const fields = this.analyzeFormFields(inputs);
8216
+ const hasErrors = fields.some((f) => !f.valid);
8217
+ return {
8218
+ id: "implicit-form",
8219
+ purpose: this.inferFormPurpose(inputs),
8220
+ fields,
8221
+ isValid: !hasErrors,
8222
+ submitButton: submitButton?.id,
8223
+ isDirty: fields.some((f) => f.value !== "" && f.touched)
8224
+ };
8225
+ }
8226
+ /**
8227
+ * Analyze a specific form
8228
+ */
8229
+ analyzeForm(form, allElements) {
8230
+ const inputs = allElements.filter(
8231
+ (el) => (el.type === "input" || el.type === "textarea" || el.type === "select") && el.state.visible
8232
+ );
8233
+ const fields = this.analyzeFormFields(inputs);
8234
+ const hasErrors = fields.some((f) => !f.valid);
8235
+ const submitButton = allElements.find(
8236
+ (el) => el.type === "button" && el.state.visible && el.semanticType === "submit-button"
8237
+ );
8238
+ return {
8239
+ id: form.id,
8240
+ name: form.label,
8241
+ purpose: form.purpose,
8242
+ fields,
8243
+ isValid: !hasErrors,
8244
+ submitButton: submitButton?.id,
8245
+ isDirty: fields.some((f) => f.value !== "")
8246
+ };
8247
+ }
8248
+ /**
8249
+ * Analyze form fields
8250
+ */
8251
+ analyzeFormFields(inputs) {
8252
+ return inputs.map((input) => ({
8253
+ id: input.id,
8254
+ label: input.accessibleName || input.label || input.id,
8255
+ type: input.type,
8256
+ value: input.state.value || "",
8257
+ valid: true,
8258
+ // Would need validation state
8259
+ required: false,
8260
+ // Would need DOM access
8261
+ touched: input.state.focused || (input.state.value?.length || 0) > 0
8262
+ }));
8263
+ }
8264
+ /**
8265
+ * Detect modal dialogs
8266
+ */
8267
+ detectModals(elements) {
8268
+ const modals = [];
8269
+ const dialogElements = elements.filter(
8270
+ (el) => el.type === "dialog" && el.state.visible
8271
+ );
8272
+ for (const dialog of dialogElements) {
8273
+ const closeButton = elements.find(
8274
+ (el) => el.type === "button" && el.state.visible && (el.semanticType === "cancel-button" || el.state.textContent?.toLowerCase().match(/close|cancel|x|dismiss/))
8275
+ );
8276
+ const primaryAction = elements.find(
8277
+ (el) => el.type === "button" && el.state.visible && el.semanticType === "submit-button"
8278
+ );
8279
+ modals.push({
8280
+ id: dialog.id,
8281
+ title: dialog.accessibleName || dialog.label,
8282
+ type: this.inferModalType(dialog),
8283
+ blocking: true,
8284
+ // Assume dialogs are blocking
8285
+ closeButton: closeButton?.id,
8286
+ primaryAction: primaryAction?.id
8287
+ });
8288
+ }
8289
+ return modals;
8290
+ }
8291
+ /**
8292
+ * Infer modal type
8293
+ */
8294
+ inferModalType(dialog) {
8295
+ const text = (dialog.accessibleName || dialog.state.textContent || "").toLowerCase();
8296
+ if (text.includes("alert") || text.includes("warning") || text.includes("error")) {
8297
+ return "alert";
8298
+ }
8299
+ if (text.includes("confirm") || text.includes("are you sure")) {
8300
+ return "confirm";
8301
+ }
8302
+ if (text.includes("prompt") || text.includes("enter")) {
8303
+ return "prompt";
8304
+ }
8305
+ return "dialog";
8306
+ }
8307
+ /**
8308
+ * Count elements by type
8309
+ */
8310
+ countElementTypes(elements) {
8311
+ const counts = {};
8312
+ for (const el of elements) {
8313
+ const type = el.type.toLowerCase();
8314
+ counts[type] = (counts[type] || 0) + 1;
8315
+ }
8316
+ return counts;
8317
+ }
8318
+ /**
8319
+ * Infer form purpose from fields
8320
+ */
8321
+ inferFormPurpose(fields) {
8322
+ const labels = fields.map(
8323
+ (f) => (f.accessibleName || f.label || "").toLowerCase()
8324
+ );
8325
+ const allLabels = labels.join(" ");
8326
+ if (allLabels.includes("email") && allLabels.includes("password")) {
8327
+ if (allLabels.includes("confirm") || allLabels.includes("name")) {
8328
+ return "Registration";
8329
+ }
8330
+ return "Login";
8331
+ }
8332
+ if (allLabels.includes("search")) return "Search";
8333
+ if (allLabels.includes("address") || allLabels.includes("city")) return "Address";
8334
+ if (allLabels.includes("card") || allLabels.includes("payment")) return "Payment";
8335
+ if (allLabels.includes("contact") || allLabels.includes("message")) return "Contact";
8336
+ return "Form";
8337
+ }
8338
+ /**
8339
+ * Infer tag name from element type
8340
+ */
8341
+ inferTagName(type) {
8342
+ const typeMap = {
8343
+ button: "button",
8344
+ input: "input",
8345
+ textarea: "textarea",
8346
+ select: "select",
8347
+ checkbox: "input",
8348
+ radio: "input",
8349
+ link: "a",
8350
+ form: "form",
8351
+ dialog: "dialog"
8352
+ };
8353
+ return typeMap[type] || "div";
8354
+ }
8355
+ /**
8356
+ * Infer ARIA role from element type
8357
+ */
8358
+ inferRole(type) {
8359
+ const roleMap = {
8360
+ button: "button",
8361
+ input: "textbox",
8362
+ textarea: "textbox",
8363
+ select: "combobox",
8364
+ checkbox: "checkbox",
8365
+ radio: "radio",
8366
+ link: "link",
8367
+ dialog: "dialog",
8368
+ menu: "menu",
8369
+ menuitem: "menuitem",
8370
+ tab: "tab"
8371
+ };
8372
+ return roleMap[type];
8373
+ }
8374
+ /**
8375
+ * Infer semantic type
8376
+ */
8377
+ inferSemanticType(element) {
8378
+ const text = (element.state.textContent || element.label || "").toLowerCase();
8379
+ const type = element.type.toLowerCase();
8380
+ if (type === "button") {
8381
+ if (text.match(/submit|save|confirm|ok|done|apply/)) return "submit-button";
8382
+ if (text.match(/cancel|close|dismiss/)) return "cancel-button";
8383
+ if (text.match(/delete|remove|trash/)) return "delete-button";
8384
+ if (text.match(/add|create|new|\+/)) return "add-button";
8385
+ if (text.match(/edit|modify/)) return "edit-button";
8386
+ if (text.match(/next|continue/)) return "next-button";
8387
+ if (text.match(/back|previous/)) return "back-button";
8388
+ return "action-button";
8389
+ }
8390
+ if (type === "input") {
8391
+ if (text.includes("email") || element.id.includes("email")) return "email-input";
8392
+ if (text.includes("password") || element.id.includes("password")) return "password-input";
8393
+ if (text.includes("search") || element.id.includes("search")) return "search-input";
8394
+ return "text-input";
8395
+ }
8396
+ return type;
8397
+ }
8398
+ /**
8399
+ * Add snapshot to history
8400
+ */
8401
+ addToHistory(snapshot) {
8402
+ this.history.push({
8403
+ snapshot,
8404
+ timestamp: Date.now()
8405
+ });
8406
+ if (this.history.length > this.maxHistorySize) {
8407
+ this.history = this.history.slice(-this.maxHistorySize);
8408
+ }
8409
+ }
8410
+ };
8411
+ function createSnapshotManager(config) {
8412
+ return new SemanticSnapshotManager(config);
8413
+ }
8414
+
8415
+ // src/ai/semantic-diff.ts
8416
+ var DEFAULT_DIFF_CONFIG = {
8417
+ ignoreInsignificant: true,
8418
+ trackedProperties: ["visible", "enabled", "focused", "checked", "value", "textContent"],
8419
+ generateSuggestions: true,
8420
+ maxModifications: 20
8421
+ };
8422
+ var INSIGNIFICANT_PROPERTIES = /* @__PURE__ */ new Set(["rect", "computedStyles", "innerHTML"]);
8423
+ function computeDiff(fromSnapshot, toSnapshot, config = {}) {
8424
+ const startTime = performance.now();
8425
+ const finalConfig = { ...DEFAULT_DIFF_CONFIG, ...config };
8426
+ const fromElements = new Map(fromSnapshot.elements.map((el) => [el.id, el]));
8427
+ const toElements = new Map(toSnapshot.elements.map((el) => [el.id, el]));
8428
+ const appeared = [];
8429
+ for (const [id, element] of toElements) {
8430
+ if (!fromElements.has(id)) {
8431
+ appeared.push({
8432
+ elementId: id,
8433
+ description: element.description,
8434
+ type: element.type,
8435
+ semanticType: element.semanticType
8436
+ });
8437
+ }
8438
+ }
8439
+ const disappeared = [];
8440
+ for (const [id, element] of fromElements) {
8441
+ if (!toElements.has(id)) {
8442
+ disappeared.push({
8443
+ elementId: id,
8444
+ description: element.description,
8445
+ type: element.type,
8446
+ semanticType: element.semanticType
8447
+ });
8448
+ }
8449
+ }
8450
+ const modified = [];
8451
+ for (const [id, toElement] of toElements) {
8452
+ const fromElement = fromElements.get(id);
8453
+ if (fromElement) {
8454
+ const modifications = compareElements(fromElement, toElement, finalConfig);
8455
+ modified.push(...modifications);
8456
+ }
8457
+ }
8458
+ const limitedModifications = modified.slice(0, finalConfig.maxModifications);
8459
+ const probableTrigger = detectTrigger(appeared, disappeared, limitedModifications);
8460
+ const suggestedActions = finalConfig.generateSuggestions ? generateSuggestedActionsFromDiff(appeared, disappeared, limitedModifications, probableTrigger) : void 0;
8461
+ const pageChanges = detectPageChanges(fromSnapshot, toSnapshot);
8462
+ const summary = generateDiffSummary(
8463
+ appeared.map((e) => e.description),
8464
+ disappeared.map((e) => e.description),
8465
+ limitedModifications
8466
+ );
8467
+ return {
8468
+ summary,
8469
+ fromSnapshotId: fromSnapshot.snapshotId,
8470
+ toSnapshotId: toSnapshot.snapshotId,
8471
+ changes: {
8472
+ appeared,
8473
+ disappeared,
8474
+ modified: limitedModifications
8475
+ },
8476
+ probableTrigger,
8477
+ suggestedActions,
8478
+ pageChanges,
8479
+ durationMs: performance.now() - startTime,
8480
+ timestamp: Date.now()
8481
+ };
8482
+ }
8483
+ function compareElements(fromElement, toElement, config) {
8484
+ const modifications = [];
8485
+ for (const property of config.trackedProperties) {
8486
+ const fromValue = getPropertyValue(fromElement, property);
8487
+ const toValue = getPropertyValue(toElement, property);
8488
+ if (fromValue !== toValue) {
8489
+ const isSignificant = isSignificantChange(property, fromValue, toValue);
8490
+ if (!config.ignoreInsignificant || isSignificant) {
8491
+ modifications.push({
8492
+ elementId: toElement.id,
8493
+ description: toElement.description,
8494
+ property,
8495
+ from: formatValue(fromValue),
8496
+ to: formatValue(toValue),
8497
+ significant: isSignificant
8498
+ });
8499
+ }
8500
+ }
8501
+ }
8502
+ return modifications;
8503
+ }
8504
+ function getPropertyValue(element, property) {
8505
+ if (property in element.state) {
8506
+ return element.state[property];
8507
+ }
8508
+ return element[property];
8509
+ }
8510
+ function isSignificantChange(property, fromValue, toValue) {
8511
+ if (INSIGNIFICANT_PROPERTIES.has(property)) {
8512
+ return false;
8513
+ }
8514
+ if (property === "visible") {
8515
+ return true;
8516
+ }
8517
+ if (property === "enabled") {
8518
+ return true;
8519
+ }
8520
+ if (property === "focused") {
8521
+ return true;
8522
+ }
8523
+ if (property === "checked") {
8524
+ return true;
8525
+ }
8526
+ if (property === "value") {
8527
+ return Boolean(fromValue) || Boolean(toValue);
8528
+ }
8529
+ if (property === "textContent") {
8530
+ const fromText = String(fromValue || "");
8531
+ const toText = String(toValue || "");
8532
+ return fromText.trim() !== toText.trim();
8533
+ }
8534
+ return true;
8535
+ }
8536
+ function formatValue(value) {
8537
+ if (value === void 0) return "undefined";
8538
+ if (value === null) return "null";
8539
+ if (typeof value === "boolean") return value ? "true" : "false";
8540
+ if (typeof value === "string") {
8541
+ if (value.length > 50) {
8542
+ return value.substring(0, 47) + "...";
8543
+ }
8544
+ return value;
8545
+ }
8546
+ if (typeof value === "object") {
8547
+ return JSON.stringify(value);
8548
+ }
8549
+ return String(value);
8550
+ }
8551
+ function detectTrigger(appeared, disappeared, modified) {
8552
+ const hasNewErrors = appeared.some(
8553
+ (e) => e.description.toLowerCase().includes("error") || e.type === "error"
8554
+ );
8555
+ if (hasNewErrors) {
8556
+ return "Form validation";
8557
+ }
8558
+ const hasNewModal = appeared.some(
8559
+ (e) => e.type === "dialog" || e.semanticType?.includes("dialog")
8560
+ );
8561
+ if (hasNewModal) {
8562
+ return "Modal opened";
8563
+ }
8564
+ const hasModalDismissed = disappeared.some(
8565
+ (e) => e.type === "dialog" || e.semanticType?.includes("dialog")
8566
+ );
8567
+ if (hasModalDismissed) {
8568
+ return "Modal closed";
8569
+ }
8570
+ const hasLoading = modified.some((m) => m.description.toLowerCase().includes("loading"));
8571
+ if (hasLoading) {
8572
+ return "Loading state change";
8573
+ }
8574
+ const hasFocusChange = modified.some((m) => m.property === "focused");
8575
+ if (hasFocusChange && modified.length <= 2) {
8576
+ return "Focus changed";
8577
+ }
8578
+ const hasValueChange = modified.some((m) => m.property === "value");
8579
+ if (hasValueChange && modified.length <= 2) {
8580
+ return "User input";
8581
+ }
8582
+ const visibilityChanges = modified.filter((m) => m.property === "visible");
8583
+ if (visibilityChanges.length > 0 && visibilityChanges.length <= 5) {
8584
+ return "UI expansion/collapse";
8585
+ }
8586
+ if (appeared.length > 5) {
8587
+ return "Page navigation";
8588
+ }
8589
+ return void 0;
8590
+ }
8591
+ function detectPageChanges(fromSnapshot, toSnapshot) {
8592
+ const urlChanged = fromSnapshot.page.url !== toSnapshot.page.url;
8593
+ const titleChanged = fromSnapshot.page.title !== toSnapshot.page.title;
8594
+ if (!urlChanged && !titleChanged) {
8595
+ return void 0;
8596
+ }
8597
+ return {
8598
+ urlChanged,
8599
+ titleChanged,
8600
+ newUrl: urlChanged ? toSnapshot.page.url : void 0,
8601
+ newTitle: titleChanged ? toSnapshot.page.title : void 0
8602
+ };
8603
+ }
8604
+ function generateSuggestedActionsFromDiff(appeared, disappeared, modified, trigger) {
8605
+ const suggestions = [];
8606
+ if (trigger === "Form validation") {
8607
+ suggestions.push("Fix the validation errors before submitting");
8608
+ }
8609
+ if (trigger === "Modal opened") {
8610
+ const modal = appeared.find(
8611
+ (e) => e.type === "dialog" || e.semanticType?.includes("dialog")
8612
+ );
8613
+ if (modal) {
8614
+ suggestions.push(`Interact with the "${modal.description}" dialog`);
8615
+ }
8616
+ }
8617
+ if (trigger === "Modal closed") {
8618
+ suggestions.push("Continue with the main page interaction");
8619
+ }
8620
+ for (const element of appeared.slice(0, 3)) {
8621
+ if (element.type === "button" && element.semanticType === "submit-button") {
8622
+ suggestions.push(`Click the "${element.description}" to proceed`);
8623
+ }
8624
+ if (element.description.toLowerCase().includes("error")) {
8625
+ suggestions.push(`Address the error: ${element.description}`);
8626
+ }
8627
+ }
8628
+ for (const mod of modified.slice(0, 3)) {
8629
+ if (mod.property === "enabled" && mod.to === "true") {
8630
+ suggestions.push(`"${mod.description}" is now enabled`);
8631
+ }
8632
+ if (mod.property === "visible" && mod.to === "true") {
8633
+ suggestions.push(`"${mod.description}" is now visible`);
8634
+ }
8635
+ }
8636
+ return suggestions.slice(0, 5);
8637
+ }
8638
+ var SemanticDiffManager = class {
8639
+ constructor(config = {}) {
8640
+ this.lastSnapshot = null;
8641
+ this.config = { ...DEFAULT_DIFF_CONFIG, ...config };
8642
+ }
8643
+ /**
8644
+ * Update with new snapshot and get diff
8645
+ */
8646
+ update(newSnapshot) {
8647
+ if (!this.lastSnapshot) {
8648
+ this.lastSnapshot = newSnapshot;
8649
+ return null;
8650
+ }
8651
+ const diff = computeDiff(this.lastSnapshot, newSnapshot, this.config);
8652
+ this.lastSnapshot = newSnapshot;
8653
+ return diff;
8654
+ }
8655
+ /**
8656
+ * Get diff from a specific snapshot to current
8657
+ */
8658
+ diffFrom(fromSnapshot) {
8659
+ if (!this.lastSnapshot) return null;
8660
+ return computeDiff(fromSnapshot, this.lastSnapshot, this.config);
8661
+ }
8662
+ /**
8663
+ * Reset the manager
8664
+ */
8665
+ reset() {
8666
+ this.lastSnapshot = null;
8667
+ }
8668
+ /**
8669
+ * Get the last known snapshot
8670
+ */
8671
+ getLastSnapshot() {
8672
+ return this.lastSnapshot;
8673
+ }
8674
+ };
8675
+ function createDiffManager(config) {
8676
+ return new SemanticDiffManager(config);
8677
+ }
8678
+ function hasSignificantChanges(diff) {
8679
+ if (diff.changes.appeared.length > 0) return true;
8680
+ if (diff.changes.disappeared.length > 0) return true;
8681
+ if (diff.changes.modified.some((m) => m.significant)) return true;
8682
+ if (diff.pageChanges?.urlChanged) return true;
8683
+ return false;
8684
+ }
8685
+ function describeDiff(diff) {
8686
+ const parts = [];
8687
+ if (diff.changes.appeared.length > 0) {
8688
+ parts.push(`${diff.changes.appeared.length} elements appeared`);
8689
+ }
8690
+ if (diff.changes.disappeared.length > 0) {
8691
+ parts.push(`${diff.changes.disappeared.length} elements disappeared`);
8692
+ }
8693
+ const significantMods = diff.changes.modified.filter((m) => m.significant);
8694
+ if (significantMods.length > 0) {
8695
+ parts.push(`${significantMods.length} elements modified`);
8696
+ }
8697
+ if (diff.pageChanges?.urlChanged) {
8698
+ parts.push("URL changed");
8699
+ }
8700
+ if (parts.length === 0) {
8701
+ return "No significant changes";
8702
+ }
8703
+ return parts.join(", ");
8704
+ }
8705
+
8706
+ export { AssertionExecutor, AutoRegisterProvider, DEFAULT_ALIAS_CONFIG, DEFAULT_ASSERTION_CONFIG, DEFAULT_DIFF_CONFIG, DEFAULT_EXECUTOR_CONFIG, DEFAULT_FUZZY_CONFIG, DEFAULT_SEARCH_CONFIG, DEFAULT_SNAPSHOT_CONFIG, DOMChangeObserver, DefaultActionExecutor, DefaultWorkflowEngine, ErrorCodes, ID_ATTRIBUTES, InMemoryRenderLogStorage, InfoPanel, Inspector, InspectorOverlay, MetricsCollector, NLActionExecutor, RenderLogManager, SearchEngine, SemanticDiffManager, SemanticSnapshotManager, UIBridgeProvider, UIBridgeRegistry, UIBridgeWSClient, areSynonyms, captureDOMSnapshot, captureInteractiveElements, computeDiff, createActionExecutor, createAssertionExecutor, createDiffManager, createElementIdentifier, createErrorContext, createMetricsCollector, createNLActionExecutor, createRenderLogManager, createSearchEngine, createSimpleError, createSnapshotManager, createWSClient, createWorkflowEngine, describeAction, describeDiff, elementMatchesIdentifier, extractModifiers, findAllElementsByIdentifier, findAllMatches, findBestMatch, findElementByIdentifier, formatDuration, formatErrorContext, formatPercentage, fuzzyContains, fuzzyMatch, generateAliases, generateCSSSelector, generateDescription, generateDiffSummary, generateElementDescription, generateNgrams, generatePageSummary, generatePurpose, generateSnapshotSummary, generateSuggestedActions, generateXPath, getBestIdentifier, getBestRecoverySuggestion, getGlobalRegistry, getSynonyms, hasSignificantChanges, inferPageType, isRecoverableError, jaroSimilarity, jaroWinklerSimilarity, levenshteinDistance, levenshteinSimilarity, ngramSimilarity, normalizeString, parseNLInstruction, parseNLInstructions, resetGlobalRegistry, setGlobalRegistry, splitCompoundInstruction, tokenSimilarity, tokenize, useActiveStates, useAutoRegister, useAvailableTransitions, useCanNavigateTo, useInspector, useNavigationPath, useStateSnapshot, useTransitions, useUIBridge, useUIBridgeContext, useUIBridgeOptional, useUIBridgeRequired, useUIComponent, useUIComponentAction, useUIElement, useUIElementRef, useUINavigation, useUIState, useUIStateGroup, useUITransition, validateParsedAction, wordSimilarity };
4664
8707
  //# sourceMappingURL=index.mjs.map
4665
8708
  //# sourceMappingURL=index.mjs.map