@qontinui/ui-bridge 0.1.1 → 0.3.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 (112) 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/babel-plugin/index.js +515 -0
  8. package/dist/babel-plugin/index.js.map +1 -0
  9. package/dist/babel-plugin/index.mjs +499 -0
  10. package/dist/babel-plugin/index.mjs.map +1 -0
  11. package/dist/control/index.d.mts +5 -4
  12. package/dist/control/index.d.ts +5 -4
  13. package/dist/core/index.d.mts +115 -42
  14. package/dist/core/index.d.ts +115 -42
  15. package/dist/core/index.js +0 -983
  16. package/dist/core/index.js.map +1 -1
  17. package/dist/core/index.mjs +1 -972
  18. package/dist/core/index.mjs.map +1 -1
  19. package/dist/debug/index.d.mts +3 -3
  20. package/dist/debug/index.d.ts +3 -3
  21. package/dist/index.d.mts +8 -7
  22. package/dist/index.d.ts +8 -7
  23. package/dist/index.js +8249 -4163
  24. package/dist/index.js.map +1 -1
  25. package/dist/index.mjs +8193 -4152
  26. package/dist/index.mjs.map +1 -1
  27. package/dist/{metrics-QCnK0EFw.d.ts → metrics-BfiT_rhZ.d.ts} +2 -2
  28. package/dist/{metrics-BCG7z7Aq.d.mts → metrics-DTA2bwG7.d.mts} +2 -2
  29. package/dist/native/control/index.js +453 -0
  30. package/dist/native/control/index.js.map +1 -0
  31. package/dist/native/control/index.mjs +450 -0
  32. package/dist/native/control/index.mjs.map +1 -0
  33. package/dist/native/core/index.js +486 -0
  34. package/dist/native/core/index.js.map +1 -0
  35. package/dist/native/core/index.mjs +475 -0
  36. package/dist/native/core/index.mjs.map +1 -0
  37. package/dist/native/debug/index.js +451 -0
  38. package/dist/native/debug/index.js.map +1 -0
  39. package/dist/native/debug/index.mjs +449 -0
  40. package/dist/native/debug/index.mjs.map +1 -0
  41. package/dist/native/index.js +2274 -0
  42. package/dist/native/index.js.map +1 -0
  43. package/dist/native/index.mjs +2246 -0
  44. package/dist/native/index.mjs.map +1 -0
  45. package/dist/native/react/index.js +1401 -0
  46. package/dist/native/react/index.js.map +1 -0
  47. package/dist/native/react/index.mjs +1389 -0
  48. package/dist/native/react/index.mjs.map +1 -0
  49. package/dist/native/server/index.js +415 -0
  50. package/dist/native/server/index.js.map +1 -0
  51. package/dist/native/server/index.mjs +410 -0
  52. package/dist/native/server/index.mjs.map +1 -0
  53. package/dist/react/index.d.mts +20 -6
  54. package/dist/react/index.d.ts +20 -6
  55. package/dist/react/index.js +629 -14
  56. package/dist/react/index.js.map +1 -1
  57. package/dist/react/index.mjs +629 -14
  58. package/dist/react/index.mjs.map +1 -1
  59. package/dist/{registry-CT6BVVKr.d.mts → registry-BKLEm-yk.d.ts} +29 -14
  60. package/dist/{registry-D4mQ01B3.d.ts → registry-BmZgyCz8.d.mts} +29 -14
  61. package/dist/render-log/index.d.mts +1 -1
  62. package/dist/render-log/index.d.ts +1 -1
  63. package/dist/server/express.d.mts +36 -0
  64. package/dist/server/express.d.ts +36 -0
  65. package/dist/server/express.js +196 -0
  66. package/dist/server/express.js.map +1 -0
  67. package/dist/server/express.mjs +192 -0
  68. package/dist/server/express.mjs.map +1 -0
  69. package/dist/server/handlers.d.mts +93 -0
  70. package/dist/server/handlers.d.ts +93 -0
  71. package/dist/server/handlers.js +4278 -0
  72. package/dist/server/handlers.js.map +1 -0
  73. package/dist/server/handlers.mjs +4275 -0
  74. package/dist/server/handlers.mjs.map +1 -0
  75. package/dist/server/index.d.mts +10 -0
  76. package/dist/server/index.d.ts +10 -0
  77. package/dist/server/index.js +5352 -0
  78. package/dist/server/index.js.map +1 -0
  79. package/dist/server/index.mjs +5337 -0
  80. package/dist/server/index.mjs.map +1 -0
  81. package/dist/server/nextjs.d.mts +126 -0
  82. package/dist/server/nextjs.d.ts +126 -0
  83. package/dist/server/nextjs.js +287 -0
  84. package/dist/server/nextjs.js.map +1 -0
  85. package/dist/server/nextjs.mjs +282 -0
  86. package/dist/server/nextjs.mjs.map +1 -0
  87. package/dist/server/standalone.d.mts +6 -0
  88. package/dist/server/standalone.d.ts +6 -0
  89. package/dist/server/standalone.js +719 -0
  90. package/dist/server/standalone.js.map +1 -0
  91. package/dist/server/standalone.mjs +715 -0
  92. package/dist/server/standalone.mjs.map +1 -0
  93. package/dist/standalone-BURj8J3G.d.ts +212 -0
  94. package/dist/standalone-Dwmel29d.d.mts +212 -0
  95. package/dist/swc-plugin/index.d.mts +79 -0
  96. package/dist/swc-plugin/index.d.ts +79 -0
  97. package/dist/swc-plugin/index.js +15 -0
  98. package/dist/swc-plugin/index.js.map +1 -0
  99. package/dist/swc-plugin/index.mjs +9 -0
  100. package/dist/swc-plugin/index.mjs.map +1 -0
  101. package/dist/types-B5Q0GVo0.d.mts +646 -0
  102. package/dist/{types-DdJD9yw5.d.mts → types-B7J7noLK.d.mts} +1 -1
  103. package/dist/{types-BDkXy5si.d.ts → types-BkNRILUa.d.ts} +1 -1
  104. package/dist/types-CEQLnFMv.d.mts +156 -0
  105. package/dist/types-CHnlwiTK.d.ts +156 -0
  106. package/dist/types-DfPqwU-i.d.ts +646 -0
  107. package/dist/{types-BpvpStn3.d.mts → types-jKVgTI6_.d.mts} +364 -160
  108. package/dist/{types-BpvpStn3.d.ts → types-jKVgTI6_.d.ts} +364 -160
  109. package/package.json +111 -3
  110. package/swc-plugin-wasm/ui_bridge_swc_plugin.wasm +0 -0
  111. package/dist/websocket-client-B2LC9CYc.d.mts +0 -124
  112. package/dist/websocket-client-DupH0X7B.d.ts +0 -124
@@ -0,0 +1,4275 @@
1
+ // src/ai/fuzzy-matcher.ts
2
+ var DEFAULT_FUZZY_CONFIG = {
3
+ threshold: 0.7,
4
+ levenshteinWeight: 0.3,
5
+ jaroWinklerWeight: 0.4,
6
+ ngramWeight: 0.3,
7
+ ngramSize: 2,
8
+ caseSensitive: false,
9
+ ignoreWhitespace: true
10
+ };
11
+ function levenshteinDistance(s1, s2) {
12
+ const len1 = s1.length;
13
+ const len2 = s2.length;
14
+ const matrix = Array(len1 + 1).fill(null).map(() => Array(len2 + 1).fill(0));
15
+ for (let i = 0; i <= len1; i++) matrix[i][0] = i;
16
+ for (let j = 0; j <= len2; j++) matrix[0][j] = j;
17
+ for (let i = 1; i <= len1; i++) {
18
+ for (let j = 1; j <= len2; j++) {
19
+ const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;
20
+ matrix[i][j] = Math.min(
21
+ matrix[i - 1][j] + 1,
22
+ // deletion
23
+ matrix[i][j - 1] + 1,
24
+ // insertion
25
+ matrix[i - 1][j - 1] + cost
26
+ // substitution
27
+ );
28
+ }
29
+ }
30
+ return matrix[len1][len2];
31
+ }
32
+ function levenshteinSimilarity(s1, s2) {
33
+ if (s1.length === 0 && s2.length === 0) return 1;
34
+ if (s1.length === 0 || s2.length === 0) return 0;
35
+ const distance = levenshteinDistance(s1, s2);
36
+ const maxLength = Math.max(s1.length, s2.length);
37
+ return 1 - distance / maxLength;
38
+ }
39
+ function jaroSimilarity(s1, s2) {
40
+ if (s1.length === 0 && s2.length === 0) return 1;
41
+ if (s1.length === 0 || s2.length === 0) return 0;
42
+ const matchDistance = Math.floor(Math.max(s1.length, s2.length) / 2) - 1;
43
+ const s1Matches = new Array(s1.length).fill(false);
44
+ const s2Matches = new Array(s2.length).fill(false);
45
+ let matches = 0;
46
+ let transpositions = 0;
47
+ for (let i = 0; i < s1.length; i++) {
48
+ const start = Math.max(0, i - matchDistance);
49
+ const end = Math.min(i + matchDistance + 1, s2.length);
50
+ for (let j = start; j < end; j++) {
51
+ if (s2Matches[j] || s1[i] !== s2[j]) continue;
52
+ s1Matches[i] = true;
53
+ s2Matches[j] = true;
54
+ matches++;
55
+ break;
56
+ }
57
+ }
58
+ if (matches === 0) return 0;
59
+ let k = 0;
60
+ for (let i = 0; i < s1.length; i++) {
61
+ if (!s1Matches[i]) continue;
62
+ while (!s2Matches[k]) k++;
63
+ if (s1[i] !== s2[k]) transpositions++;
64
+ k++;
65
+ }
66
+ return (matches / s1.length + matches / s2.length + (matches - transpositions / 2) / matches) / 3;
67
+ }
68
+ function jaroWinklerSimilarity(s1, s2, prefixScale = 0.1) {
69
+ const jaroSim = jaroSimilarity(s1, s2);
70
+ let prefixLength = 0;
71
+ const maxPrefix = Math.min(4, Math.min(s1.length, s2.length));
72
+ for (let i = 0; i < maxPrefix; i++) {
73
+ if (s1[i] === s2[i]) {
74
+ prefixLength++;
75
+ } else {
76
+ break;
77
+ }
78
+ }
79
+ return jaroSim + prefixLength * prefixScale * (1 - jaroSim);
80
+ }
81
+ function generateNgrams(s, n) {
82
+ const ngrams = /* @__PURE__ */ new Set();
83
+ if (s.length < n) {
84
+ ngrams.add(s);
85
+ return ngrams;
86
+ }
87
+ for (let i = 0; i <= s.length - n; i++) {
88
+ ngrams.add(s.substring(i, i + n));
89
+ }
90
+ return ngrams;
91
+ }
92
+ function ngramSimilarity(s1, s2, n = 2) {
93
+ if (s1.length === 0 && s2.length === 0) return 1;
94
+ if (s1.length === 0 || s2.length === 0) return 0;
95
+ const ngrams1 = generateNgrams(s1, n);
96
+ const ngrams2 = generateNgrams(s2, n);
97
+ let intersection = 0;
98
+ for (const ngram of ngrams1) {
99
+ if (ngrams2.has(ngram)) {
100
+ intersection++;
101
+ }
102
+ }
103
+ const union = ngrams1.size + ngrams2.size - intersection;
104
+ return union === 0 ? 0 : intersection / union;
105
+ }
106
+ function normalizeString(s, config = {}) {
107
+ let normalized = s;
108
+ if (!config.caseSensitive) {
109
+ normalized = normalized.toLowerCase();
110
+ }
111
+ if (config.ignoreWhitespace !== false) {
112
+ normalized = normalized.replace(/\s+/g, " ").trim();
113
+ }
114
+ return normalized;
115
+ }
116
+ function fuzzyMatch(source, target, config = {}) {
117
+ const finalConfig = { ...DEFAULT_FUZZY_CONFIG, ...config };
118
+ const normalizedSource = normalizeString(source, finalConfig);
119
+ const normalizedTarget = normalizeString(target, finalConfig);
120
+ const levenshteinScore = levenshteinSimilarity(normalizedSource, normalizedTarget);
121
+ const jaroWinklerScore = jaroWinklerSimilarity(normalizedSource, normalizedTarget);
122
+ const ngramScore = ngramSimilarity(normalizedSource, normalizedTarget, finalConfig.ngramSize);
123
+ const similarity = levenshteinScore * finalConfig.levenshteinWeight + jaroWinklerScore * finalConfig.jaroWinklerWeight + ngramScore * finalConfig.ngramWeight;
124
+ return {
125
+ similarity,
126
+ isMatch: similarity >= finalConfig.threshold,
127
+ scores: {
128
+ levenshtein: levenshteinScore,
129
+ jaroWinkler: jaroWinklerScore,
130
+ ngram: ngramScore
131
+ },
132
+ normalizedSource,
133
+ normalizedTarget
134
+ };
135
+ }
136
+ function fuzzyContains(source, target, config = {}) {
137
+ const finalConfig = { ...DEFAULT_FUZZY_CONFIG, ...config };
138
+ const normalizedSource = normalizeString(source, finalConfig);
139
+ const normalizedTarget = normalizeString(target, finalConfig);
140
+ if (normalizedSource.includes(normalizedTarget)) {
141
+ return true;
142
+ }
143
+ const sourceWords = normalizedSource.split(/\s+/);
144
+ const targetWords = normalizedTarget.split(/\s+/);
145
+ for (const targetWord of targetWords) {
146
+ const hasMatch = sourceWords.some((sourceWord) => {
147
+ const result = fuzzyMatch(sourceWord, targetWord, { ...finalConfig, threshold: 0.8 });
148
+ return result.isMatch;
149
+ });
150
+ if (!hasMatch) {
151
+ return false;
152
+ }
153
+ }
154
+ return true;
155
+ }
156
+ function wordSimilarity(s1, s2, config = {}) {
157
+ const finalConfig = { ...DEFAULT_FUZZY_CONFIG, ...config };
158
+ const words1 = normalizeString(s1, finalConfig).split(/\s+/);
159
+ const words2 = normalizeString(s2, finalConfig).split(/\s+/);
160
+ if (words1.length === 0 && words2.length === 0) return 1;
161
+ if (words1.length === 0 || words2.length === 0) return 0;
162
+ let totalSimilarity = 0;
163
+ let matchCount = 0;
164
+ for (const word1 of words1) {
165
+ let bestSim = 0;
166
+ for (const word2 of words2) {
167
+ const result = fuzzyMatch(word1, word2, finalConfig);
168
+ if (result.similarity > bestSim) {
169
+ bestSim = result.similarity;
170
+ }
171
+ }
172
+ totalSimilarity += bestSim;
173
+ if (bestSim >= finalConfig.threshold) {
174
+ matchCount++;
175
+ }
176
+ }
177
+ const avgSimilarity = totalSimilarity / words1.length;
178
+ const matchRatio = matchCount / Math.max(words1.length, words2.length);
179
+ return avgSimilarity * 0.5 + matchRatio * 0.5;
180
+ }
181
+ function tokenize(s) {
182
+ return s.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[_-]/g, " ").replace(/\s+/g, " ").trim().toLowerCase().split(" ").filter((token) => token.length > 0);
183
+ }
184
+ function tokenSimilarity(s1, s2) {
185
+ const tokens1 = tokenize(s1);
186
+ const tokens2 = tokenize(s2);
187
+ if (tokens1.length === 0 && tokens2.length === 0) return 1;
188
+ if (tokens1.length === 0 || tokens2.length === 0) return 0;
189
+ const set1 = new Set(tokens1);
190
+ const set2 = new Set(tokens2);
191
+ let intersection = 0;
192
+ for (const token of set1) {
193
+ if (set2.has(token)) {
194
+ intersection++;
195
+ }
196
+ }
197
+ const union = set1.size + set2.size - intersection;
198
+ return union === 0 ? 0 : intersection / union;
199
+ }
200
+
201
+ // src/ai/alias-generator.ts
202
+ var DEFAULT_ALIAS_CONFIG = {
203
+ includeText: true,
204
+ includeAriaLabel: true,
205
+ includePlaceholder: true,
206
+ includeTitle: true,
207
+ includeSynonyms: true,
208
+ maxAliases: 20,
209
+ minLength: 2,
210
+ maxLength: 50
211
+ };
212
+ var SYNONYMS = {
213
+ // Submit-related
214
+ submit: ["send", "go", "confirm", "ok", "apply", "save", "done", "finish"],
215
+ send: ["submit", "deliver", "post"],
216
+ save: ["submit", "store", "keep", "apply"],
217
+ cancel: ["close", "dismiss", "abort", "back", "exit", "quit", "nevermind"],
218
+ close: ["cancel", "dismiss", "exit", "x"],
219
+ delete: ["remove", "trash", "erase", "clear", "destroy"],
220
+ remove: ["delete", "clear", "discard"],
221
+ edit: ["modify", "change", "update", "alter"],
222
+ update: ["edit", "modify", "save", "refresh"],
223
+ add: ["create", "new", "plus", "insert"],
224
+ create: ["add", "new", "make"],
225
+ search: ["find", "lookup", "query", "filter"],
226
+ find: ["search", "locate", "lookup"],
227
+ login: ["signin", "sign in", "log in", "authenticate", "enter"],
228
+ logout: ["signout", "sign out", "log out", "exit"],
229
+ register: ["signup", "sign up", "join", "create account"],
230
+ next: ["continue", "forward", "proceed", "advance"],
231
+ previous: ["back", "backward", "return", "prior"],
232
+ back: ["previous", "return", "backward"],
233
+ start: ["begin", "launch", "initiate", "run", "execute"],
234
+ stop: ["end", "halt", "pause", "terminate"],
235
+ enable: ["activate", "turn on", "switch on"],
236
+ disable: ["deactivate", "turn off", "switch off"],
237
+ show: ["display", "reveal", "view", "open"],
238
+ hide: ["conceal", "collapse", "close"],
239
+ expand: ["open", "show", "unfold", "reveal"],
240
+ collapse: ["close", "hide", "fold", "minimize"],
241
+ yes: ["ok", "confirm", "agree", "accept"],
242
+ no: ["cancel", "decline", "reject", "deny"],
243
+ help: ["support", "assistance", "info", "information", "faq"],
244
+ settings: ["preferences", "options", "config", "configuration"],
245
+ profile: ["account", "user", "me"],
246
+ download: ["export", "save", "get"],
247
+ upload: ["import", "load", "attach"],
248
+ refresh: ["reload", "update", "sync"],
249
+ copy: ["duplicate", "clone"],
250
+ paste: ["insert"],
251
+ select: ["choose", "pick"],
252
+ toggle: ["switch", "flip"],
253
+ // Form fields
254
+ email: ["e-mail", "mail"],
255
+ password: ["pass", "pwd", "secret"],
256
+ username: ["user", "login", "account", "name"],
257
+ firstname: ["first name", "given name", "forename"],
258
+ lastname: ["last name", "surname", "family name"],
259
+ fullname: ["full name", "name", "complete name"],
260
+ phone: ["telephone", "tel", "mobile", "cell"],
261
+ address: ["location", "street"],
262
+ city: ["town"],
263
+ country: ["nation"],
264
+ zip: ["zipcode", "postal", "postal code", "postcode"],
265
+ // Navigation
266
+ home: ["main", "start", "dashboard"],
267
+ menu: ["navigation", "nav"],
268
+ sidebar: ["side bar", "side panel", "side menu"]
269
+ };
270
+ var ELEMENT_ACTION_WORDS = {
271
+ button: ["button", "btn", "click"],
272
+ input: ["input", "field", "textbox", "box"],
273
+ textarea: ["textarea", "text area", "text field", "multiline"],
274
+ select: ["select", "dropdown", "combo", "picker", "chooser"],
275
+ checkbox: ["checkbox", "check", "tick"],
276
+ radio: ["radio", "option", "choice"],
277
+ link: ["link", "anchor", "href"],
278
+ form: ["form"],
279
+ menu: ["menu"],
280
+ menuitem: ["menu item", "option"],
281
+ tab: ["tab"],
282
+ dialog: ["dialog", "modal", "popup"],
283
+ switch: ["switch", "toggle"],
284
+ slider: ["slider", "range"]
285
+ };
286
+ function normalizeAlias(text) {
287
+ return text.toLowerCase().replace(/[^\w\s]/g, " ").replace(/\s+/g, " ").trim();
288
+ }
289
+ function extractWords(text) {
290
+ const tokens = tokenize(text);
291
+ return tokens.filter((t) => t.length >= 2);
292
+ }
293
+ function generateTextAliases(text, config) {
294
+ if (!text || !config.includeText) return [];
295
+ const aliases = [];
296
+ const normalized = normalizeAlias(text);
297
+ if (normalized.length >= config.minLength && normalized.length <= config.maxLength) {
298
+ aliases.push(normalized);
299
+ }
300
+ const words = extractWords(text);
301
+ for (const word of words) {
302
+ if (word.length >= config.minLength) {
303
+ aliases.push(word);
304
+ }
305
+ }
306
+ if (words.length >= 2 && words.length <= 4) {
307
+ const twoWords = words.slice(0, 2).join(" ");
308
+ if (twoWords.length <= config.maxLength) {
309
+ aliases.push(twoWords);
310
+ }
311
+ if (words.length > 2) {
312
+ const lastTwo = words.slice(-2).join(" ");
313
+ if (lastTwo.length <= config.maxLength) {
314
+ aliases.push(lastTwo);
315
+ }
316
+ }
317
+ }
318
+ return aliases;
319
+ }
320
+ function generateSynonyms(aliases, config) {
321
+ if (!config.includeSynonyms) return [];
322
+ const synonyms = [];
323
+ for (const alias of aliases) {
324
+ const words = alias.toLowerCase().split(/\s+/);
325
+ for (const word of words) {
326
+ if (SYNONYMS[word]) {
327
+ for (const synonym of SYNONYMS[word]) {
328
+ const newAlias = alias.toLowerCase().replace(word, synonym);
329
+ if (newAlias !== alias.toLowerCase()) {
330
+ synonyms.push(newAlias);
331
+ }
332
+ if (synonym.length >= config.minLength) {
333
+ synonyms.push(synonym);
334
+ }
335
+ }
336
+ }
337
+ }
338
+ }
339
+ return synonyms;
340
+ }
341
+ function generateTypeAliases(elementType) {
342
+ const type = elementType.toLowerCase();
343
+ return ELEMENT_ACTION_WORDS[type] || [type];
344
+ }
345
+ function generateAliases(input, config = {}) {
346
+ const finalConfig = { ...DEFAULT_ALIAS_CONFIG, ...config };
347
+ const aliasSet = /* @__PURE__ */ new Set();
348
+ const addAlias = (alias) => {
349
+ const normalized = normalizeAlias(alias);
350
+ if (normalized.length >= finalConfig.minLength && normalized.length <= finalConfig.maxLength) {
351
+ aliasSet.add(normalized);
352
+ }
353
+ };
354
+ const addAliases = (aliases2) => {
355
+ for (const alias of aliases2) {
356
+ addAlias(alias);
357
+ }
358
+ };
359
+ if (finalConfig.includeText && input.textContent) {
360
+ addAliases(generateTextAliases(input.textContent, finalConfig));
361
+ }
362
+ if (finalConfig.includeAriaLabel && input.ariaLabel) {
363
+ addAliases(generateTextAliases(input.ariaLabel, finalConfig));
364
+ }
365
+ if (finalConfig.includeAriaLabel && input.ariaLabelledBy) {
366
+ addAliases(generateTextAliases(input.ariaLabelledBy, finalConfig));
367
+ }
368
+ if (finalConfig.includePlaceholder && input.placeholder) {
369
+ addAliases(generateTextAliases(input.placeholder, finalConfig));
370
+ }
371
+ if (finalConfig.includeTitle && input.title) {
372
+ addAliases(generateTextAliases(input.title, finalConfig));
373
+ }
374
+ if (input.labelText) {
375
+ addAliases(generateTextAliases(input.labelText, finalConfig));
376
+ }
377
+ if (input.id) {
378
+ addAliases(extractWords(input.id));
379
+ }
380
+ if (input.name) {
381
+ addAliases(extractWords(input.name));
382
+ }
383
+ if (input.value && (input.elementType === "button" || input.inputType === "submit" || input.inputType === "button")) {
384
+ addAliases(generateTextAliases(input.value, finalConfig));
385
+ }
386
+ if (input.elementType) {
387
+ addAliases(generateTypeAliases(input.elementType));
388
+ }
389
+ if (input.inputType) {
390
+ addAlias(input.inputType);
391
+ if (input.inputType === "email") {
392
+ addAliases(["email", "e-mail", "email address"]);
393
+ } else if (input.inputType === "password") {
394
+ addAliases(["password", "pass", "pwd"]);
395
+ } else if (input.inputType === "tel") {
396
+ addAliases(["phone", "telephone", "mobile"]);
397
+ } else if (input.inputType === "url") {
398
+ addAliases(["url", "website", "link", "address"]);
399
+ } else if (input.inputType === "search") {
400
+ addAliases(["search", "find", "query"]);
401
+ }
402
+ }
403
+ if (finalConfig.includeSynonyms) {
404
+ const currentAliases = Array.from(aliasSet);
405
+ addAliases(generateSynonyms(currentAliases, finalConfig));
406
+ }
407
+ let aliases = Array.from(aliasSet);
408
+ aliases.sort((a, b) => a.length - b.length);
409
+ if (aliases.length > finalConfig.maxAliases) {
410
+ aliases = aliases.slice(0, finalConfig.maxAliases);
411
+ }
412
+ return aliases;
413
+ }
414
+ function generateDescription(input) {
415
+ const parts = [];
416
+ let name = input.ariaLabel || input.labelText || input.textContent || input.placeholder || input.title || input.id || input.name;
417
+ if (name) {
418
+ name = name.trim();
419
+ if (name.length > 30) {
420
+ name = name.substring(0, 27) + "...";
421
+ }
422
+ parts.push(`"${name}"`);
423
+ }
424
+ const typeWords = ELEMENT_ACTION_WORDS[input.elementType || ""] || [input.elementType || "element"];
425
+ parts.push(typeWords[0]);
426
+ if (input.inputType && input.inputType !== "text") {
427
+ parts.push(`(${input.inputType})`);
428
+ }
429
+ return parts.join(" ");
430
+ }
431
+ function generatePurpose(input) {
432
+ const text = (input.textContent || input.ariaLabel || input.title || "").toLowerCase();
433
+ const type = input.elementType?.toLowerCase() || "";
434
+ const inputType = input.inputType?.toLowerCase() || "";
435
+ if (type === "button" || inputType === "submit") {
436
+ if (text.match(/submit|send|save|confirm|ok|done|finish|apply/)) {
437
+ return "Submits the form";
438
+ }
439
+ if (text.match(/cancel|close|dismiss|back|exit/)) {
440
+ return "Cancels or closes the current action";
441
+ }
442
+ if (text.match(/delete|remove|trash|clear/)) {
443
+ return "Deletes or removes an item";
444
+ }
445
+ if (text.match(/edit|modify|change|update/)) {
446
+ return "Edits or modifies an item";
447
+ }
448
+ if (text.match(/add|create|new|\+/)) {
449
+ return "Creates or adds a new item";
450
+ }
451
+ if (text.match(/search|find|lookup/)) {
452
+ return "Performs a search";
453
+ }
454
+ if (text.match(/login|sign.?in/)) {
455
+ return "Signs the user in";
456
+ }
457
+ if (text.match(/logout|sign.?out/)) {
458
+ return "Signs the user out";
459
+ }
460
+ if (text.match(/register|sign.?up|join/)) {
461
+ return "Creates a new account";
462
+ }
463
+ if (text.match(/next|continue|proceed/)) {
464
+ return "Proceeds to the next step";
465
+ }
466
+ if (text.match(/previous|back|return/)) {
467
+ return "Returns to the previous step";
468
+ }
469
+ }
470
+ if (type === "input" || type === "textarea") {
471
+ if (inputType === "email") return "Accepts email address input";
472
+ if (inputType === "password") return "Accepts password input";
473
+ if (inputType === "search") return "Accepts search query input";
474
+ if (inputType === "tel") return "Accepts phone number input";
475
+ if (inputType === "url") return "Accepts URL input";
476
+ if (inputType === "number") return "Accepts numeric input";
477
+ if (inputType === "date") return "Accepts date input";
478
+ if (inputType === "file") return "Accepts file upload";
479
+ }
480
+ if (type === "checkbox") {
481
+ return "Toggles an option on or off";
482
+ }
483
+ if (type === "radio") {
484
+ return "Selects one option from a group";
485
+ }
486
+ if (type === "select") {
487
+ return "Selects an option from a dropdown";
488
+ }
489
+ if (type === "link") {
490
+ return "Navigates to another page";
491
+ }
492
+ return void 0;
493
+ }
494
+ function generateSuggestedActions(input) {
495
+ const type = input.elementType?.toLowerCase() || "";
496
+ const inputType = input.inputType?.toLowerCase() || "";
497
+ const text = (input.textContent || input.ariaLabel || "").toLowerCase();
498
+ const actions = [];
499
+ switch (type) {
500
+ case "button":
501
+ actions.push(`click "${text || "this button"}"`);
502
+ break;
503
+ case "input":
504
+ if (inputType === "checkbox") {
505
+ actions.push("check to enable", "uncheck to disable");
506
+ } else if (inputType === "radio") {
507
+ actions.push("select this option");
508
+ } else {
509
+ actions.push(`type into "${text || "this field"}"`);
510
+ actions.push("clear the field");
511
+ }
512
+ break;
513
+ case "textarea":
514
+ actions.push(`type into "${text || "this text area"}"`);
515
+ actions.push("clear the content");
516
+ break;
517
+ case "select":
518
+ actions.push(`select an option from "${text || "this dropdown"}"`);
519
+ break;
520
+ case "checkbox":
521
+ actions.push("check to enable", "uncheck to disable");
522
+ break;
523
+ case "radio":
524
+ actions.push("select this option");
525
+ break;
526
+ case "link":
527
+ actions.push(`click to navigate to "${text || "the linked page"}"`);
528
+ break;
529
+ case "switch":
530
+ actions.push("toggle on", "toggle off");
531
+ break;
532
+ default:
533
+ actions.push("click");
534
+ }
535
+ return actions;
536
+ }
537
+ function areSynonyms(word1, word2) {
538
+ const w1 = word1.toLowerCase().trim();
539
+ const w2 = word2.toLowerCase().trim();
540
+ if (w1 === w2) return true;
541
+ const synonyms1 = SYNONYMS[w1] || [];
542
+ const synonyms2 = SYNONYMS[w2] || [];
543
+ return synonyms1.includes(w2) || synonyms2.includes(w1);
544
+ }
545
+
546
+ // src/ai/search-engine.ts
547
+ var DEFAULT_SEARCH_CONFIG = {
548
+ fuzzyThreshold: 0.7,
549
+ textWeight: 0.35,
550
+ accessibilityWeight: 0.25,
551
+ roleWeight: 0.15,
552
+ spatialWeight: 0.1,
553
+ aliasWeight: 0.15,
554
+ maxResults: 20,
555
+ includeHidden: false
556
+ };
557
+ var SearchEngine = class {
558
+ // Cache valid for 100ms
559
+ constructor(config = {}) {
560
+ this.cachedElements = [];
561
+ this.cacheTimestamp = 0;
562
+ this.cacheValidityMs = 100;
563
+ this.config = { ...DEFAULT_SEARCH_CONFIG, ...config };
564
+ }
565
+ /**
566
+ * Update cached elements from various sources
567
+ */
568
+ updateElements(elements, getState) {
569
+ this.cachedElements = elements.map((el) => this.toSearchable(el, getState));
570
+ this.cacheTimestamp = Date.now();
571
+ }
572
+ /**
573
+ * Convert an element to searchable format
574
+ */
575
+ toSearchable(element, getState) {
576
+ let state;
577
+ let textContent;
578
+ let tagName;
579
+ let role;
580
+ let ariaLabel;
581
+ let placeholder;
582
+ let title;
583
+ let labelText;
584
+ let value;
585
+ if ("getState" in element && typeof element.getState === "function") {
586
+ state = getState ? getState(element) : element.getState();
587
+ textContent = state.textContent || void 0;
588
+ tagName = element.element.tagName.toLowerCase();
589
+ role = element.element.getAttribute("role") || void 0;
590
+ ariaLabel = element.element.getAttribute("aria-label") || void 0;
591
+ placeholder = element.element.getAttribute("placeholder") || void 0;
592
+ title = element.element.getAttribute("title") || void 0;
593
+ if (element.element.id) {
594
+ const labelEl = document.querySelector(`label[for="${element.element.id}"]`);
595
+ labelText = labelEl?.textContent?.trim() || void 0;
596
+ }
597
+ if (element.element instanceof HTMLInputElement || element.element instanceof HTMLTextAreaElement || element.element instanceof HTMLSelectElement) {
598
+ value = element.element.value || void 0;
599
+ }
600
+ } else {
601
+ const discovered = element;
602
+ state = discovered.state;
603
+ textContent = state.textContent || void 0;
604
+ tagName = discovered.tagName;
605
+ role = discovered.role || void 0;
606
+ ariaLabel = discovered.accessibleName || void 0;
607
+ }
608
+ const aliases = generateAliases({
609
+ textContent,
610
+ ariaLabel,
611
+ placeholder,
612
+ title,
613
+ elementType: element.type,
614
+ id: element.id,
615
+ labelText,
616
+ value
617
+ });
618
+ const description = generateDescription({
619
+ textContent,
620
+ ariaLabel,
621
+ placeholder,
622
+ title,
623
+ elementType: element.type,
624
+ id: element.id,
625
+ labelText
626
+ });
627
+ return {
628
+ id: element.id,
629
+ element,
630
+ state,
631
+ textContent,
632
+ ariaLabel,
633
+ placeholder,
634
+ title,
635
+ role,
636
+ tagName,
637
+ type: element.type,
638
+ aliases,
639
+ description,
640
+ rect: state.rect,
641
+ labelText,
642
+ value
643
+ };
644
+ }
645
+ /**
646
+ * Search for elements matching the criteria
647
+ */
648
+ search(criteria, elements) {
649
+ const startTime = performance.now();
650
+ if (elements) {
651
+ this.updateElements(elements);
652
+ }
653
+ let searchableElements = this.cachedElements;
654
+ if (!this.config.includeHidden && !criteria.fuzzy) {
655
+ searchableElements = searchableElements.filter((el) => el.state.visible);
656
+ }
657
+ const results = [];
658
+ for (const searchable of searchableElements) {
659
+ const result = this.scoreElement(searchable, criteria);
660
+ if (result.confidence >= (criteria.fuzzyThreshold ?? this.config.fuzzyThreshold)) {
661
+ results.push(result);
662
+ }
663
+ }
664
+ results.sort((a, b) => b.confidence - a.confidence);
665
+ const limitedResults = results.slice(0, this.config.maxResults);
666
+ return {
667
+ results: limitedResults,
668
+ bestMatch: limitedResults.length > 0 ? limitedResults[0] : null,
669
+ scannedCount: searchableElements.length,
670
+ durationMs: performance.now() - startTime,
671
+ criteria,
672
+ timestamp: Date.now()
673
+ };
674
+ }
675
+ /**
676
+ * Find the best matching element
677
+ */
678
+ findBest(criteria, elements) {
679
+ const response = this.search(criteria, elements);
680
+ return response.bestMatch;
681
+ }
682
+ /**
683
+ * Find elements by text content
684
+ */
685
+ findByText(text, fuzzy = true, elements) {
686
+ return this.search({ text, fuzzy }, elements).results;
687
+ }
688
+ /**
689
+ * Find elements by role
690
+ */
691
+ findByRole(role, name, elements) {
692
+ const criteria = { role };
693
+ if (name) {
694
+ criteria.accessibleName = name;
695
+ }
696
+ return this.search(criteria, elements).results;
697
+ }
698
+ /**
699
+ * Find elements by accessible name
700
+ */
701
+ findByAccessibleName(name, elements) {
702
+ return this.search({ accessibleName: name, fuzzy: true }, elements).results;
703
+ }
704
+ /**
705
+ * Find elements near another element
706
+ */
707
+ findNear(referenceId, criteria, elements) {
708
+ return this.search({ ...criteria, near: referenceId }, elements).results;
709
+ }
710
+ /**
711
+ * Find elements within a container
712
+ */
713
+ findWithin(containerId, criteria, elements) {
714
+ return this.search({ ...criteria, within: containerId }, elements).results;
715
+ }
716
+ /**
717
+ * Score an element against search criteria
718
+ */
719
+ scoreElement(searchable, criteria) {
720
+ const scores = {};
721
+ const matchReasons = [];
722
+ let totalWeight = 0;
723
+ let weightedScore = 0;
724
+ const fuzzyConfig = {
725
+ ...DEFAULT_FUZZY_CONFIG,
726
+ threshold: criteria.fuzzyThreshold ?? this.config.fuzzyThreshold
727
+ };
728
+ if (criteria.text) {
729
+ const textScore = this.scoreTextMatch(searchable, criteria.text, criteria.fuzzy !== false, fuzzyConfig.threshold);
730
+ scores.text = textScore.score;
731
+ if (textScore.score > 0) {
732
+ matchReasons.push(...textScore.reasons);
733
+ }
734
+ weightedScore += textScore.score * this.config.textWeight;
735
+ totalWeight += this.config.textWeight;
736
+ }
737
+ if (criteria.textContains) {
738
+ const containsScore = this.scoreContainsMatch(searchable, criteria.textContains, criteria.fuzzy !== false);
739
+ scores.text = Math.max(scores.text || 0, containsScore.score);
740
+ if (containsScore.score > 0 && containsScore.reasons.length > 0) {
741
+ matchReasons.push(...containsScore.reasons);
742
+ }
743
+ weightedScore += containsScore.score * this.config.textWeight;
744
+ totalWeight += this.config.textWeight;
745
+ }
746
+ if (criteria.accessibleName) {
747
+ const accessibilityScore = this.scoreAccessibilityMatch(
748
+ searchable,
749
+ criteria.accessibleName,
750
+ criteria.fuzzy !== false,
751
+ fuzzyConfig.threshold
752
+ );
753
+ scores.accessibility = accessibilityScore.score;
754
+ if (accessibilityScore.score > 0) {
755
+ matchReasons.push(...accessibilityScore.reasons);
756
+ }
757
+ weightedScore += accessibilityScore.score * this.config.accessibilityWeight;
758
+ totalWeight += this.config.accessibilityWeight;
759
+ }
760
+ if (criteria.role) {
761
+ const roleScore = this.scoreRoleMatch(searchable, criteria.role);
762
+ scores.role = roleScore.score;
763
+ if (roleScore.score > 0) {
764
+ matchReasons.push(...roleScore.reasons);
765
+ }
766
+ weightedScore += roleScore.score * this.config.roleWeight;
767
+ totalWeight += this.config.roleWeight;
768
+ }
769
+ if (criteria.type) {
770
+ const typeMatch = searchable.type.toLowerCase() === criteria.type.toLowerCase();
771
+ if (typeMatch) {
772
+ matchReasons.push(`type: ${criteria.type}`);
773
+ weightedScore += 1 * this.config.roleWeight;
774
+ totalWeight += this.config.roleWeight;
775
+ }
776
+ }
777
+ if (criteria.near) {
778
+ const spatialScore = this.scoreSpatialMatch(searchable, criteria.near);
779
+ scores.spatial = spatialScore.score;
780
+ if (spatialScore.score > 0) {
781
+ matchReasons.push(...spatialScore.reasons);
782
+ }
783
+ weightedScore += spatialScore.score * this.config.spatialWeight;
784
+ totalWeight += this.config.spatialWeight;
785
+ }
786
+ if (criteria.placeholder && searchable.placeholder) {
787
+ const placeholderResult = fuzzyMatch(searchable.placeholder, criteria.placeholder, fuzzyConfig);
788
+ if (placeholderResult.isMatch) {
789
+ matchReasons.push(`placeholder matches`);
790
+ weightedScore += placeholderResult.similarity * this.config.textWeight;
791
+ totalWeight += this.config.textWeight;
792
+ }
793
+ }
794
+ if (criteria.title && searchable.title) {
795
+ const titleResult = fuzzyMatch(searchable.title, criteria.title, fuzzyConfig);
796
+ if (titleResult.isMatch) {
797
+ matchReasons.push(`title matches`);
798
+ weightedScore += titleResult.similarity * this.config.textWeight;
799
+ totalWeight += this.config.textWeight;
800
+ }
801
+ }
802
+ if (criteria.idPattern) {
803
+ const idMatch = this.matchPattern(searchable.id, criteria.idPattern);
804
+ if (idMatch) {
805
+ matchReasons.push(`id matches pattern`);
806
+ weightedScore += 1 * this.config.textWeight;
807
+ totalWeight += this.config.textWeight;
808
+ }
809
+ }
810
+ const aliasScore = this.scoreAliasMatch(searchable, criteria, fuzzyConfig.threshold);
811
+ if (aliasScore.score > 0) {
812
+ scores.fuzzy = aliasScore.score;
813
+ matchReasons.push(...aliasScore.reasons);
814
+ weightedScore += aliasScore.score * this.config.aliasWeight;
815
+ totalWeight += this.config.aliasWeight;
816
+ }
817
+ const confidence = totalWeight > 0 ? weightedScore / totalWeight : 0;
818
+ const aiElement = this.toAIDiscoveredElement(searchable);
819
+ return {
820
+ element: aiElement,
821
+ confidence,
822
+ matchReasons,
823
+ scores
824
+ };
825
+ }
826
+ /**
827
+ * Score text match
828
+ */
829
+ scoreTextMatch(searchable, text, fuzzy, threshold) {
830
+ const reasons = [];
831
+ let maxScore = 0;
832
+ const textsToMatch = [
833
+ searchable.textContent,
834
+ searchable.labelText,
835
+ searchable.value
836
+ ].filter(Boolean);
837
+ for (const targetText of textsToMatch) {
838
+ if (targetText.toLowerCase() === text.toLowerCase()) {
839
+ maxScore = Math.max(maxScore, 1);
840
+ reasons.push("exact text match");
841
+ continue;
842
+ }
843
+ if (fuzzy) {
844
+ const result = fuzzyMatch(targetText, text, { threshold });
845
+ if (result.isMatch && result.similarity > maxScore) {
846
+ maxScore = result.similarity;
847
+ reasons.push(`text similarity: ${(result.similarity * 100).toFixed(0)}%`);
848
+ }
849
+ const wordSim = wordSimilarity(targetText, text, { threshold });
850
+ if (wordSim > maxScore && wordSim >= threshold) {
851
+ maxScore = wordSim;
852
+ reasons.push(`word match: ${(wordSim * 100).toFixed(0)}%`);
853
+ }
854
+ }
855
+ }
856
+ return { score: maxScore, reasons };
857
+ }
858
+ /**
859
+ * Score contains match
860
+ */
861
+ scoreContainsMatch(searchable, text, fuzzy) {
862
+ const reasons = [];
863
+ let maxScore = 0;
864
+ const textsToMatch = [
865
+ searchable.textContent,
866
+ searchable.labelText,
867
+ searchable.ariaLabel
868
+ ].filter(Boolean);
869
+ for (const targetText of textsToMatch) {
870
+ if (targetText.toLowerCase().includes(text.toLowerCase())) {
871
+ maxScore = Math.max(maxScore, 0.9);
872
+ reasons.push("text contains match");
873
+ continue;
874
+ }
875
+ if (fuzzy && fuzzyContains(targetText, text)) {
876
+ maxScore = Math.max(maxScore, 0.7);
877
+ reasons.push("fuzzy contains match");
878
+ }
879
+ }
880
+ return { score: maxScore, reasons };
881
+ }
882
+ /**
883
+ * Score accessibility match
884
+ */
885
+ scoreAccessibilityMatch(searchable, name, fuzzy, threshold) {
886
+ const reasons = [];
887
+ let maxScore = 0;
888
+ const accessibleNames = [
889
+ searchable.ariaLabel,
890
+ searchable.ariaLabelledBy,
891
+ searchable.labelText,
892
+ searchable.title
893
+ ].filter(Boolean);
894
+ for (const accessibleName of accessibleNames) {
895
+ if (accessibleName.toLowerCase() === name.toLowerCase()) {
896
+ maxScore = Math.max(maxScore, 1);
897
+ reasons.push("exact accessible name match");
898
+ continue;
899
+ }
900
+ if (fuzzy) {
901
+ const result = fuzzyMatch(accessibleName, name, { threshold });
902
+ if (result.isMatch && result.similarity > maxScore) {
903
+ maxScore = result.similarity;
904
+ reasons.push(`accessible name similarity: ${(result.similarity * 100).toFixed(0)}%`);
905
+ }
906
+ }
907
+ }
908
+ return { score: maxScore, reasons };
909
+ }
910
+ /**
911
+ * Score role match
912
+ */
913
+ scoreRoleMatch(searchable, role) {
914
+ const reasons = [];
915
+ const normalizedRole = role.toLowerCase();
916
+ if (searchable.role?.toLowerCase() === normalizedRole) {
917
+ return { score: 1, reasons: [`role: ${role}`] };
918
+ }
919
+ const tagRoleMap = {
920
+ button: ["button", "input[type=button]", "input[type=submit]"],
921
+ textbox: ["input", "textarea"],
922
+ checkbox: ["input[type=checkbox]"],
923
+ radio: ["input[type=radio]"],
924
+ link: ["a"],
925
+ listbox: ["select"],
926
+ combobox: ["select", "input[list]"],
927
+ navigation: ["nav"],
928
+ main: ["main"],
929
+ heading: ["h1", "h2", "h3", "h4", "h5", "h6"]
930
+ };
931
+ const inferredRoles = tagRoleMap[normalizedRole] || [];
932
+ if (inferredRoles.some((r) => searchable.tagName === r || searchable.type.toLowerCase() === normalizedRole)) {
933
+ return { score: 0.8, reasons: [`inferred role: ${role}`] };
934
+ }
935
+ return { score: 0, reasons };
936
+ }
937
+ /**
938
+ * Score spatial match (proximity to another element)
939
+ */
940
+ scoreSpatialMatch(searchable, nearId) {
941
+ const reference = this.cachedElements.find((el) => el.id === nearId);
942
+ if (!reference) {
943
+ return { score: 0, reasons: [] };
944
+ }
945
+ const distance = this.calculateDistance(searchable.rect, reference.rect);
946
+ const nearThreshold = 200;
947
+ if (distance > nearThreshold * 3) {
948
+ return { score: 0, reasons: [] };
949
+ }
950
+ const score = Math.max(0, 1 - distance / (nearThreshold * 3));
951
+ return {
952
+ score,
953
+ reasons: [`${distance.toFixed(0)}px from ${nearId}`]
954
+ };
955
+ }
956
+ /**
957
+ * Calculate distance between two element rectangles
958
+ */
959
+ calculateDistance(rect1, rect2) {
960
+ const center1 = {
961
+ x: rect1.x + rect1.width / 2,
962
+ y: rect1.y + rect1.height / 2
963
+ };
964
+ const center2 = {
965
+ x: rect2.x + rect2.width / 2,
966
+ y: rect2.y + rect2.height / 2
967
+ };
968
+ return Math.sqrt(Math.pow(center1.x - center2.x, 2) + Math.pow(center1.y - center2.y, 2));
969
+ }
970
+ /**
971
+ * Score alias match
972
+ */
973
+ scoreAliasMatch(searchable, criteria, threshold) {
974
+ const reasons = [];
975
+ let maxScore = 0;
976
+ const searchTerms = [];
977
+ if (criteria.text) searchTerms.push(criteria.text);
978
+ if (criteria.textContains) searchTerms.push(criteria.textContains);
979
+ if (criteria.accessibleName) searchTerms.push(criteria.accessibleName);
980
+ for (const searchTerm of searchTerms) {
981
+ const termLower = searchTerm.toLowerCase();
982
+ for (const alias of searchable.aliases) {
983
+ if (alias === termLower) {
984
+ maxScore = Math.max(maxScore, 1);
985
+ reasons.push(`alias match: "${alias}"`);
986
+ continue;
987
+ }
988
+ const searchWords = termLower.split(/\s+/);
989
+ const aliasWords = alias.split(/\s+/);
990
+ for (const searchWord of searchWords) {
991
+ for (const aliasWord of aliasWords) {
992
+ if (areSynonyms(searchWord, aliasWord)) {
993
+ maxScore = Math.max(maxScore, 0.85);
994
+ reasons.push(`synonym match: "${searchWord}" ~ "${aliasWord}"`);
995
+ }
996
+ }
997
+ }
998
+ const result = fuzzyMatch(alias, termLower, { threshold });
999
+ if (result.isMatch && result.similarity > maxScore) {
1000
+ maxScore = result.similarity;
1001
+ reasons.push(`fuzzy alias: "${alias}" (${(result.similarity * 100).toFixed(0)}%)`);
1002
+ }
1003
+ const tokenSim = tokenSimilarity(alias, termLower);
1004
+ if (tokenSim > maxScore && tokenSim >= threshold) {
1005
+ maxScore = tokenSim;
1006
+ reasons.push(`token match: "${alias}"`);
1007
+ }
1008
+ }
1009
+ }
1010
+ return { score: maxScore, reasons };
1011
+ }
1012
+ /**
1013
+ * Match a string against a pattern (supports * wildcard)
1014
+ */
1015
+ matchPattern(str, pattern) {
1016
+ const regexPattern = pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, ".*");
1017
+ return new RegExp(`^${regexPattern}$`, "i").test(str);
1018
+ }
1019
+ /**
1020
+ * Convert searchable element to AI discovered element
1021
+ */
1022
+ toAIDiscoveredElement(searchable) {
1023
+ const discoveredBase = "getState" in searchable.element ? {
1024
+ id: searchable.id,
1025
+ type: searchable.type,
1026
+ label: searchable.element.label,
1027
+ tagName: searchable.tagName,
1028
+ role: searchable.role,
1029
+ accessibleName: searchable.ariaLabel,
1030
+ actions: searchable.element.actions,
1031
+ state: searchable.state,
1032
+ registered: true
1033
+ } : searchable.element;
1034
+ return {
1035
+ ...discoveredBase,
1036
+ description: searchable.description,
1037
+ aliases: searchable.aliases,
1038
+ purpose: generatePurpose({
1039
+ textContent: searchable.textContent,
1040
+ ariaLabel: searchable.ariaLabel,
1041
+ elementType: searchable.type,
1042
+ tagName: searchable.tagName
1043
+ }),
1044
+ parentContext: void 0,
1045
+ // Would need DOM traversal
1046
+ suggestedActions: generateSuggestedActions({
1047
+ textContent: searchable.textContent,
1048
+ ariaLabel: searchable.ariaLabel,
1049
+ elementType: searchable.type,
1050
+ tagName: searchable.tagName
1051
+ }),
1052
+ semanticType: this.inferSemanticType(searchable),
1053
+ labelText: searchable.labelText,
1054
+ placeholder: searchable.placeholder,
1055
+ title: searchable.title
1056
+ };
1057
+ }
1058
+ /**
1059
+ * Infer a semantic type for the element
1060
+ */
1061
+ inferSemanticType(searchable) {
1062
+ const text = (searchable.textContent || searchable.ariaLabel || "").toLowerCase();
1063
+ const type = searchable.type.toLowerCase();
1064
+ if (type === "input" || type === "textarea") {
1065
+ if (searchable.placeholder?.toLowerCase().includes("email") || text.includes("email")) {
1066
+ return "email-input";
1067
+ }
1068
+ if (searchable.placeholder?.toLowerCase().includes("password") || text.includes("password")) {
1069
+ return "password-input";
1070
+ }
1071
+ if (searchable.placeholder?.toLowerCase().includes("search") || text.includes("search")) {
1072
+ return "search-input";
1073
+ }
1074
+ return "text-input";
1075
+ }
1076
+ if (type === "button") {
1077
+ if (text.match(/submit|save|confirm|ok|done|apply/)) return "submit-button";
1078
+ if (text.match(/cancel|close|dismiss/)) return "cancel-button";
1079
+ if (text.match(/delete|remove|trash/)) return "delete-button";
1080
+ if (text.match(/add|create|new|\+/)) return "add-button";
1081
+ if (text.match(/edit|modify/)) return "edit-button";
1082
+ if (text.match(/next|continue/)) return "next-button";
1083
+ if (text.match(/back|previous/)) return "back-button";
1084
+ return "action-button";
1085
+ }
1086
+ if (type === "link") {
1087
+ if (text.match(/home|dashboard/)) return "home-link";
1088
+ if (text.match(/login|sign.?in/)) return "login-link";
1089
+ if (text.match(/logout|sign.?out/)) return "logout-link";
1090
+ return "navigation-link";
1091
+ }
1092
+ return type;
1093
+ }
1094
+ };
1095
+
1096
+ // src/ai/summary-generator.ts
1097
+ var DEFAULT_SUMMARY_CONFIG = {
1098
+ maxLength: 2e3,
1099
+ includeForms: true,
1100
+ includeElementCounts: true,
1101
+ includeModals: true,
1102
+ includeFocused: true,
1103
+ verbosity: "normal"
1104
+ };
1105
+ function generatePageSummary(elements, pageContext, config = {}) {
1106
+ const finalConfig = { ...DEFAULT_SUMMARY_CONFIG, ...config };
1107
+ const lines = [];
1108
+ if (pageContext) {
1109
+ if (pageContext.title) {
1110
+ lines.push(`Page: "${pageContext.title}"`);
1111
+ }
1112
+ if (pageContext.pageType && pageContext.pageType !== "unknown") {
1113
+ lines.push(`Type: ${formatPageType(pageContext.pageType)}`);
1114
+ }
1115
+ }
1116
+ if (finalConfig.includeElementCounts) {
1117
+ const counts = countElementTypes(elements);
1118
+ const countParts = [];
1119
+ if (counts.button > 0) countParts.push(`${counts.button} button${counts.button > 1 ? "s" : ""}`);
1120
+ if (counts.input > 0) countParts.push(`${counts.input} input${counts.input > 1 ? "s" : ""}`);
1121
+ if (counts.link > 0) countParts.push(`${counts.link} link${counts.link > 1 ? "s" : ""}`);
1122
+ if (counts.select > 0) countParts.push(`${counts.select} dropdown${counts.select > 1 ? "s" : ""}`);
1123
+ if (counts.checkbox > 0) countParts.push(`${counts.checkbox} checkbox${counts.checkbox > 1 ? "es" : ""}`);
1124
+ if (countParts.length > 0) {
1125
+ lines.push(`Contains: ${countParts.join(", ")}`);
1126
+ }
1127
+ }
1128
+ if (finalConfig.includeForms) {
1129
+ const forms = detectForms(elements);
1130
+ if (forms.length > 0) {
1131
+ lines.push("");
1132
+ lines.push("Forms:");
1133
+ for (const form of forms) {
1134
+ lines.push(generateFormSummary(form, finalConfig.verbosity));
1135
+ }
1136
+ }
1137
+ }
1138
+ if (finalConfig.includeModals && pageContext?.activeModals && pageContext.activeModals.length > 0) {
1139
+ lines.push("");
1140
+ lines.push(`Active modals: ${pageContext.activeModals.join(", ")}`);
1141
+ }
1142
+ if (finalConfig.includeFocused && pageContext?.focusedElement) {
1143
+ lines.push(`Focus: ${pageContext.focusedElement}`);
1144
+ }
1145
+ const keyElements = getKeyElements(elements);
1146
+ if (keyElements.length > 0) {
1147
+ lines.push("");
1148
+ lines.push("Key elements:");
1149
+ for (const el of keyElements) {
1150
+ lines.push(` - ${el.description}${el.state.enabled ? "" : " (disabled)"}`);
1151
+ }
1152
+ }
1153
+ let summary = lines.join("\n");
1154
+ if (summary.length > finalConfig.maxLength) {
1155
+ summary = summary.substring(0, finalConfig.maxLength - 3) + "...";
1156
+ }
1157
+ return summary;
1158
+ }
1159
+ function generateFormSummary(form, verbosity) {
1160
+ const lines = [];
1161
+ const formName = form.name || form.purpose || form.id;
1162
+ lines.push(` ${formName}:`);
1163
+ if (verbosity === "brief") {
1164
+ const fieldCount = form.fields.length;
1165
+ const filledCount = form.fields.filter((f) => f.value).length;
1166
+ lines.push(` ${filledCount}/${fieldCount} fields filled, ${form.isValid ? "valid" : "has errors"}`);
1167
+ } else {
1168
+ for (const field of form.fields) {
1169
+ let fieldLine = ` - ${field.label || field.id}`;
1170
+ if (field.value) {
1171
+ fieldLine += ` = "${truncate(field.value, 15)}"`;
1172
+ } else if (field.placeholder) {
1173
+ fieldLine += ` (${field.placeholder})`;
1174
+ } else {
1175
+ fieldLine += " (empty)";
1176
+ }
1177
+ if (!field.valid && field.error) {
1178
+ fieldLine += ` [ERROR: ${field.error}]`;
1179
+ } else if (field.required && !field.value) {
1180
+ fieldLine += " [required]";
1181
+ }
1182
+ lines.push(fieldLine);
1183
+ }
1184
+ if (form.submitButton) {
1185
+ lines.push(` Submit: ${form.submitButton}`);
1186
+ }
1187
+ }
1188
+ return lines.join("\n");
1189
+ }
1190
+ function generateDiffSummary(appeared, disappeared, modified) {
1191
+ const lines = [];
1192
+ if (appeared.length > 0) {
1193
+ lines.push(`Appeared: ${appeared.join(", ")}`);
1194
+ }
1195
+ if (disappeared.length > 0) {
1196
+ lines.push(`Disappeared: ${disappeared.join(", ")}`);
1197
+ }
1198
+ if (modified.length > 0) {
1199
+ lines.push("Changed:");
1200
+ for (const mod of modified.slice(0, 5)) {
1201
+ lines.push(` - ${mod.description}: ${mod.property} changed from "${mod.from}" to "${mod.to}"`);
1202
+ }
1203
+ if (modified.length > 5) {
1204
+ lines.push(` ... and ${modified.length - 5} more changes`);
1205
+ }
1206
+ }
1207
+ if (lines.length === 0) {
1208
+ return "No changes detected";
1209
+ }
1210
+ return lines.join("\n");
1211
+ }
1212
+ function countElementTypes(elements) {
1213
+ const counts = {};
1214
+ for (const el of elements) {
1215
+ const type = el.type.toLowerCase();
1216
+ counts[type] = (counts[type] || 0) + 1;
1217
+ }
1218
+ return counts;
1219
+ }
1220
+ function detectForms(elements) {
1221
+ const formElements = elements.filter(
1222
+ (el) => el.type === "input" || el.type === "textarea" || el.type === "select" || el.type === "checkbox"
1223
+ );
1224
+ if (formElements.length === 0) return [];
1225
+ const forms = [];
1226
+ const submitButtons = elements.filter(
1227
+ (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")
1228
+ );
1229
+ const defaultForm = {
1230
+ id: "detected-form",
1231
+ purpose: inferFormPurpose(formElements),
1232
+ fields: formElements.map((el) => ({
1233
+ id: el.id,
1234
+ label: el.labelText || el.accessibleName || el.placeholder || el.id,
1235
+ type: el.type,
1236
+ value: el.state.value || "",
1237
+ valid: true,
1238
+ // Can't determine without validation state
1239
+ required: false,
1240
+ // Can't determine without DOM access
1241
+ placeholder: el.placeholder
1242
+ })),
1243
+ isValid: true,
1244
+ submitButton: submitButtons[0]?.id
1245
+ };
1246
+ if (defaultForm.fields.length > 0) {
1247
+ forms.push(defaultForm);
1248
+ }
1249
+ return forms;
1250
+ }
1251
+ function inferFormPurpose(fields) {
1252
+ const labels = fields.map(
1253
+ (f) => (f.labelText || f.accessibleName || f.placeholder || "").toLowerCase()
1254
+ );
1255
+ const allLabels = labels.join(" ");
1256
+ if (allLabels.includes("email") && allLabels.includes("password")) {
1257
+ if (allLabels.includes("confirm") || allLabels.includes("name")) {
1258
+ return "Registration form";
1259
+ }
1260
+ return "Login form";
1261
+ }
1262
+ if (allLabels.includes("search")) {
1263
+ return "Search form";
1264
+ }
1265
+ if (allLabels.includes("address") || allLabels.includes("city") || allLabels.includes("zip")) {
1266
+ return "Address form";
1267
+ }
1268
+ if (allLabels.includes("card") || allLabels.includes("cvv") || allLabels.includes("expir")) {
1269
+ return "Payment form";
1270
+ }
1271
+ if (allLabels.includes("contact") || allLabels.includes("message")) {
1272
+ return "Contact form";
1273
+ }
1274
+ return "Form";
1275
+ }
1276
+ function getKeyElements(elements) {
1277
+ const keyElements = [];
1278
+ const actionButtons = elements.filter(
1279
+ (el) => el.type === "button" && el.state.visible && (el.semanticType?.includes("submit") || el.semanticType?.includes("action") || el.semanticType?.includes("next"))
1280
+ );
1281
+ keyElements.push(...actionButtons.slice(0, 2));
1282
+ const primaryInputs = elements.filter(
1283
+ (el) => (el.type === "input" || el.type === "textarea") && el.state.visible
1284
+ );
1285
+ keyElements.push(...primaryInputs.slice(0, 3));
1286
+ const links = elements.filter((el) => el.type === "link" && el.state.visible);
1287
+ keyElements.push(...links.slice(0, 2));
1288
+ const unique = [...new Map(keyElements.map((e) => [e.id, e])).values()];
1289
+ return unique.slice(0, 8);
1290
+ }
1291
+ function formatPageType(pageType) {
1292
+ const typeLabels = {
1293
+ login: "Login page",
1294
+ dashboard: "Dashboard",
1295
+ form: "Form page",
1296
+ list: "List/table page",
1297
+ detail: "Detail page",
1298
+ search: "Search page",
1299
+ checkout: "Checkout page",
1300
+ settings: "Settings page",
1301
+ unknown: "Unknown"
1302
+ };
1303
+ return typeLabels[pageType || "unknown"] || "Page";
1304
+ }
1305
+ function truncate(str, maxLength) {
1306
+ if (str.length <= maxLength) return str;
1307
+ return str.substring(0, maxLength - 3) + "...";
1308
+ }
1309
+ function inferPageType(url, title, elements) {
1310
+ const urlLower = url.toLowerCase();
1311
+ const titleLower = title.toLowerCase();
1312
+ if (urlLower.includes("login") || urlLower.includes("signin")) return "login";
1313
+ if (urlLower.includes("dashboard")) return "dashboard";
1314
+ if (urlLower.includes("search")) return "search";
1315
+ if (urlLower.includes("checkout") || urlLower.includes("payment")) return "checkout";
1316
+ if (urlLower.includes("settings") || urlLower.includes("preferences")) return "settings";
1317
+ if (titleLower.includes("login") || titleLower.includes("sign in")) return "login";
1318
+ if (titleLower.includes("dashboard")) return "dashboard";
1319
+ if (titleLower.includes("search")) return "search";
1320
+ const hasLoginForm = elements.some((el) => el.type === "input" && el.semanticType === "email-input") && elements.some((el) => el.type === "input" && el.semanticType === "password-input");
1321
+ if (hasLoginForm) return "login";
1322
+ const hasSearchInput = elements.some(
1323
+ (el) => el.type === "input" && el.semanticType === "search-input"
1324
+ );
1325
+ if (hasSearchInput) return "search";
1326
+ const inputCount = elements.filter(
1327
+ (el) => el.type === "input" || el.type === "textarea" || el.type === "select"
1328
+ ).length;
1329
+ if (inputCount >= 3) return "form";
1330
+ const hasTable = elements.some((el) => el.tagName === "table");
1331
+ const hasMany = elements.length > 20;
1332
+ if (hasTable || hasMany) return "list";
1333
+ return "unknown";
1334
+ }
1335
+
1336
+ // src/ai/nl-action-parser.ts
1337
+ var ACTION_PATTERNS = [
1338
+ // Click patterns
1339
+ {
1340
+ regex: /^click\s+(?:on\s+)?(?:the\s+)?(.+?)(?:\s+button)?$/i,
1341
+ action: "click",
1342
+ targetGroup: 1,
1343
+ confidence: 0.95
1344
+ },
1345
+ {
1346
+ regex: /^press\s+(?:the\s+)?(.+?)(?:\s+button)?$/i,
1347
+ action: "click",
1348
+ targetGroup: 1,
1349
+ confidence: 0.9
1350
+ },
1351
+ {
1352
+ regex: /^tap\s+(?:on\s+)?(?:the\s+)?(.+)$/i,
1353
+ action: "click",
1354
+ targetGroup: 1,
1355
+ confidence: 0.85
1356
+ },
1357
+ {
1358
+ regex: /^activate\s+(?:the\s+)?(.+)$/i,
1359
+ action: "click",
1360
+ targetGroup: 1,
1361
+ confidence: 0.8
1362
+ },
1363
+ // Double click patterns
1364
+ {
1365
+ regex: /^double[\s-]?click\s+(?:on\s+)?(?:the\s+)?(.+)$/i,
1366
+ action: "doubleClick",
1367
+ targetGroup: 1,
1368
+ confidence: 0.95
1369
+ },
1370
+ // Right click patterns
1371
+ {
1372
+ regex: /^right[\s-]?click\s+(?:on\s+)?(?:the\s+)?(.+)$/i,
1373
+ action: "rightClick",
1374
+ targetGroup: 1,
1375
+ confidence: 0.95
1376
+ },
1377
+ {
1378
+ regex: /^context\s+click\s+(?:on\s+)?(?:the\s+)?(.+)$/i,
1379
+ action: "rightClick",
1380
+ targetGroup: 1,
1381
+ confidence: 0.9
1382
+ },
1383
+ // Type patterns - "type X in Y"
1384
+ {
1385
+ regex: /^type\s+["'](.+?)["']\s+(?:in(?:to)?|on)\s+(?:the\s+)?(.+)$/i,
1386
+ action: "type",
1387
+ targetGroup: 2,
1388
+ valueGroup: 1,
1389
+ confidence: 0.95
1390
+ },
1391
+ {
1392
+ regex: /^type\s+(.+?)\s+(?:in(?:to)?|on)\s+(?:the\s+)?(.+)$/i,
1393
+ action: "type",
1394
+ targetGroup: 2,
1395
+ valueGroup: 1,
1396
+ confidence: 0.85
1397
+ },
1398
+ // Type patterns - "enter X in Y"
1399
+ {
1400
+ regex: /^enter\s+["'](.+?)["']\s+(?:in(?:to)?|on)\s+(?:the\s+)?(.+)$/i,
1401
+ action: "type",
1402
+ targetGroup: 2,
1403
+ valueGroup: 1,
1404
+ confidence: 0.95
1405
+ },
1406
+ {
1407
+ regex: /^enter\s+(.+?)\s+(?:in(?:to)?|on)\s+(?:the\s+)?(.+)$/i,
1408
+ action: "type",
1409
+ targetGroup: 2,
1410
+ valueGroup: 1,
1411
+ confidence: 0.85
1412
+ },
1413
+ // Type patterns - "input X into Y"
1414
+ {
1415
+ regex: /^input\s+["'](.+?)["']\s+(?:in(?:to)?)\s+(?:the\s+)?(.+)$/i,
1416
+ action: "type",
1417
+ targetGroup: 2,
1418
+ valueGroup: 1,
1419
+ confidence: 0.9
1420
+ },
1421
+ // Type patterns - "fill Y with X"
1422
+ {
1423
+ regex: /^fill\s+(?:in\s+)?(?:the\s+)?(.+?)\s+with\s+["'](.+?)["']$/i,
1424
+ action: "type",
1425
+ targetGroup: 1,
1426
+ valueGroup: 2,
1427
+ confidence: 0.95
1428
+ },
1429
+ {
1430
+ regex: /^fill\s+(?:in\s+)?(?:the\s+)?(.+?)\s+with\s+(.+)$/i,
1431
+ action: "type",
1432
+ targetGroup: 1,
1433
+ valueGroup: 2,
1434
+ confidence: 0.85
1435
+ },
1436
+ // Type patterns - "set Y to X"
1437
+ {
1438
+ regex: /^set\s+(?:the\s+)?(.+?)\s+to\s+["'](.+?)["']$/i,
1439
+ action: "type",
1440
+ targetGroup: 1,
1441
+ valueGroup: 2,
1442
+ confidence: 0.9
1443
+ },
1444
+ // Select patterns
1445
+ {
1446
+ regex: /^select\s+["'](.+?)["']\s+(?:from|in)\s+(?:the\s+)?(.+)$/i,
1447
+ action: "select",
1448
+ targetGroup: 2,
1449
+ valueGroup: 1,
1450
+ confidence: 0.95
1451
+ },
1452
+ {
1453
+ regex: /^choose\s+["'](.+?)["']\s+(?:from|in)\s+(?:the\s+)?(.+)$/i,
1454
+ action: "select",
1455
+ targetGroup: 2,
1456
+ valueGroup: 1,
1457
+ confidence: 0.9
1458
+ },
1459
+ {
1460
+ regex: /^pick\s+["'](.+?)["']\s+(?:from|in)\s+(?:the\s+)?(.+)$/i,
1461
+ action: "select",
1462
+ targetGroup: 2,
1463
+ valueGroup: 1,
1464
+ confidence: 0.85
1465
+ },
1466
+ // Check patterns
1467
+ {
1468
+ regex: /^check\s+(?:the\s+)?(.+?)(?:\s+checkbox)?$/i,
1469
+ action: "check",
1470
+ targetGroup: 1,
1471
+ confidence: 0.9
1472
+ },
1473
+ {
1474
+ regex: /^enable\s+(?:the\s+)?(.+)$/i,
1475
+ action: "check",
1476
+ targetGroup: 1,
1477
+ confidence: 0.8
1478
+ },
1479
+ {
1480
+ regex: /^tick\s+(?:the\s+)?(.+)$/i,
1481
+ action: "check",
1482
+ targetGroup: 1,
1483
+ confidence: 0.85
1484
+ },
1485
+ // Uncheck patterns
1486
+ {
1487
+ regex: /^uncheck\s+(?:the\s+)?(.+?)(?:\s+checkbox)?$/i,
1488
+ action: "uncheck",
1489
+ targetGroup: 1,
1490
+ confidence: 0.9
1491
+ },
1492
+ {
1493
+ regex: /^disable\s+(?:the\s+)?(.+)$/i,
1494
+ action: "uncheck",
1495
+ targetGroup: 1,
1496
+ confidence: 0.8
1497
+ },
1498
+ {
1499
+ regex: /^untick\s+(?:the\s+)?(.+)$/i,
1500
+ action: "uncheck",
1501
+ targetGroup: 1,
1502
+ confidence: 0.85
1503
+ },
1504
+ // Clear patterns
1505
+ {
1506
+ regex: /^clear\s+(?:the\s+)?(.+)$/i,
1507
+ action: "clear",
1508
+ targetGroup: 1,
1509
+ confidence: 0.9
1510
+ },
1511
+ {
1512
+ regex: /^erase\s+(?:the\s+)?(.+)$/i,
1513
+ action: "clear",
1514
+ targetGroup: 1,
1515
+ confidence: 0.85
1516
+ },
1517
+ {
1518
+ regex: /^empty\s+(?:the\s+)?(.+)$/i,
1519
+ action: "clear",
1520
+ targetGroup: 1,
1521
+ confidence: 0.8
1522
+ },
1523
+ // Hover patterns
1524
+ {
1525
+ regex: /^hover\s+(?:over\s+)?(?:the\s+)?(.+)$/i,
1526
+ action: "hover",
1527
+ targetGroup: 1,
1528
+ confidence: 0.9
1529
+ },
1530
+ {
1531
+ regex: /^mouse\s+over\s+(?:the\s+)?(.+)$/i,
1532
+ action: "hover",
1533
+ targetGroup: 1,
1534
+ confidence: 0.85
1535
+ },
1536
+ // Focus patterns
1537
+ {
1538
+ regex: /^focus\s+(?:on\s+)?(?:the\s+)?(.+)$/i,
1539
+ action: "focus",
1540
+ targetGroup: 1,
1541
+ confidence: 0.9
1542
+ },
1543
+ // Scroll patterns
1544
+ {
1545
+ regex: /^scroll\s+(up|down|left|right)$/i,
1546
+ action: "scroll",
1547
+ targetGroup: 1,
1548
+ confidence: 0.9
1549
+ },
1550
+ {
1551
+ regex: /^scroll\s+(?:the\s+)?(.+?)\s+(up|down|left|right)$/i,
1552
+ action: "scroll",
1553
+ targetGroup: 1,
1554
+ confidence: 0.85
1555
+ },
1556
+ {
1557
+ regex: /^scroll\s+to\s+(?:the\s+)?(.+)$/i,
1558
+ action: "scroll",
1559
+ targetGroup: 1,
1560
+ confidence: 0.85
1561
+ },
1562
+ // Wait patterns
1563
+ {
1564
+ regex: /^wait\s+(?:for\s+)?(?:the\s+)?(.+?)(?:\s+to\s+(?:be\s+)?(.+))?$/i,
1565
+ action: "wait",
1566
+ targetGroup: 1,
1567
+ confidence: 0.85
1568
+ },
1569
+ {
1570
+ regex: /^wait\s+until\s+(?:the\s+)?(.+?)(?:\s+(?:is|becomes)\s+(.+))?$/i,
1571
+ action: "wait",
1572
+ targetGroup: 1,
1573
+ confidence: 0.85
1574
+ },
1575
+ // Assert patterns
1576
+ {
1577
+ regex: /^(?:assert|verify|check)\s+(?:that\s+)?(?:the\s+)?(.+?)\s+(?:is\s+)?(visible|hidden|enabled|disabled|checked|unchecked|focused)$/i,
1578
+ action: "assert",
1579
+ targetGroup: 1,
1580
+ confidence: 0.9
1581
+ },
1582
+ {
1583
+ regex: /^(?:assert|verify|check)\s+(?:that\s+)?(?:the\s+)?(.+?)\s+(?:contains|has)\s+["'](.+?)["']$/i,
1584
+ action: "assert",
1585
+ targetGroup: 1,
1586
+ valueGroup: 2,
1587
+ confidence: 0.9
1588
+ },
1589
+ {
1590
+ regex: /^(?:the\s+)?(.+?)\s+should\s+(?:be\s+)?(visible|hidden|enabled|disabled|checked|unchecked|focused)$/i,
1591
+ action: "assert",
1592
+ targetGroup: 1,
1593
+ confidence: 0.85
1594
+ }
1595
+ ];
1596
+ var ASSERTION_TYPE_MAP = {
1597
+ visible: "visible",
1598
+ hidden: "hidden",
1599
+ enabled: "enabled",
1600
+ disabled: "disabled",
1601
+ checked: "checked",
1602
+ unchecked: "unchecked",
1603
+ focused: "focused",
1604
+ contains: "containsText",
1605
+ has: "hasText"
1606
+ };
1607
+ function parseNLInstruction(instruction) {
1608
+ const trimmed = instruction.trim();
1609
+ if (!trimmed) return null;
1610
+ for (const pattern of ACTION_PATTERNS) {
1611
+ const match = trimmed.match(pattern.regex);
1612
+ if (match) {
1613
+ const parsed = {
1614
+ action: pattern.action,
1615
+ targetDescription: cleanTargetDescription(match[pattern.targetGroup] || ""),
1616
+ rawInstruction: instruction,
1617
+ parseConfidence: pattern.confidence
1618
+ };
1619
+ if (pattern.valueGroup && match[pattern.valueGroup]) {
1620
+ parsed.value = match[pattern.valueGroup];
1621
+ }
1622
+ if (pattern.modifierExtractor) {
1623
+ parsed.modifiers = pattern.modifierExtractor(match);
1624
+ }
1625
+ if (pattern.action === "scroll") {
1626
+ const directionMatch = trimmed.match(/(up|down|left|right)/i);
1627
+ if (directionMatch) {
1628
+ parsed.scrollDirection = directionMatch[1].toLowerCase();
1629
+ }
1630
+ }
1631
+ if (pattern.action === "assert") {
1632
+ const assertMatch = trimmed.match(/(visible|hidden|enabled|disabled|checked|unchecked|focused|contains|has)/i);
1633
+ if (assertMatch) {
1634
+ parsed.assertionType = ASSERTION_TYPE_MAP[assertMatch[1].toLowerCase()];
1635
+ }
1636
+ }
1637
+ if (pattern.action === "wait") {
1638
+ const waitCondition = match[2];
1639
+ if (waitCondition) {
1640
+ parsed.waitCondition = waitCondition;
1641
+ }
1642
+ }
1643
+ return parsed;
1644
+ }
1645
+ }
1646
+ return inferAction(trimmed);
1647
+ }
1648
+ function cleanTargetDescription(target) {
1649
+ return target.trim().replace(/^(the|a|an)\s+/i, "").replace(/\s+(button|field|input|link|dropdown|checkbox|radio)$/i, "").trim();
1650
+ }
1651
+ function inferAction(instruction) {
1652
+ const lower = instruction.toLowerCase();
1653
+ if (lower.includes("click") || lower.includes("press") || lower.includes("tap")) {
1654
+ const target = instruction.replace(/click|press|tap|on|the/gi, "").trim();
1655
+ if (target) {
1656
+ return {
1657
+ action: "click",
1658
+ targetDescription: cleanTargetDescription(target),
1659
+ rawInstruction: instruction,
1660
+ parseConfidence: 0.6
1661
+ };
1662
+ }
1663
+ }
1664
+ if (lower.includes("type") || lower.includes("enter") || lower.includes("input")) {
1665
+ const quotedMatch = instruction.match(/["'](.+?)["']/);
1666
+ if (quotedMatch) {
1667
+ const target = instruction.replace(/type|enter|input|into|in|the|["'].*?["']/gi, "").trim();
1668
+ return {
1669
+ action: "type",
1670
+ targetDescription: cleanTargetDescription(target),
1671
+ value: quotedMatch[1],
1672
+ rawInstruction: instruction,
1673
+ parseConfidence: 0.5
1674
+ };
1675
+ }
1676
+ }
1677
+ return null;
1678
+ }
1679
+ function validateParsedAction(action) {
1680
+ const errors = [];
1681
+ if (!action.targetDescription && action.action !== "scroll") {
1682
+ errors.push("No target element specified");
1683
+ }
1684
+ if ((action.action === "type" || action.action === "select") && !action.value) {
1685
+ errors.push(`No value specified for ${action.action} action`);
1686
+ }
1687
+ if (action.parseConfidence < 0.5) {
1688
+ errors.push("Low confidence parsing - instruction may be ambiguous");
1689
+ }
1690
+ return {
1691
+ valid: errors.length === 0,
1692
+ errors
1693
+ };
1694
+ }
1695
+ function describeAction(action) {
1696
+ switch (action.action) {
1697
+ case "click":
1698
+ return `Click on "${action.targetDescription}"`;
1699
+ case "doubleClick":
1700
+ return `Double-click on "${action.targetDescription}"`;
1701
+ case "rightClick":
1702
+ return `Right-click on "${action.targetDescription}"`;
1703
+ case "type":
1704
+ return `Type "${action.value}" into "${action.targetDescription}"`;
1705
+ case "select":
1706
+ return `Select "${action.value}" from "${action.targetDescription}"`;
1707
+ case "check":
1708
+ return `Check "${action.targetDescription}"`;
1709
+ case "uncheck":
1710
+ return `Uncheck "${action.targetDescription}"`;
1711
+ case "clear":
1712
+ return `Clear "${action.targetDescription}"`;
1713
+ case "hover":
1714
+ return `Hover over "${action.targetDescription}"`;
1715
+ case "focus":
1716
+ return `Focus on "${action.targetDescription}"`;
1717
+ case "scroll":
1718
+ if (action.scrollDirection) {
1719
+ return `Scroll ${action.scrollDirection}`;
1720
+ }
1721
+ return `Scroll to "${action.targetDescription}"`;
1722
+ case "wait":
1723
+ return `Wait for "${action.targetDescription}"${action.waitCondition ? ` to be ${action.waitCondition}` : ""}`;
1724
+ case "assert":
1725
+ return `Assert "${action.targetDescription}" is ${action.assertionType || "valid"}`;
1726
+ default:
1727
+ return `${action.action} on "${action.targetDescription}"`;
1728
+ }
1729
+ }
1730
+
1731
+ // src/ai/error-context.ts
1732
+ function getElementState(el) {
1733
+ if ("state" in el && el.state) {
1734
+ return el.state;
1735
+ }
1736
+ if ("getState" in el && typeof el.getState === "function") {
1737
+ try {
1738
+ return el.getState();
1739
+ } catch {
1740
+ return void 0;
1741
+ }
1742
+ }
1743
+ return void 0;
1744
+ }
1745
+ var ERROR_MESSAGES = {
1746
+ PARSE_ERROR: "Could not parse the natural language instruction",
1747
+ VALIDATION_ERROR: "The parsed action failed validation",
1748
+ ELEMENT_NOT_FOUND: "No element matching the description could be found",
1749
+ ELEMENT_NOT_VISIBLE: "The element exists but is not visible",
1750
+ ELEMENT_DISABLED: "The element is disabled and cannot be interacted with",
1751
+ ELEMENT_BLOCKED: "The element is blocked by another element",
1752
+ MULTIPLE_ELEMENTS: "Multiple elements match the description",
1753
+ LOW_CONFIDENCE: "The best match has low confidence",
1754
+ AMBIGUOUS_MATCH: "Multiple elements match with similar confidence",
1755
+ ACTION_FAILED: "The action could not be completed",
1756
+ ACTION_TIMEOUT: "The action timed out waiting for a condition",
1757
+ UNSUPPORTED_ACTION: "The requested action is not supported",
1758
+ UNEXPECTED_STATE: "The element is in an unexpected state",
1759
+ STALE_ELEMENT: "The element is no longer attached to the DOM",
1760
+ PAGE_LOAD_ERROR: "The page failed to load correctly",
1761
+ NAVIGATION_ERROR: "Navigation to the target page failed"
1762
+ };
1763
+ var ERROR_SUGGESTIONS = {
1764
+ PARSE_ERROR: [
1765
+ {
1766
+ action: 'Use a simpler instruction format like "click Submit button"',
1767
+ confidence: 0.8,
1768
+ priority: 1
1769
+ },
1770
+ {
1771
+ action: "Use specific element names visible on the page",
1772
+ confidence: 0.7,
1773
+ priority: 2
1774
+ }
1775
+ ],
1776
+ VALIDATION_ERROR: [
1777
+ {
1778
+ action: "Provide required parameters for the action",
1779
+ confidence: 0.9,
1780
+ priority: 1
1781
+ },
1782
+ {
1783
+ action: "Check the instruction format",
1784
+ confidence: 0.7,
1785
+ priority: 2
1786
+ }
1787
+ ],
1788
+ ELEMENT_NOT_FOUND: [
1789
+ {
1790
+ action: "Wait for the page to fully load",
1791
+ command: "wait for page to load",
1792
+ confidence: 0.7,
1793
+ priority: 1
1794
+ },
1795
+ {
1796
+ action: "Use a different description for the element",
1797
+ confidence: 0.8,
1798
+ priority: 2
1799
+ },
1800
+ {
1801
+ action: "Scroll the page to reveal the element",
1802
+ command: "scroll down",
1803
+ confidence: 0.6,
1804
+ priority: 3
1805
+ }
1806
+ ],
1807
+ ELEMENT_NOT_VISIBLE: [
1808
+ {
1809
+ action: "Scroll to make the element visible",
1810
+ command: "scroll to element",
1811
+ confidence: 0.9,
1812
+ priority: 1
1813
+ },
1814
+ {
1815
+ action: "Close any overlaying elements",
1816
+ confidence: 0.7,
1817
+ priority: 2
1818
+ },
1819
+ {
1820
+ action: "Wait for loading to complete",
1821
+ command: "wait for loading",
1822
+ confidence: 0.6,
1823
+ priority: 3
1824
+ }
1825
+ ],
1826
+ ELEMENT_DISABLED: [
1827
+ {
1828
+ action: "Fill in required fields first",
1829
+ confidence: 0.8,
1830
+ priority: 1
1831
+ },
1832
+ {
1833
+ action: "Complete prerequisite steps",
1834
+ confidence: 0.7,
1835
+ priority: 2
1836
+ },
1837
+ {
1838
+ action: "Wait for the element to become enabled",
1839
+ command: "wait for element to be enabled",
1840
+ confidence: 0.6,
1841
+ priority: 3
1842
+ }
1843
+ ],
1844
+ ELEMENT_BLOCKED: [
1845
+ {
1846
+ action: "Close the modal or popup",
1847
+ command: "click close button",
1848
+ confidence: 0.9,
1849
+ priority: 1
1850
+ },
1851
+ {
1852
+ action: "Dismiss the overlay",
1853
+ confidence: 0.8,
1854
+ priority: 2
1855
+ },
1856
+ {
1857
+ action: "Wait for the blocking element to disappear",
1858
+ confidence: 0.6,
1859
+ priority: 3
1860
+ }
1861
+ ],
1862
+ MULTIPLE_ELEMENTS: [
1863
+ {
1864
+ action: "Use a more specific description",
1865
+ confidence: 0.9,
1866
+ priority: 1
1867
+ },
1868
+ {
1869
+ action: "Include the element position (first, second, etc.)",
1870
+ confidence: 0.8,
1871
+ priority: 2
1872
+ },
1873
+ {
1874
+ action: "Use the element ID directly",
1875
+ confidence: 0.7,
1876
+ priority: 3
1877
+ }
1878
+ ],
1879
+ LOW_CONFIDENCE: [
1880
+ {
1881
+ action: "Use the exact text shown on the element",
1882
+ confidence: 0.9,
1883
+ priority: 1
1884
+ },
1885
+ {
1886
+ action: "Lower the confidence threshold if the match is correct",
1887
+ confidence: 0.7,
1888
+ priority: 2
1889
+ },
1890
+ {
1891
+ action: "Try a different way to describe the element",
1892
+ confidence: 0.6,
1893
+ priority: 3
1894
+ }
1895
+ ],
1896
+ AMBIGUOUS_MATCH: [
1897
+ {
1898
+ action: "Be more specific about which element you mean",
1899
+ confidence: 0.9,
1900
+ priority: 1
1901
+ },
1902
+ {
1903
+ action: "Include the section or form name",
1904
+ confidence: 0.8,
1905
+ priority: 2
1906
+ }
1907
+ ],
1908
+ ACTION_FAILED: [
1909
+ {
1910
+ action: "Check if the element is interactable",
1911
+ confidence: 0.7,
1912
+ priority: 1
1913
+ },
1914
+ {
1915
+ action: "Wait and retry the action",
1916
+ command: "wait 1 second then retry",
1917
+ confidence: 0.6,
1918
+ priority: 2
1919
+ }
1920
+ ],
1921
+ ACTION_TIMEOUT: [
1922
+ {
1923
+ action: "Increase the timeout duration",
1924
+ confidence: 0.8,
1925
+ priority: 1
1926
+ },
1927
+ {
1928
+ action: "Check if the condition can ever be met",
1929
+ confidence: 0.7,
1930
+ priority: 2
1931
+ }
1932
+ ],
1933
+ UNSUPPORTED_ACTION: [
1934
+ {
1935
+ action: "Use a different action type",
1936
+ confidence: 0.9,
1937
+ priority: 1
1938
+ },
1939
+ {
1940
+ action: "Break down into simpler actions",
1941
+ confidence: 0.7,
1942
+ priority: 2
1943
+ }
1944
+ ],
1945
+ UNEXPECTED_STATE: [
1946
+ {
1947
+ action: "Refresh the page state",
1948
+ command: "refresh",
1949
+ confidence: 0.7,
1950
+ priority: 1
1951
+ },
1952
+ {
1953
+ action: "Wait for state to stabilize",
1954
+ command: "wait 2 seconds",
1955
+ confidence: 0.6,
1956
+ priority: 2
1957
+ }
1958
+ ],
1959
+ STALE_ELEMENT: [
1960
+ {
1961
+ action: "Re-find the element",
1962
+ confidence: 0.9,
1963
+ priority: 1
1964
+ },
1965
+ {
1966
+ action: "Wait for page to stabilize",
1967
+ command: "wait 1 second",
1968
+ confidence: 0.7,
1969
+ priority: 2
1970
+ }
1971
+ ],
1972
+ PAGE_LOAD_ERROR: [
1973
+ {
1974
+ action: "Refresh the page",
1975
+ command: "refresh page",
1976
+ confidence: 0.8,
1977
+ priority: 1
1978
+ },
1979
+ {
1980
+ action: "Check network connectivity",
1981
+ confidence: 0.6,
1982
+ priority: 2
1983
+ }
1984
+ ],
1985
+ NAVIGATION_ERROR: [
1986
+ {
1987
+ action: "Try the navigation again",
1988
+ confidence: 0.7,
1989
+ priority: 1
1990
+ },
1991
+ {
1992
+ action: "Check if the URL is correct",
1993
+ confidence: 0.6,
1994
+ priority: 2
1995
+ }
1996
+ ]
1997
+ };
1998
+ function createErrorContext(errorCode, attemptedAction, availableElements, searchCriteria, nearestMatch) {
1999
+ const message = ERROR_MESSAGES[errorCode] || "An unknown error occurred";
2000
+ const baseSuggestions = ERROR_SUGGESTIONS[errorCode] || [];
2001
+ const possibleBlockers = detectPossibleBlockers(availableElements);
2002
+ const visibleElements = availableElements.filter((el) => {
2003
+ const state = getElementState(el);
2004
+ return state?.visible ?? false;
2005
+ }).length;
2006
+ const suggestions = enhanceSuggestions(
2007
+ baseSuggestions,
2008
+ errorCode,
2009
+ nearestMatch,
2010
+ possibleBlockers
2011
+ );
2012
+ return {
2013
+ code: errorCode,
2014
+ message,
2015
+ attemptedAction,
2016
+ searchCriteria,
2017
+ searchResults: {
2018
+ candidatesFound: availableElements.length,
2019
+ nearestMatch: nearestMatch ? {
2020
+ element: nearestMatch.element,
2021
+ confidence: nearestMatch.confidence,
2022
+ whyNotSelected: determineWhyNotSelected(errorCode, nearestMatch)
2023
+ } : void 0
2024
+ },
2025
+ pageContext: {
2026
+ url: typeof window !== "undefined" ? window.location.href : "",
2027
+ title: typeof document !== "undefined" ? document.title : "",
2028
+ visibleElements,
2029
+ possibleBlockers
2030
+ },
2031
+ suggestions,
2032
+ timestamp: Date.now()
2033
+ };
2034
+ }
2035
+ function detectPossibleBlockers(elements) {
2036
+ const blockers = [];
2037
+ for (const el of elements) {
2038
+ const state = getElementState(el);
2039
+ if (!state) continue;
2040
+ if (el.type === "dialog" && state.visible) {
2041
+ blockers.push(`Modal dialog: ${el.id}`);
2042
+ }
2043
+ if (state.computedStyles?.pointerEvents === "none") {
2044
+ continue;
2045
+ }
2046
+ }
2047
+ return blockers;
2048
+ }
2049
+ function enhanceSuggestions(baseSuggestions, errorCode, nearestMatch, possibleBlockers) {
2050
+ const suggestions = [...baseSuggestions];
2051
+ if (possibleBlockers && possibleBlockers.length > 0) {
2052
+ suggestions.unshift({
2053
+ action: `Close the blocking element: ${possibleBlockers[0]}`,
2054
+ command: "click close button",
2055
+ confidence: 0.85,
2056
+ priority: 0
2057
+ });
2058
+ }
2059
+ if (nearestMatch && errorCode === "LOW_CONFIDENCE") {
2060
+ suggestions.unshift({
2061
+ action: `Did you mean: "${nearestMatch.element.description}"?`,
2062
+ command: `click "${nearestMatch.element.description}"`,
2063
+ confidence: nearestMatch.confidence,
2064
+ priority: 0
2065
+ });
2066
+ }
2067
+ suggestions.sort((a, b) => a.priority - b.priority);
2068
+ return suggestions;
2069
+ }
2070
+ function determineWhyNotSelected(errorCode, nearestMatch) {
2071
+ switch (errorCode) {
2072
+ case "LOW_CONFIDENCE":
2073
+ return `Confidence (${(nearestMatch.confidence * 100).toFixed(0)}%) below threshold`;
2074
+ case "ELEMENT_NOT_VISIBLE":
2075
+ return "Element is not visible";
2076
+ case "ELEMENT_DISABLED":
2077
+ return "Element is disabled";
2078
+ case "AMBIGUOUS_MATCH":
2079
+ return "Multiple elements with similar confidence";
2080
+ default:
2081
+ return "Did not meet selection criteria";
2082
+ }
2083
+ }
2084
+
2085
+ // src/ai/nl-action-executor.ts
2086
+ var DEFAULT_EXECUTOR_CONFIG = {
2087
+ defaultConfidenceThreshold: 0.7,
2088
+ defaultTimeout: 5e3,
2089
+ maxAlternatives: 3,
2090
+ verbose: false
2091
+ };
2092
+ var NLActionExecutor = class {
2093
+ constructor(config = {}) {
2094
+ this.actionExecutor = null;
2095
+ this.elements = [];
2096
+ this.config = { ...DEFAULT_EXECUTOR_CONFIG, ...config };
2097
+ this.searchEngine = new SearchEngine(this.config.searchConfig);
2098
+ }
2099
+ /**
2100
+ * Set the action executor for performing DOM actions
2101
+ */
2102
+ setActionExecutor(executor) {
2103
+ this.actionExecutor = executor;
2104
+ }
2105
+ /**
2106
+ * Update available elements for search
2107
+ */
2108
+ updateElements(elements) {
2109
+ this.elements = elements;
2110
+ this.searchEngine.updateElements(elements);
2111
+ }
2112
+ /**
2113
+ * Execute a natural language instruction
2114
+ */
2115
+ async execute(request) {
2116
+ const startTime = performance.now();
2117
+ const threshold = request.confidenceThreshold ?? this.config.defaultConfidenceThreshold;
2118
+ const parsed = parseNLInstruction(request.instruction);
2119
+ if (!parsed) {
2120
+ return this.createFailureResponse(
2121
+ startTime,
2122
+ "PARSE_ERROR",
2123
+ `Could not parse instruction: "${request.instruction}"`,
2124
+ request.instruction,
2125
+ [],
2126
+ threshold
2127
+ );
2128
+ }
2129
+ const validation = validateParsedAction(parsed);
2130
+ if (!validation.valid) {
2131
+ return this.createFailureResponse(
2132
+ startTime,
2133
+ "VALIDATION_ERROR",
2134
+ validation.errors.join("; "),
2135
+ request.instruction,
2136
+ [],
2137
+ threshold
2138
+ );
2139
+ }
2140
+ const searchCriteria = this.buildSearchCriteria(parsed);
2141
+ const searchResponse = this.searchEngine.search(searchCriteria);
2142
+ if (!searchResponse.bestMatch) {
2143
+ return this.createFailureResponse(
2144
+ startTime,
2145
+ "ELEMENT_NOT_FOUND",
2146
+ `Could not find element matching: "${parsed.targetDescription}"`,
2147
+ request.instruction,
2148
+ searchResponse.results,
2149
+ threshold,
2150
+ searchCriteria
2151
+ );
2152
+ }
2153
+ if (searchResponse.bestMatch.confidence < threshold) {
2154
+ const alternatives = searchResponse.results.slice(0, this.config.maxAlternatives);
2155
+ return this.createFailureResponse(
2156
+ startTime,
2157
+ "LOW_CONFIDENCE",
2158
+ `Best match confidence (${(searchResponse.bestMatch.confidence * 100).toFixed(0)}%) is below threshold (${(threshold * 100).toFixed(0)}%)`,
2159
+ request.instruction,
2160
+ alternatives,
2161
+ threshold,
2162
+ searchCriteria,
2163
+ searchResponse.bestMatch
2164
+ );
2165
+ }
2166
+ try {
2167
+ const result = await this.performAction(
2168
+ parsed,
2169
+ searchResponse.bestMatch.element,
2170
+ request.timeout ?? this.config.defaultTimeout
2171
+ );
2172
+ return {
2173
+ success: true,
2174
+ executedAction: describeAction(parsed),
2175
+ elementUsed: searchResponse.bestMatch.element,
2176
+ confidence: searchResponse.bestMatch.confidence,
2177
+ elementState: result.elementState,
2178
+ durationMs: performance.now() - startTime,
2179
+ timestamp: Date.now()
2180
+ };
2181
+ } catch (error2) {
2182
+ const errorMessage = error2 instanceof Error ? error2.message : String(error2);
2183
+ const alternatives = searchResponse.results.filter((r) => r !== searchResponse.bestMatch).slice(0, this.config.maxAlternatives);
2184
+ return this.createFailureResponse(
2185
+ startTime,
2186
+ "ACTION_FAILED",
2187
+ errorMessage,
2188
+ request.instruction,
2189
+ alternatives,
2190
+ threshold,
2191
+ searchCriteria,
2192
+ searchResponse.bestMatch
2193
+ );
2194
+ }
2195
+ }
2196
+ /**
2197
+ * Execute a parsed action directly (skip parsing)
2198
+ */
2199
+ async executeParsed(parsed, threshold) {
2200
+ const startTime = performance.now();
2201
+ const confidenceThreshold = threshold ?? this.config.defaultConfidenceThreshold;
2202
+ const searchCriteria = this.buildSearchCriteria(parsed);
2203
+ const searchResponse = this.searchEngine.search(searchCriteria);
2204
+ if (!searchResponse.bestMatch) {
2205
+ return this.createFailureResponse(
2206
+ startTime,
2207
+ "ELEMENT_NOT_FOUND",
2208
+ `Could not find element: "${parsed.targetDescription}"`,
2209
+ parsed.rawInstruction,
2210
+ [],
2211
+ confidenceThreshold,
2212
+ searchCriteria
2213
+ );
2214
+ }
2215
+ if (searchResponse.bestMatch.confidence < confidenceThreshold) {
2216
+ return this.createFailureResponse(
2217
+ startTime,
2218
+ "LOW_CONFIDENCE",
2219
+ `Best match confidence too low`,
2220
+ parsed.rawInstruction,
2221
+ searchResponse.results.slice(0, this.config.maxAlternatives),
2222
+ confidenceThreshold,
2223
+ searchCriteria,
2224
+ searchResponse.bestMatch
2225
+ );
2226
+ }
2227
+ try {
2228
+ const result = await this.performAction(
2229
+ parsed,
2230
+ searchResponse.bestMatch.element,
2231
+ this.config.defaultTimeout
2232
+ );
2233
+ return {
2234
+ success: true,
2235
+ executedAction: describeAction(parsed),
2236
+ elementUsed: searchResponse.bestMatch.element,
2237
+ confidence: searchResponse.bestMatch.confidence,
2238
+ elementState: result.elementState,
2239
+ durationMs: performance.now() - startTime,
2240
+ timestamp: Date.now()
2241
+ };
2242
+ } catch (error2) {
2243
+ return this.createFailureResponse(
2244
+ startTime,
2245
+ "ACTION_FAILED",
2246
+ error2 instanceof Error ? error2.message : String(error2),
2247
+ parsed.rawInstruction,
2248
+ searchResponse.results.filter((r) => r !== searchResponse.bestMatch).slice(0, this.config.maxAlternatives),
2249
+ confidenceThreshold,
2250
+ searchCriteria,
2251
+ searchResponse.bestMatch
2252
+ );
2253
+ }
2254
+ }
2255
+ /**
2256
+ * Build search criteria from a parsed action
2257
+ */
2258
+ buildSearchCriteria(parsed) {
2259
+ const criteria = {
2260
+ text: parsed.targetDescription,
2261
+ fuzzy: true,
2262
+ fuzzyThreshold: this.config.defaultConfidenceThreshold
2263
+ };
2264
+ switch (parsed.action) {
2265
+ case "click":
2266
+ case "doubleClick":
2267
+ case "rightClick":
2268
+ break;
2269
+ case "type":
2270
+ case "clear":
2271
+ criteria.type = "input";
2272
+ break;
2273
+ case "select":
2274
+ criteria.type = "select";
2275
+ break;
2276
+ case "check":
2277
+ case "uncheck":
2278
+ criteria.type = "checkbox";
2279
+ break;
2280
+ }
2281
+ return criteria;
2282
+ }
2283
+ /**
2284
+ * Perform the actual action on an element
2285
+ */
2286
+ async performAction(parsed, element, timeout) {
2287
+ if (!this.actionExecutor) {
2288
+ throw new Error("No action executor configured");
2289
+ }
2290
+ const actionMap = {
2291
+ click: "click",
2292
+ doubleClick: "doubleClick",
2293
+ rightClick: "rightClick",
2294
+ type: "type",
2295
+ select: "select",
2296
+ check: "check",
2297
+ uncheck: "uncheck",
2298
+ scroll: "scroll",
2299
+ wait: null,
2300
+ // Special handling
2301
+ assert: null,
2302
+ // Special handling
2303
+ hover: "hover",
2304
+ focus: "focus",
2305
+ clear: "clear"
2306
+ };
2307
+ const standardAction = actionMap[parsed.action];
2308
+ if (!standardAction) {
2309
+ if (parsed.action === "wait") {
2310
+ const waitResult = await this.actionExecutor.waitFor(element.id, {
2311
+ visible: true,
2312
+ timeout
2313
+ });
2314
+ if (!waitResult.met) {
2315
+ throw new Error(waitResult.error || "Wait condition not met");
2316
+ }
2317
+ return { elementState: waitResult.state };
2318
+ }
2319
+ if (parsed.action === "assert") {
2320
+ throw new Error("Use the assertions module for assert actions");
2321
+ }
2322
+ throw new Error(`Unsupported action: ${parsed.action}`);
2323
+ }
2324
+ const actionRequest = {
2325
+ action: standardAction,
2326
+ waitOptions: {
2327
+ visible: true,
2328
+ enabled: true,
2329
+ timeout
2330
+ }
2331
+ };
2332
+ if (standardAction === "type" && parsed.value) {
2333
+ actionRequest.params = { text: parsed.value };
2334
+ } else if (standardAction === "select" && parsed.value) {
2335
+ actionRequest.params = { value: parsed.value };
2336
+ } else if (standardAction === "scroll" && parsed.scrollDirection) {
2337
+ actionRequest.params = { direction: parsed.scrollDirection };
2338
+ }
2339
+ const response = await this.actionExecutor.executeAction(element.id, actionRequest);
2340
+ if (!response.success) {
2341
+ throw new Error(response.error || "Action failed");
2342
+ }
2343
+ return { elementState: response.elementState };
2344
+ }
2345
+ /**
2346
+ * Create a failure response with suggestions
2347
+ */
2348
+ createFailureResponse(startTime, errorCode, errorMessage, instruction, alternatives, threshold, searchCriteria, nearestMatch) {
2349
+ const suggestions = this.generateSuggestions(
2350
+ errorCode,
2351
+ instruction,
2352
+ alternatives,
2353
+ nearestMatch
2354
+ );
2355
+ const dummyElement = nearestMatch?.element || {
2356
+ id: "not-found",
2357
+ type: "unknown",
2358
+ tagName: "unknown",
2359
+ actions: [],
2360
+ state: {
2361
+ visible: false,
2362
+ enabled: false,
2363
+ focused: false,
2364
+ rect: { x: 0, y: 0, width: 0, height: 0, top: 0, right: 0, bottom: 0, left: 0 }
2365
+ },
2366
+ registered: false,
2367
+ description: "Element not found",
2368
+ aliases: [],
2369
+ suggestedActions: []
2370
+ };
2371
+ return {
2372
+ success: false,
2373
+ executedAction: instruction,
2374
+ elementUsed: dummyElement,
2375
+ confidence: nearestMatch?.confidence || 0,
2376
+ elementState: dummyElement.state,
2377
+ durationMs: performance.now() - startTime,
2378
+ timestamp: Date.now(),
2379
+ error: errorMessage,
2380
+ errorCode,
2381
+ suggestions,
2382
+ alternatives: alternatives.slice(0, this.config.maxAlternatives)
2383
+ };
2384
+ }
2385
+ /**
2386
+ * Generate recovery suggestions
2387
+ */
2388
+ generateSuggestions(errorCode, instruction, alternatives, nearestMatch) {
2389
+ const suggestions = [];
2390
+ switch (errorCode) {
2391
+ case "PARSE_ERROR":
2392
+ suggestions.push('Try using a simpler phrase like "click Submit button"');
2393
+ suggestions.push('Ensure the instruction follows patterns like "click X" or "type Y into X"');
2394
+ break;
2395
+ case "ELEMENT_NOT_FOUND":
2396
+ if (alternatives.length > 0) {
2397
+ suggestions.push(`Did you mean: "${alternatives[0].element.description}"?`);
2398
+ }
2399
+ suggestions.push("Check if the element is visible on the page");
2400
+ suggestions.push("Try using a more specific description");
2401
+ break;
2402
+ case "LOW_CONFIDENCE":
2403
+ if (nearestMatch) {
2404
+ suggestions.push(
2405
+ `Found "${nearestMatch.element.description}" with ${(nearestMatch.confidence * 100).toFixed(0)}% confidence`
2406
+ );
2407
+ }
2408
+ suggestions.push("Try using the exact text shown on the element");
2409
+ suggestions.push("Lower the confidence threshold if this match is correct");
2410
+ break;
2411
+ case "ACTION_FAILED":
2412
+ suggestions.push("Check if the element is enabled");
2413
+ suggestions.push("Wait for any loading to complete");
2414
+ suggestions.push("Ensure no modal or overlay is blocking the element");
2415
+ break;
2416
+ default:
2417
+ suggestions.push("Try a different approach or check the page state");
2418
+ }
2419
+ return suggestions;
2420
+ }
2421
+ /**
2422
+ * Get rich error context for debugging
2423
+ */
2424
+ getErrorContext(errorCode, instruction, searchCriteria, nearestMatch) {
2425
+ return createErrorContext(
2426
+ errorCode,
2427
+ instruction,
2428
+ this.elements,
2429
+ searchCriteria,
2430
+ nearestMatch
2431
+ );
2432
+ }
2433
+ };
2434
+
2435
+ // src/ai/assertions.ts
2436
+ var DEFAULT_ASSERTION_CONFIG = {
2437
+ defaultTimeout: 5e3,
2438
+ pollInterval: 100,
2439
+ fuzzyThreshold: 0.7,
2440
+ includeSuggestions: true
2441
+ };
2442
+ var AssertionExecutor = class {
2443
+ constructor(config = {}) {
2444
+ this.elements = [];
2445
+ this.config = { ...DEFAULT_ASSERTION_CONFIG, ...config };
2446
+ this.searchEngine = new SearchEngine({ fuzzyThreshold: this.config.fuzzyThreshold });
2447
+ }
2448
+ /**
2449
+ * Update available elements for assertions
2450
+ */
2451
+ updateElements(elements) {
2452
+ this.elements = elements;
2453
+ this.searchEngine.updateElements(elements);
2454
+ }
2455
+ /**
2456
+ * Execute a single assertion
2457
+ */
2458
+ async assert(request) {
2459
+ const startTime = performance.now();
2460
+ const timeout = request.timeout ?? this.config.defaultTimeout;
2461
+ const element = await this.findElement(request.target, request.fuzzy !== false);
2462
+ if (!element && request.type !== "notExists") {
2463
+ return this.createResult(
2464
+ false,
2465
+ typeof request.target === "string" ? request.target : JSON.stringify(request.target),
2466
+ "element not found",
2467
+ request.type === "exists" ? true : request.expected,
2468
+ null,
2469
+ "Element could not be found",
2470
+ this.config.includeSuggestions ? "Check if the element exists and is properly labeled" : void 0,
2471
+ startTime
2472
+ );
2473
+ }
2474
+ return this.executeAssertion(request, element, timeout, startTime);
2475
+ }
2476
+ /**
2477
+ * Execute multiple assertions
2478
+ */
2479
+ async assertBatch(request) {
2480
+ const startTime = performance.now();
2481
+ const results = [];
2482
+ let passedCount = 0;
2483
+ let failedCount = 0;
2484
+ for (const assertion of request.assertions) {
2485
+ const result = await this.assert(assertion);
2486
+ results.push(result);
2487
+ if (result.passed) {
2488
+ passedCount++;
2489
+ } else {
2490
+ failedCount++;
2491
+ if (request.stopOnFailure) {
2492
+ break;
2493
+ }
2494
+ }
2495
+ }
2496
+ const passed = request.mode === "all" ? failedCount === 0 : passedCount > 0;
2497
+ return {
2498
+ passed,
2499
+ results,
2500
+ passedCount,
2501
+ failedCount,
2502
+ durationMs: performance.now() - startTime,
2503
+ timestamp: Date.now()
2504
+ };
2505
+ }
2506
+ /**
2507
+ * Convenience method: assert element is visible
2508
+ */
2509
+ async assertVisible(target, timeout) {
2510
+ return this.assert({ target, type: "visible", timeout });
2511
+ }
2512
+ /**
2513
+ * Convenience method: assert element is hidden
2514
+ */
2515
+ async assertHidden(target, timeout) {
2516
+ return this.assert({ target, type: "hidden", timeout });
2517
+ }
2518
+ /**
2519
+ * Convenience method: assert element is enabled
2520
+ */
2521
+ async assertEnabled(target, timeout) {
2522
+ return this.assert({ target, type: "enabled", timeout });
2523
+ }
2524
+ /**
2525
+ * Convenience method: assert element is disabled
2526
+ */
2527
+ async assertDisabled(target, timeout) {
2528
+ return this.assert({ target, type: "disabled", timeout });
2529
+ }
2530
+ /**
2531
+ * Convenience method: assert element has text
2532
+ */
2533
+ async assertHasText(target, text, timeout) {
2534
+ return this.assert({ target, type: "hasText", expected: text, timeout });
2535
+ }
2536
+ /**
2537
+ * Convenience method: assert element contains text
2538
+ */
2539
+ async assertContainsText(target, text, timeout) {
2540
+ return this.assert({ target, type: "containsText", expected: text, timeout });
2541
+ }
2542
+ /**
2543
+ * Convenience method: assert element has value
2544
+ */
2545
+ async assertHasValue(target, value, timeout) {
2546
+ return this.assert({ target, type: "hasValue", expected: value, timeout });
2547
+ }
2548
+ /**
2549
+ * Convenience method: assert element exists
2550
+ */
2551
+ async assertExists(target, timeout) {
2552
+ return this.assert({ target, type: "exists", timeout });
2553
+ }
2554
+ /**
2555
+ * Convenience method: assert element does not exist
2556
+ */
2557
+ async assertNotExists(target, timeout) {
2558
+ return this.assert({ target, type: "notExists", timeout });
2559
+ }
2560
+ /**
2561
+ * Convenience method: assert checkbox is checked
2562
+ */
2563
+ async assertChecked(target, timeout) {
2564
+ return this.assert({ target, type: "checked", timeout });
2565
+ }
2566
+ /**
2567
+ * Convenience method: assert checkbox is unchecked
2568
+ */
2569
+ async assertUnchecked(target, timeout) {
2570
+ return this.assert({ target, type: "unchecked", timeout });
2571
+ }
2572
+ /**
2573
+ * Convenience method: assert element count
2574
+ */
2575
+ async assertCount(target, expectedCount, timeout) {
2576
+ return this.assert({ target, type: "count", expected: expectedCount, timeout });
2577
+ }
2578
+ /**
2579
+ * Find element by target (string or criteria)
2580
+ */
2581
+ async findElement(target, fuzzy = true) {
2582
+ const criteria = typeof target === "string" ? { text: target, fuzzy } : { ...target, fuzzy };
2583
+ const searchResult = this.searchEngine.findBest(criteria);
2584
+ if (searchResult && searchResult.confidence >= this.config.fuzzyThreshold) {
2585
+ return searchResult.element;
2586
+ }
2587
+ return null;
2588
+ }
2589
+ /**
2590
+ * Execute the actual assertion
2591
+ */
2592
+ async executeAssertion(request, element, timeout, startTime) {
2593
+ const targetStr = typeof request.target === "string" ? request.target : JSON.stringify(request.target);
2594
+ const elementDescription = element?.description || targetStr;
2595
+ switch (request.type) {
2596
+ case "visible":
2597
+ return this.assertVisibility(element, true, elementDescription, request.message, startTime);
2598
+ case "hidden":
2599
+ return this.assertVisibility(element, false, elementDescription, request.message, startTime);
2600
+ case "enabled":
2601
+ return this.assertEnabledState(element, true, elementDescription, request.message, startTime);
2602
+ case "disabled":
2603
+ return this.assertEnabledState(element, false, elementDescription, request.message, startTime);
2604
+ case "focused":
2605
+ return this.assertFocused(element, elementDescription, request.message, startTime);
2606
+ case "checked":
2607
+ return this.assertCheckedState(element, true, elementDescription, request.message, startTime);
2608
+ case "unchecked":
2609
+ return this.assertCheckedState(element, false, elementDescription, request.message, startTime);
2610
+ case "hasText":
2611
+ return this.assertTextMatch(
2612
+ element,
2613
+ request.expected,
2614
+ true,
2615
+ elementDescription,
2616
+ request.message,
2617
+ startTime
2618
+ );
2619
+ case "containsText":
2620
+ return this.assertTextMatch(
2621
+ element,
2622
+ request.expected,
2623
+ false,
2624
+ elementDescription,
2625
+ request.message,
2626
+ startTime
2627
+ );
2628
+ case "hasValue":
2629
+ return this.assertValue(
2630
+ element,
2631
+ request.expected,
2632
+ elementDescription,
2633
+ request.message,
2634
+ startTime
2635
+ );
2636
+ case "exists":
2637
+ return this.createResult(
2638
+ element !== null,
2639
+ targetStr,
2640
+ elementDescription,
2641
+ true,
2642
+ element !== null,
2643
+ element === null ? "Element does not exist" : void 0,
2644
+ void 0,
2645
+ startTime,
2646
+ element?.state
2647
+ );
2648
+ case "notExists":
2649
+ return this.createResult(
2650
+ element === null,
2651
+ targetStr,
2652
+ elementDescription,
2653
+ false,
2654
+ element === null,
2655
+ element !== null ? "Element exists but should not" : void 0,
2656
+ void 0,
2657
+ startTime,
2658
+ element?.state
2659
+ );
2660
+ case "count":
2661
+ return this.assertElementCount(
2662
+ request.target,
2663
+ request.expected,
2664
+ targetStr,
2665
+ request.message,
2666
+ startTime
2667
+ );
2668
+ case "attribute":
2669
+ return this.assertAttribute(
2670
+ element,
2671
+ request.attributeName,
2672
+ request.expected,
2673
+ elementDescription,
2674
+ request.message,
2675
+ startTime
2676
+ );
2677
+ case "hasClass":
2678
+ return this.assertHasClass(
2679
+ element,
2680
+ request.expected,
2681
+ elementDescription,
2682
+ request.message,
2683
+ startTime
2684
+ );
2685
+ case "cssProperty":
2686
+ return this.assertCssProperty(
2687
+ element,
2688
+ request.propertyName,
2689
+ request.expected,
2690
+ elementDescription,
2691
+ request.message,
2692
+ startTime
2693
+ );
2694
+ default:
2695
+ return this.createResult(
2696
+ false,
2697
+ targetStr,
2698
+ elementDescription,
2699
+ void 0,
2700
+ void 0,
2701
+ `Unknown assertion type: ${request.type}`,
2702
+ void 0,
2703
+ startTime
2704
+ );
2705
+ }
2706
+ }
2707
+ /**
2708
+ * Assert visibility state
2709
+ */
2710
+ assertVisibility(element, expectedVisible, description, message, startTime = performance.now()) {
2711
+ const isVisible = element.state.visible;
2712
+ const passed = isVisible === expectedVisible;
2713
+ return this.createResult(
2714
+ passed,
2715
+ element.id,
2716
+ description,
2717
+ expectedVisible,
2718
+ isVisible,
2719
+ passed ? void 0 : message || `Element is ${isVisible ? "visible" : "hidden"} but expected ${expectedVisible ? "visible" : "hidden"}`,
2720
+ passed ? void 0 : "Check if element is covered by another element or has display:none",
2721
+ startTime,
2722
+ element.state
2723
+ );
2724
+ }
2725
+ /**
2726
+ * Assert enabled state
2727
+ */
2728
+ assertEnabledState(element, expectedEnabled, description, message, startTime = performance.now()) {
2729
+ const isEnabled = element.state.enabled;
2730
+ const passed = isEnabled === expectedEnabled;
2731
+ return this.createResult(
2732
+ passed,
2733
+ element.id,
2734
+ description,
2735
+ expectedEnabled,
2736
+ isEnabled,
2737
+ passed ? void 0 : message || `Element is ${isEnabled ? "enabled" : "disabled"} but expected ${expectedEnabled ? "enabled" : "disabled"}`,
2738
+ passed ? void 0 : "Check if the element has a disabled attribute or aria-disabled",
2739
+ startTime,
2740
+ element.state
2741
+ );
2742
+ }
2743
+ /**
2744
+ * Assert focused state
2745
+ */
2746
+ assertFocused(element, description, message, startTime = performance.now()) {
2747
+ const isFocused = element.state.focused;
2748
+ return this.createResult(
2749
+ isFocused,
2750
+ element.id,
2751
+ description,
2752
+ true,
2753
+ isFocused,
2754
+ isFocused ? void 0 : message || "Element is not focused",
2755
+ isFocused ? void 0 : "Click or focus the element first",
2756
+ startTime,
2757
+ element.state
2758
+ );
2759
+ }
2760
+ /**
2761
+ * Assert checked state
2762
+ */
2763
+ assertCheckedState(element, expectedChecked, description, message, startTime = performance.now()) {
2764
+ const isChecked = element.state.checked ?? false;
2765
+ const passed = isChecked === expectedChecked;
2766
+ return this.createResult(
2767
+ passed,
2768
+ element.id,
2769
+ description,
2770
+ expectedChecked,
2771
+ isChecked,
2772
+ passed ? void 0 : message || `Element is ${isChecked ? "checked" : "unchecked"} but expected ${expectedChecked ? "checked" : "unchecked"}`,
2773
+ passed ? void 0 : "Click the checkbox to change its state",
2774
+ startTime,
2775
+ element.state
2776
+ );
2777
+ }
2778
+ /**
2779
+ * Assert text content
2780
+ */
2781
+ assertTextMatch(element, expectedText, exact, description, message, startTime = performance.now()) {
2782
+ const actualText = element.state.textContent || "";
2783
+ const passed = exact ? actualText === expectedText : actualText.includes(expectedText);
2784
+ return this.createResult(
2785
+ passed,
2786
+ element.id,
2787
+ description,
2788
+ expectedText,
2789
+ actualText,
2790
+ passed ? void 0 : message || (exact ? `Text "${actualText}" does not match expected "${expectedText}"` : `Text "${actualText}" does not contain "${expectedText}"`),
2791
+ passed ? void 0 : "Verify the element contains the expected text",
2792
+ startTime,
2793
+ element.state
2794
+ );
2795
+ }
2796
+ /**
2797
+ * Assert input value
2798
+ */
2799
+ assertValue(element, expectedValue, description, message, startTime = performance.now()) {
2800
+ const actualValue = element.state.value || "";
2801
+ const passed = actualValue === expectedValue;
2802
+ return this.createResult(
2803
+ passed,
2804
+ element.id,
2805
+ description,
2806
+ expectedValue,
2807
+ actualValue,
2808
+ passed ? void 0 : message || `Value "${actualValue}" does not match expected "${expectedValue}"`,
2809
+ passed ? void 0 : "Type the expected value into the input",
2810
+ startTime,
2811
+ element.state
2812
+ );
2813
+ }
2814
+ /**
2815
+ * Assert element count
2816
+ */
2817
+ assertElementCount(criteria, expectedCount, targetStr, message, startTime = performance.now()) {
2818
+ const searchResponse = this.searchEngine.search(criteria);
2819
+ const actualCount = searchResponse.results.length;
2820
+ const passed = actualCount === expectedCount;
2821
+ return this.createResult(
2822
+ passed,
2823
+ targetStr,
2824
+ `${actualCount} elements matching criteria`,
2825
+ expectedCount,
2826
+ actualCount,
2827
+ passed ? void 0 : message || `Found ${actualCount} elements but expected ${expectedCount}`,
2828
+ passed ? void 0 : "Adjust search criteria or wait for elements to load",
2829
+ startTime
2830
+ );
2831
+ }
2832
+ /**
2833
+ * Assert attribute value (placeholder for DOM attribute assertions)
2834
+ */
2835
+ assertAttribute(element, attributeName, expectedValue, description, message, startTime = performance.now()) {
2836
+ let actualValue;
2837
+ switch (attributeName.toLowerCase()) {
2838
+ case "placeholder":
2839
+ actualValue = element.placeholder;
2840
+ break;
2841
+ case "title":
2842
+ actualValue = element.title;
2843
+ break;
2844
+ default:
2845
+ return this.createResult(
2846
+ false,
2847
+ element.id,
2848
+ description,
2849
+ expectedValue,
2850
+ void 0,
2851
+ `Cannot check attribute "${attributeName}" without DOM access`,
2852
+ "Use the server API to check element attributes",
2853
+ startTime,
2854
+ element.state
2855
+ );
2856
+ }
2857
+ const passed = actualValue === expectedValue;
2858
+ return this.createResult(
2859
+ passed,
2860
+ element.id,
2861
+ description,
2862
+ expectedValue,
2863
+ actualValue,
2864
+ passed ? void 0 : message || `Attribute "${attributeName}" is "${actualValue}" but expected "${expectedValue}"`,
2865
+ void 0,
2866
+ startTime,
2867
+ element.state
2868
+ );
2869
+ }
2870
+ /**
2871
+ * Assert element has CSS class
2872
+ */
2873
+ assertHasClass(element, className, description, message, startTime = performance.now()) {
2874
+ return this.createResult(
2875
+ false,
2876
+ element.id,
2877
+ description,
2878
+ className,
2879
+ void 0,
2880
+ "Cannot check CSS classes without DOM access",
2881
+ "Use the server API to check element classes",
2882
+ startTime,
2883
+ element.state
2884
+ );
2885
+ }
2886
+ /**
2887
+ * Assert CSS property value
2888
+ */
2889
+ assertCssProperty(element, propertyName, expectedValue, description, message, startTime = performance.now()) {
2890
+ const computedStyles = element.state.computedStyles;
2891
+ if (!computedStyles) {
2892
+ return this.createResult(
2893
+ false,
2894
+ element.id,
2895
+ description,
2896
+ expectedValue,
2897
+ void 0,
2898
+ "Computed styles not available",
2899
+ "Request element state with computed styles",
2900
+ startTime,
2901
+ element.state
2902
+ );
2903
+ }
2904
+ const styleKey = propertyName;
2905
+ const actualValue = computedStyles[styleKey];
2906
+ const passed = actualValue === expectedValue;
2907
+ return this.createResult(
2908
+ passed,
2909
+ element.id,
2910
+ description,
2911
+ expectedValue,
2912
+ actualValue,
2913
+ passed ? void 0 : message || `CSS property "${propertyName}" is "${actualValue}" but expected "${expectedValue}"`,
2914
+ void 0,
2915
+ startTime,
2916
+ element.state
2917
+ );
2918
+ }
2919
+ /**
2920
+ * Create an assertion result
2921
+ */
2922
+ createResult(passed, target, targetDescription, expected, actual, failureReason, suggestion, startTime = performance.now(), elementState) {
2923
+ return {
2924
+ passed,
2925
+ target,
2926
+ targetDescription,
2927
+ expected,
2928
+ actual,
2929
+ failureReason,
2930
+ suggestion: this.config.includeSuggestions ? suggestion : void 0,
2931
+ elementState,
2932
+ durationMs: performance.now() - startTime,
2933
+ timestamp: Date.now()
2934
+ };
2935
+ }
2936
+ };
2937
+
2938
+ // src/ai/semantic-snapshot.ts
2939
+ var DEFAULT_SNAPSHOT_CONFIG = {
2940
+ analyzeForms: true,
2941
+ detectModals: true,
2942
+ inferPageType: true,
2943
+ generateDescriptions: true,
2944
+ maxElements: 500
2945
+ };
2946
+ var SemanticSnapshotManager = class {
2947
+ constructor(config = {}) {
2948
+ this.history = [];
2949
+ this.maxHistorySize = 10;
2950
+ this.snapshotCounter = 0;
2951
+ this.config = { ...DEFAULT_SNAPSHOT_CONFIG, ...config };
2952
+ this.searchEngine = new SearchEngine();
2953
+ }
2954
+ /**
2955
+ * Create a semantic snapshot from a control snapshot
2956
+ */
2957
+ createSnapshot(controlSnapshot, pageContext) {
2958
+ const snapshotId = `snapshot-${++this.snapshotCounter}-${Date.now()}`;
2959
+ const aiElements = this.convertElements(controlSnapshot.elements);
2960
+ this.searchEngine.updateElements(aiElements);
2961
+ const fullPageContext = this.buildPageContext(aiElements, pageContext);
2962
+ const forms = this.config.analyzeForms ? this.analyzeForms(aiElements) : [];
2963
+ const modals = this.config.detectModals ? this.detectModals(aiElements) : [];
2964
+ const elementCounts = this.countElementTypes(aiElements);
2965
+ const summary = generatePageSummary(aiElements, fullPageContext);
2966
+ const focusedElement = aiElements.find((el) => el.state.focused)?.id;
2967
+ const snapshot = {
2968
+ timestamp: Date.now(),
2969
+ snapshotId,
2970
+ page: fullPageContext,
2971
+ elements: aiElements.slice(0, this.config.maxElements),
2972
+ forms,
2973
+ activeModals: modals,
2974
+ focusedElement,
2975
+ summary,
2976
+ elementCounts
2977
+ };
2978
+ this.addToHistory(snapshot);
2979
+ return snapshot;
2980
+ }
2981
+ /**
2982
+ * Get the last snapshot
2983
+ */
2984
+ getLastSnapshot() {
2985
+ if (this.history.length === 0) return null;
2986
+ return this.history[this.history.length - 1].snapshot;
2987
+ }
2988
+ /**
2989
+ * Get snapshot by ID
2990
+ */
2991
+ getSnapshot(snapshotId) {
2992
+ const entry = this.history.find((h) => h.snapshot.snapshotId === snapshotId);
2993
+ return entry?.snapshot || null;
2994
+ }
2995
+ /**
2996
+ * Get snapshot history
2997
+ */
2998
+ getHistory() {
2999
+ return this.history.map((h) => h.snapshot);
3000
+ }
3001
+ /**
3002
+ * Clear history
3003
+ */
3004
+ clearHistory() {
3005
+ this.history = [];
3006
+ }
3007
+ /**
3008
+ * Convert control snapshot elements to AI elements
3009
+ */
3010
+ convertElements(elements) {
3011
+ return elements.map((el) => this.convertElement(el));
3012
+ }
3013
+ /**
3014
+ * Convert a single element to AI element
3015
+ */
3016
+ convertElement(element) {
3017
+ const aliases = generateAliases({
3018
+ textContent: element.state.textContent,
3019
+ elementType: element.type,
3020
+ id: element.id,
3021
+ labelText: element.label
3022
+ });
3023
+ const description = this.config.generateDescriptions ? generateDescription({
3024
+ textContent: element.state.textContent,
3025
+ elementType: element.type,
3026
+ id: element.id,
3027
+ labelText: element.label
3028
+ }) : element.label || element.id;
3029
+ const purpose = generatePurpose({
3030
+ textContent: element.state.textContent,
3031
+ elementType: element.type
3032
+ });
3033
+ const suggestedActions = generateSuggestedActions({
3034
+ textContent: element.state.textContent,
3035
+ elementType: element.type
3036
+ });
3037
+ return {
3038
+ id: element.id,
3039
+ type: element.type,
3040
+ label: element.label,
3041
+ tagName: this.inferTagName(element.type),
3042
+ role: this.inferRole(element.type),
3043
+ accessibleName: element.label || element.state.textContent?.trim(),
3044
+ actions: element.actions,
3045
+ state: element.state,
3046
+ registered: true,
3047
+ description,
3048
+ aliases,
3049
+ purpose,
3050
+ suggestedActions,
3051
+ semanticType: this.inferSemanticType(element)
3052
+ };
3053
+ }
3054
+ /**
3055
+ * Build full page context
3056
+ */
3057
+ buildPageContext(elements, partial) {
3058
+ const url = partial?.url || (typeof window !== "undefined" ? window.location.href : "");
3059
+ const title = partial?.title || (typeof document !== "undefined" ? document.title : "");
3060
+ const pageType = this.config.inferPageType ? inferPageType(url, title, elements) : partial?.pageType || "unknown";
3061
+ const activeModals = elements.filter((el) => el.type === "dialog" && el.state.visible).map((el) => el.id);
3062
+ return {
3063
+ url,
3064
+ title,
3065
+ pageType,
3066
+ activeModals: partial?.activeModals || activeModals,
3067
+ focusedElement: partial?.focusedElement || elements.find((el) => el.state.focused)?.id,
3068
+ navigation: partial?.navigation
3069
+ };
3070
+ }
3071
+ /**
3072
+ * Analyze forms in the snapshot
3073
+ */
3074
+ analyzeForms(elements) {
3075
+ const forms = [];
3076
+ const formElements = elements.filter((el) => el.type === "form");
3077
+ if (formElements.length === 0) {
3078
+ const implicitForm = this.detectImplicitForm(elements);
3079
+ if (implicitForm) {
3080
+ forms.push(implicitForm);
3081
+ }
3082
+ } else {
3083
+ for (const form of formElements) {
3084
+ const formState = this.analyzeForm(form, elements);
3085
+ if (formState) {
3086
+ forms.push(formState);
3087
+ }
3088
+ }
3089
+ }
3090
+ return forms;
3091
+ }
3092
+ /**
3093
+ * Detect implicit form from inputs
3094
+ */
3095
+ detectImplicitForm(elements) {
3096
+ const inputs = elements.filter(
3097
+ (el) => el.type === "input" || el.type === "textarea" || el.type === "select" || el.type === "checkbox"
3098
+ );
3099
+ if (inputs.length === 0) return null;
3100
+ const submitButton = elements.find(
3101
+ (el) => el.type === "button" && el.state.visible && (el.semanticType === "submit-button" || el.state.textContent?.toLowerCase().match(/submit|save|send|continue/))
3102
+ );
3103
+ const fields = this.analyzeFormFields(inputs);
3104
+ const hasErrors = fields.some((f) => !f.valid);
3105
+ return {
3106
+ id: "implicit-form",
3107
+ purpose: this.inferFormPurpose(inputs),
3108
+ fields,
3109
+ isValid: !hasErrors,
3110
+ submitButton: submitButton?.id,
3111
+ isDirty: fields.some((f) => f.value !== "" && f.touched)
3112
+ };
3113
+ }
3114
+ /**
3115
+ * Analyze a specific form
3116
+ */
3117
+ analyzeForm(form, allElements) {
3118
+ const inputs = allElements.filter(
3119
+ (el) => (el.type === "input" || el.type === "textarea" || el.type === "select") && el.state.visible
3120
+ );
3121
+ const fields = this.analyzeFormFields(inputs);
3122
+ const hasErrors = fields.some((f) => !f.valid);
3123
+ const submitButton = allElements.find(
3124
+ (el) => el.type === "button" && el.state.visible && el.semanticType === "submit-button"
3125
+ );
3126
+ return {
3127
+ id: form.id,
3128
+ name: form.label,
3129
+ purpose: form.purpose,
3130
+ fields,
3131
+ isValid: !hasErrors,
3132
+ submitButton: submitButton?.id,
3133
+ isDirty: fields.some((f) => f.value !== "")
3134
+ };
3135
+ }
3136
+ /**
3137
+ * Analyze form fields
3138
+ */
3139
+ analyzeFormFields(inputs) {
3140
+ return inputs.map((input) => ({
3141
+ id: input.id,
3142
+ label: input.accessibleName || input.label || input.id,
3143
+ type: input.type,
3144
+ value: input.state.value || "",
3145
+ valid: true,
3146
+ // Would need validation state
3147
+ required: false,
3148
+ // Would need DOM access
3149
+ touched: input.state.focused || (input.state.value?.length || 0) > 0
3150
+ }));
3151
+ }
3152
+ /**
3153
+ * Detect modal dialogs
3154
+ */
3155
+ detectModals(elements) {
3156
+ const modals = [];
3157
+ const dialogElements = elements.filter(
3158
+ (el) => el.type === "dialog" && el.state.visible
3159
+ );
3160
+ for (const dialog of dialogElements) {
3161
+ const closeButton = elements.find(
3162
+ (el) => el.type === "button" && el.state.visible && (el.semanticType === "cancel-button" || el.state.textContent?.toLowerCase().match(/close|cancel|x|dismiss/))
3163
+ );
3164
+ const primaryAction = elements.find(
3165
+ (el) => el.type === "button" && el.state.visible && el.semanticType === "submit-button"
3166
+ );
3167
+ modals.push({
3168
+ id: dialog.id,
3169
+ title: dialog.accessibleName || dialog.label,
3170
+ type: this.inferModalType(dialog),
3171
+ blocking: true,
3172
+ // Assume dialogs are blocking
3173
+ closeButton: closeButton?.id,
3174
+ primaryAction: primaryAction?.id
3175
+ });
3176
+ }
3177
+ return modals;
3178
+ }
3179
+ /**
3180
+ * Infer modal type
3181
+ */
3182
+ inferModalType(dialog) {
3183
+ const text = (dialog.accessibleName || dialog.state.textContent || "").toLowerCase();
3184
+ if (text.includes("alert") || text.includes("warning") || text.includes("error")) {
3185
+ return "alert";
3186
+ }
3187
+ if (text.includes("confirm") || text.includes("are you sure")) {
3188
+ return "confirm";
3189
+ }
3190
+ if (text.includes("prompt") || text.includes("enter")) {
3191
+ return "prompt";
3192
+ }
3193
+ return "dialog";
3194
+ }
3195
+ /**
3196
+ * Count elements by type
3197
+ */
3198
+ countElementTypes(elements) {
3199
+ const counts = {};
3200
+ for (const el of elements) {
3201
+ const type = el.type.toLowerCase();
3202
+ counts[type] = (counts[type] || 0) + 1;
3203
+ }
3204
+ return counts;
3205
+ }
3206
+ /**
3207
+ * Infer form purpose from fields
3208
+ */
3209
+ inferFormPurpose(fields) {
3210
+ const labels = fields.map(
3211
+ (f) => (f.accessibleName || f.label || "").toLowerCase()
3212
+ );
3213
+ const allLabels = labels.join(" ");
3214
+ if (allLabels.includes("email") && allLabels.includes("password")) {
3215
+ if (allLabels.includes("confirm") || allLabels.includes("name")) {
3216
+ return "Registration";
3217
+ }
3218
+ return "Login";
3219
+ }
3220
+ if (allLabels.includes("search")) return "Search";
3221
+ if (allLabels.includes("address") || allLabels.includes("city")) return "Address";
3222
+ if (allLabels.includes("card") || allLabels.includes("payment")) return "Payment";
3223
+ if (allLabels.includes("contact") || allLabels.includes("message")) return "Contact";
3224
+ return "Form";
3225
+ }
3226
+ /**
3227
+ * Infer tag name from element type
3228
+ */
3229
+ inferTagName(type) {
3230
+ const typeMap = {
3231
+ button: "button",
3232
+ input: "input",
3233
+ textarea: "textarea",
3234
+ select: "select",
3235
+ checkbox: "input",
3236
+ radio: "input",
3237
+ link: "a",
3238
+ form: "form",
3239
+ dialog: "dialog"
3240
+ };
3241
+ return typeMap[type] || "div";
3242
+ }
3243
+ /**
3244
+ * Infer ARIA role from element type
3245
+ */
3246
+ inferRole(type) {
3247
+ const roleMap = {
3248
+ button: "button",
3249
+ input: "textbox",
3250
+ textarea: "textbox",
3251
+ select: "combobox",
3252
+ checkbox: "checkbox",
3253
+ radio: "radio",
3254
+ link: "link",
3255
+ dialog: "dialog",
3256
+ menu: "menu",
3257
+ menuitem: "menuitem",
3258
+ tab: "tab"
3259
+ };
3260
+ return roleMap[type];
3261
+ }
3262
+ /**
3263
+ * Infer semantic type
3264
+ */
3265
+ inferSemanticType(element) {
3266
+ const text = (element.state.textContent || element.label || "").toLowerCase();
3267
+ const type = element.type.toLowerCase();
3268
+ if (type === "button") {
3269
+ if (text.match(/submit|save|confirm|ok|done|apply/)) return "submit-button";
3270
+ if (text.match(/cancel|close|dismiss/)) return "cancel-button";
3271
+ if (text.match(/delete|remove|trash/)) return "delete-button";
3272
+ if (text.match(/add|create|new|\+/)) return "add-button";
3273
+ if (text.match(/edit|modify/)) return "edit-button";
3274
+ if (text.match(/next|continue/)) return "next-button";
3275
+ if (text.match(/back|previous/)) return "back-button";
3276
+ return "action-button";
3277
+ }
3278
+ if (type === "input") {
3279
+ if (text.includes("email") || element.id.includes("email")) return "email-input";
3280
+ if (text.includes("password") || element.id.includes("password")) return "password-input";
3281
+ if (text.includes("search") || element.id.includes("search")) return "search-input";
3282
+ return "text-input";
3283
+ }
3284
+ return type;
3285
+ }
3286
+ /**
3287
+ * Add snapshot to history
3288
+ */
3289
+ addToHistory(snapshot) {
3290
+ this.history.push({
3291
+ snapshot,
3292
+ timestamp: Date.now()
3293
+ });
3294
+ if (this.history.length > this.maxHistorySize) {
3295
+ this.history = this.history.slice(-this.maxHistorySize);
3296
+ }
3297
+ }
3298
+ };
3299
+
3300
+ // src/ai/semantic-diff.ts
3301
+ var DEFAULT_DIFF_CONFIG = {
3302
+ ignoreInsignificant: true,
3303
+ trackedProperties: ["visible", "enabled", "focused", "checked", "value", "textContent"],
3304
+ generateSuggestions: true,
3305
+ maxModifications: 20
3306
+ };
3307
+ var INSIGNIFICANT_PROPERTIES = /* @__PURE__ */ new Set(["rect", "computedStyles", "innerHTML"]);
3308
+ function computeDiff(fromSnapshot, toSnapshot, config = {}) {
3309
+ const startTime = performance.now();
3310
+ const finalConfig = { ...DEFAULT_DIFF_CONFIG, ...config };
3311
+ const fromElements = new Map(fromSnapshot.elements.map((el) => [el.id, el]));
3312
+ const toElements = new Map(toSnapshot.elements.map((el) => [el.id, el]));
3313
+ const appeared = [];
3314
+ for (const [id, element] of toElements) {
3315
+ if (!fromElements.has(id)) {
3316
+ appeared.push({
3317
+ elementId: id,
3318
+ description: element.description,
3319
+ type: element.type,
3320
+ semanticType: element.semanticType
3321
+ });
3322
+ }
3323
+ }
3324
+ const disappeared = [];
3325
+ for (const [id, element] of fromElements) {
3326
+ if (!toElements.has(id)) {
3327
+ disappeared.push({
3328
+ elementId: id,
3329
+ description: element.description,
3330
+ type: element.type,
3331
+ semanticType: element.semanticType
3332
+ });
3333
+ }
3334
+ }
3335
+ const modified = [];
3336
+ for (const [id, toElement] of toElements) {
3337
+ const fromElement = fromElements.get(id);
3338
+ if (fromElement) {
3339
+ const modifications = compareElements(fromElement, toElement, finalConfig);
3340
+ modified.push(...modifications);
3341
+ }
3342
+ }
3343
+ const limitedModifications = modified.slice(0, finalConfig.maxModifications);
3344
+ const probableTrigger = detectTrigger(appeared, disappeared, limitedModifications);
3345
+ const suggestedActions = finalConfig.generateSuggestions ? generateSuggestedActionsFromDiff(appeared, disappeared, limitedModifications, probableTrigger) : void 0;
3346
+ const pageChanges = detectPageChanges(fromSnapshot, toSnapshot);
3347
+ const summary = generateDiffSummary(
3348
+ appeared.map((e) => e.description),
3349
+ disappeared.map((e) => e.description),
3350
+ limitedModifications
3351
+ );
3352
+ return {
3353
+ summary,
3354
+ fromSnapshotId: fromSnapshot.snapshotId,
3355
+ toSnapshotId: toSnapshot.snapshotId,
3356
+ changes: {
3357
+ appeared,
3358
+ disappeared,
3359
+ modified: limitedModifications
3360
+ },
3361
+ probableTrigger,
3362
+ suggestedActions,
3363
+ pageChanges,
3364
+ durationMs: performance.now() - startTime,
3365
+ timestamp: Date.now()
3366
+ };
3367
+ }
3368
+ function compareElements(fromElement, toElement, config) {
3369
+ const modifications = [];
3370
+ for (const property of config.trackedProperties) {
3371
+ const fromValue = getPropertyValue(fromElement, property);
3372
+ const toValue = getPropertyValue(toElement, property);
3373
+ if (fromValue !== toValue) {
3374
+ const isSignificant = isSignificantChange(property, fromValue, toValue);
3375
+ if (!config.ignoreInsignificant || isSignificant) {
3376
+ modifications.push({
3377
+ elementId: toElement.id,
3378
+ description: toElement.description,
3379
+ property,
3380
+ from: formatValue(fromValue),
3381
+ to: formatValue(toValue),
3382
+ significant: isSignificant
3383
+ });
3384
+ }
3385
+ }
3386
+ }
3387
+ return modifications;
3388
+ }
3389
+ function getPropertyValue(element, property) {
3390
+ if (property in element.state) {
3391
+ return element.state[property];
3392
+ }
3393
+ return element[property];
3394
+ }
3395
+ function isSignificantChange(property, fromValue, toValue) {
3396
+ if (INSIGNIFICANT_PROPERTIES.has(property)) {
3397
+ return false;
3398
+ }
3399
+ if (property === "visible") {
3400
+ return true;
3401
+ }
3402
+ if (property === "enabled") {
3403
+ return true;
3404
+ }
3405
+ if (property === "focused") {
3406
+ return true;
3407
+ }
3408
+ if (property === "checked") {
3409
+ return true;
3410
+ }
3411
+ if (property === "value") {
3412
+ return Boolean(fromValue) || Boolean(toValue);
3413
+ }
3414
+ if (property === "textContent") {
3415
+ const fromText = String(fromValue || "");
3416
+ const toText = String(toValue || "");
3417
+ return fromText.trim() !== toText.trim();
3418
+ }
3419
+ return true;
3420
+ }
3421
+ function formatValue(value) {
3422
+ if (value === void 0) return "undefined";
3423
+ if (value === null) return "null";
3424
+ if (typeof value === "boolean") return value ? "true" : "false";
3425
+ if (typeof value === "string") {
3426
+ if (value.length > 50) {
3427
+ return value.substring(0, 47) + "...";
3428
+ }
3429
+ return value;
3430
+ }
3431
+ if (typeof value === "object") {
3432
+ return JSON.stringify(value);
3433
+ }
3434
+ return String(value);
3435
+ }
3436
+ function detectTrigger(appeared, disappeared, modified) {
3437
+ const hasNewErrors = appeared.some(
3438
+ (e) => e.description.toLowerCase().includes("error") || e.type === "error"
3439
+ );
3440
+ if (hasNewErrors) {
3441
+ return "Form validation";
3442
+ }
3443
+ const hasNewModal = appeared.some(
3444
+ (e) => e.type === "dialog" || e.semanticType?.includes("dialog")
3445
+ );
3446
+ if (hasNewModal) {
3447
+ return "Modal opened";
3448
+ }
3449
+ const hasModalDismissed = disappeared.some(
3450
+ (e) => e.type === "dialog" || e.semanticType?.includes("dialog")
3451
+ );
3452
+ if (hasModalDismissed) {
3453
+ return "Modal closed";
3454
+ }
3455
+ const hasLoading = modified.some((m) => m.description.toLowerCase().includes("loading"));
3456
+ if (hasLoading) {
3457
+ return "Loading state change";
3458
+ }
3459
+ const hasFocusChange = modified.some((m) => m.property === "focused");
3460
+ if (hasFocusChange && modified.length <= 2) {
3461
+ return "Focus changed";
3462
+ }
3463
+ const hasValueChange = modified.some((m) => m.property === "value");
3464
+ if (hasValueChange && modified.length <= 2) {
3465
+ return "User input";
3466
+ }
3467
+ const visibilityChanges = modified.filter((m) => m.property === "visible");
3468
+ if (visibilityChanges.length > 0 && visibilityChanges.length <= 5) {
3469
+ return "UI expansion/collapse";
3470
+ }
3471
+ if (appeared.length > 5) {
3472
+ return "Page navigation";
3473
+ }
3474
+ return void 0;
3475
+ }
3476
+ function detectPageChanges(fromSnapshot, toSnapshot) {
3477
+ const urlChanged = fromSnapshot.page.url !== toSnapshot.page.url;
3478
+ const titleChanged = fromSnapshot.page.title !== toSnapshot.page.title;
3479
+ if (!urlChanged && !titleChanged) {
3480
+ return void 0;
3481
+ }
3482
+ return {
3483
+ urlChanged,
3484
+ titleChanged,
3485
+ newUrl: urlChanged ? toSnapshot.page.url : void 0,
3486
+ newTitle: titleChanged ? toSnapshot.page.title : void 0
3487
+ };
3488
+ }
3489
+ function generateSuggestedActionsFromDiff(appeared, disappeared, modified, trigger) {
3490
+ const suggestions = [];
3491
+ if (trigger === "Form validation") {
3492
+ suggestions.push("Fix the validation errors before submitting");
3493
+ }
3494
+ if (trigger === "Modal opened") {
3495
+ const modal = appeared.find(
3496
+ (e) => e.type === "dialog" || e.semanticType?.includes("dialog")
3497
+ );
3498
+ if (modal) {
3499
+ suggestions.push(`Interact with the "${modal.description}" dialog`);
3500
+ }
3501
+ }
3502
+ if (trigger === "Modal closed") {
3503
+ suggestions.push("Continue with the main page interaction");
3504
+ }
3505
+ for (const element of appeared.slice(0, 3)) {
3506
+ if (element.type === "button" && element.semanticType === "submit-button") {
3507
+ suggestions.push(`Click the "${element.description}" to proceed`);
3508
+ }
3509
+ if (element.description.toLowerCase().includes("error")) {
3510
+ suggestions.push(`Address the error: ${element.description}`);
3511
+ }
3512
+ }
3513
+ for (const mod of modified.slice(0, 3)) {
3514
+ if (mod.property === "enabled" && mod.to === "true") {
3515
+ suggestions.push(`"${mod.description}" is now enabled`);
3516
+ }
3517
+ if (mod.property === "visible" && mod.to === "true") {
3518
+ suggestions.push(`"${mod.description}" is now visible`);
3519
+ }
3520
+ }
3521
+ return suggestions.slice(0, 5);
3522
+ }
3523
+ var SemanticDiffManager = class {
3524
+ constructor(config = {}) {
3525
+ this.lastSnapshot = null;
3526
+ this.config = { ...DEFAULT_DIFF_CONFIG, ...config };
3527
+ }
3528
+ /**
3529
+ * Update with new snapshot and get diff
3530
+ */
3531
+ update(newSnapshot) {
3532
+ if (!this.lastSnapshot) {
3533
+ this.lastSnapshot = newSnapshot;
3534
+ return null;
3535
+ }
3536
+ const diff = computeDiff(this.lastSnapshot, newSnapshot, this.config);
3537
+ this.lastSnapshot = newSnapshot;
3538
+ return diff;
3539
+ }
3540
+ /**
3541
+ * Get diff from a specific snapshot to current
3542
+ */
3543
+ diffFrom(fromSnapshot) {
3544
+ if (!this.lastSnapshot) return null;
3545
+ return computeDiff(fromSnapshot, this.lastSnapshot, this.config);
3546
+ }
3547
+ /**
3548
+ * Reset the manager
3549
+ */
3550
+ reset() {
3551
+ this.lastSnapshot = null;
3552
+ }
3553
+ /**
3554
+ * Get the last known snapshot
3555
+ */
3556
+ getLastSnapshot() {
3557
+ return this.lastSnapshot;
3558
+ }
3559
+ };
3560
+
3561
+ // src/server/handlers.ts
3562
+ function success(data) {
3563
+ return {
3564
+ success: true,
3565
+ data,
3566
+ timestamp: Date.now()
3567
+ };
3568
+ }
3569
+ function error(message, code) {
3570
+ return {
3571
+ success: false,
3572
+ error: message,
3573
+ code,
3574
+ timestamp: Date.now()
3575
+ };
3576
+ }
3577
+ function getRecoverySuggestions(errorCode) {
3578
+ switch (errorCode) {
3579
+ case "ELEMENT_NOT_FOUND":
3580
+ return [
3581
+ { suggestion: "Wait for the page to fully load", command: "wait for page to load", confidence: 0.7, retryable: true },
3582
+ { suggestion: "Use a different description for the element", confidence: 0.8, retryable: false },
3583
+ { suggestion: "Scroll the page to reveal the element", command: "scroll down", confidence: 0.6, retryable: true }
3584
+ ];
3585
+ case "ELEMENT_NOT_VISIBLE":
3586
+ return [
3587
+ { suggestion: "Scroll to make the element visible", command: "scroll to element", confidence: 0.9, retryable: true },
3588
+ { suggestion: "Wait for any loading overlays to disappear", confidence: 0.7, retryable: true },
3589
+ { suggestion: "Close any blocking modals or popups", command: "click close button", confidence: 0.8, retryable: true }
3590
+ ];
3591
+ case "ELEMENT_NOT_ENABLED":
3592
+ return [
3593
+ { suggestion: "Fill in required fields first", confidence: 0.8, retryable: false },
3594
+ { suggestion: "Complete prerequisite steps in the form", confidence: 0.7, retryable: false },
3595
+ { suggestion: "Wait for the element to become enabled", command: "wait for element to be enabled", confidence: 0.6, retryable: true }
3596
+ ];
3597
+ case "ELEMENT_NOT_INTERACTABLE":
3598
+ return [
3599
+ { suggestion: "Close any modal or popup blocking the element", command: "click close button", confidence: 0.9, retryable: true },
3600
+ { suggestion: "Wait for animations to complete", confidence: 0.7, retryable: true },
3601
+ { suggestion: "Scroll the element into the viewport", command: "scroll to element", confidence: 0.8, retryable: true }
3602
+ ];
3603
+ case "ACTION_TIMEOUT":
3604
+ return [
3605
+ { suggestion: "Increase the timeout duration", confidence: 0.8, retryable: true },
3606
+ { suggestion: "Check if the condition can ever be met", confidence: 0.7, retryable: false },
3607
+ { suggestion: "Verify the page is responding", command: "check page status", confidence: 0.6, retryable: true }
3608
+ ];
3609
+ case "LOW_CONFIDENCE":
3610
+ return [
3611
+ { suggestion: "Use the exact text shown on the element", confidence: 0.9, retryable: false },
3612
+ { suggestion: "Try a different description that more closely matches the element", confidence: 0.8, retryable: false },
3613
+ { suggestion: "Lower the confidence threshold if the match is correct", confidence: 0.7, retryable: true }
3614
+ ];
3615
+ case "AMBIGUOUS_MATCH":
3616
+ return [
3617
+ { suggestion: "Be more specific about which element you mean", confidence: 0.9, retryable: false },
3618
+ { suggestion: "Include the section or form name in the description", confidence: 0.8, retryable: false },
3619
+ { suggestion: "Use the element ID directly", confidence: 0.7, retryable: false }
3620
+ ];
3621
+ default:
3622
+ return [
3623
+ { suggestion: "Try a different approach or check the page state", confidence: 0.5, retryable: false }
3624
+ ];
3625
+ }
3626
+ }
3627
+ function createFailureDetails(errorCode, message, options = {}) {
3628
+ const retryableErrors = [
3629
+ "ELEMENT_NOT_VISIBLE",
3630
+ "ACTION_TIMEOUT",
3631
+ "LOW_CONFIDENCE",
3632
+ "NETWORK_ERROR",
3633
+ "STATE_NOT_REACHED"
3634
+ ];
3635
+ return {
3636
+ errorCode,
3637
+ message,
3638
+ elementId: options.elementId,
3639
+ selectorsTried: options.selectorsTried,
3640
+ suggestedActions: getRecoverySuggestions(errorCode),
3641
+ retryRecommended: retryableErrors.includes(errorCode),
3642
+ durationMs: options.durationMs,
3643
+ timeoutMs: options.timeoutMs
3644
+ };
3645
+ }
3646
+ function createHandlers(registry, actionExecutor, config = {}) {
3647
+ const searchEngine = new SearchEngine();
3648
+ const nlExecutor = new NLActionExecutor();
3649
+ const assertionExecutor = new AssertionExecutor();
3650
+ const snapshotManager = new SemanticSnapshotManager();
3651
+ const diffManager = new SemanticDiffManager();
3652
+ function refreshElements() {
3653
+ const elements = registry.getAllElements();
3654
+ searchEngine.updateElements(elements);
3655
+ nlExecutor.updateElements(elements);
3656
+ nlExecutor.setActionExecutor(actionExecutor);
3657
+ assertionExecutor.updateElements(elements);
3658
+ }
3659
+ return {
3660
+ // =========================================================================
3661
+ // Render Log Handlers
3662
+ // =========================================================================
3663
+ getRenderLog: async (query) => {
3664
+ try {
3665
+ const entries = registry.getRenderLog?.() ?? [];
3666
+ let filtered = entries;
3667
+ if (query?.type) {
3668
+ filtered = filtered.filter((e) => e.type === query.type);
3669
+ }
3670
+ if (query?.since) {
3671
+ filtered = filtered.filter((e) => e.timestamp >= query.since);
3672
+ }
3673
+ if (query?.until) {
3674
+ filtered = filtered.filter((e) => e.timestamp <= query.until);
3675
+ }
3676
+ if (query?.limit) {
3677
+ filtered = filtered.slice(0, query.limit);
3678
+ }
3679
+ return success(filtered);
3680
+ } catch (err) {
3681
+ return error(err.message, "RENDER_LOG_ERROR");
3682
+ }
3683
+ },
3684
+ clearRenderLog: async () => {
3685
+ try {
3686
+ registry.clearRenderLog?.();
3687
+ return success(void 0);
3688
+ } catch (err) {
3689
+ return error(err.message, "RENDER_LOG_ERROR");
3690
+ }
3691
+ },
3692
+ captureSnapshot: async () => {
3693
+ try {
3694
+ const snapshot = registry.captureSnapshot?.();
3695
+ return success(snapshot);
3696
+ } catch (err) {
3697
+ return error(err.message, "SNAPSHOT_ERROR");
3698
+ }
3699
+ },
3700
+ getRenderLogPath: async () => {
3701
+ return success({ path: config.renderLogPath || "" });
3702
+ },
3703
+ // =========================================================================
3704
+ // Element Handlers
3705
+ // =========================================================================
3706
+ getElements: async () => {
3707
+ try {
3708
+ const elements = registry.getAllElements();
3709
+ return success(elements);
3710
+ } catch (err) {
3711
+ return error(err.message, "ELEMENTS_ERROR");
3712
+ }
3713
+ },
3714
+ getElement: async (id) => {
3715
+ try {
3716
+ const element = registry.getElement(id);
3717
+ if (!element) {
3718
+ const failureDetails = createFailureDetails("ELEMENT_NOT_FOUND", `Element not found: ${id}`, {
3719
+ elementId: id,
3720
+ selectorsTried: [id]
3721
+ });
3722
+ return {
3723
+ success: false,
3724
+ error: `Element not found: ${id}`,
3725
+ code: "ELEMENT_NOT_FOUND",
3726
+ data: { failureDetails },
3727
+ timestamp: Date.now()
3728
+ };
3729
+ }
3730
+ return success(element);
3731
+ } catch (err) {
3732
+ return error(err.message, "ELEMENT_ERROR");
3733
+ }
3734
+ },
3735
+ getElementState: async (id) => {
3736
+ try {
3737
+ const element = registry.getElement(id);
3738
+ if (!element) {
3739
+ return error(`Element not found: ${id}`, "NOT_FOUND");
3740
+ }
3741
+ return success(element.state);
3742
+ } catch (err) {
3743
+ return error(err.message, "ELEMENT_STATE_ERROR");
3744
+ }
3745
+ },
3746
+ executeElementAction: async (id, request) => {
3747
+ const startTime = Date.now();
3748
+ try {
3749
+ const element = registry.getElement(id);
3750
+ if (!element) {
3751
+ const failureDetails = createFailureDetails("ELEMENT_NOT_FOUND", `Element not found: ${id}`, {
3752
+ elementId: id,
3753
+ selectorsTried: [id],
3754
+ durationMs: Date.now() - startTime
3755
+ });
3756
+ return {
3757
+ success: false,
3758
+ error: `Element not found: ${id}`,
3759
+ code: "ELEMENT_NOT_FOUND",
3760
+ data: {
3761
+ success: false,
3762
+ error: `Element not found: ${id}`,
3763
+ failureDetails,
3764
+ durationMs: Date.now() - startTime,
3765
+ timestamp: Date.now()
3766
+ },
3767
+ timestamp: Date.now()
3768
+ };
3769
+ }
3770
+ const result = await actionExecutor.executeAction(id, {
3771
+ action: request.action,
3772
+ params: request.params,
3773
+ waitOptions: request.waitOptions
3774
+ });
3775
+ if (result && typeof result === "object" && "success" in result && !result.success) {
3776
+ const actionResult = result;
3777
+ let errorCode = "UNKNOWN_ERROR";
3778
+ const errorMsg = actionResult.error?.toLowerCase() || "";
3779
+ if (errorMsg.includes("not found")) {
3780
+ errorCode = "ELEMENT_NOT_FOUND";
3781
+ } else if (errorMsg.includes("not visible") || errorMsg.includes("hidden")) {
3782
+ errorCode = "ELEMENT_NOT_VISIBLE";
3783
+ } else if (errorMsg.includes("disabled") || errorMsg.includes("not enabled")) {
3784
+ errorCode = "ELEMENT_NOT_ENABLED";
3785
+ } else if (errorMsg.includes("timeout")) {
3786
+ errorCode = "ACTION_TIMEOUT";
3787
+ } else if (errorMsg.includes("blocked") || errorMsg.includes("interactable")) {
3788
+ errorCode = "ELEMENT_NOT_INTERACTABLE";
3789
+ }
3790
+ const failureDetails = createFailureDetails(errorCode, actionResult.error || "Action failed", {
3791
+ elementId: id,
3792
+ durationMs: Date.now() - startTime
3793
+ });
3794
+ return success({
3795
+ ...actionResult,
3796
+ failureDetails
3797
+ });
3798
+ }
3799
+ return success(result);
3800
+ } catch (err) {
3801
+ const errorMessage = err.message;
3802
+ let errorCode = "UNKNOWN_ERROR";
3803
+ if (errorMessage.includes("not found")) {
3804
+ errorCode = "ELEMENT_NOT_FOUND";
3805
+ } else if (errorMessage.includes("timeout")) {
3806
+ errorCode = "ACTION_TIMEOUT";
3807
+ } else if (errorMessage.includes("network") || errorMessage.includes("fetch")) {
3808
+ errorCode = "NETWORK_ERROR";
3809
+ }
3810
+ const failureDetails = createFailureDetails(errorCode, errorMessage, {
3811
+ elementId: id,
3812
+ durationMs: Date.now() - startTime
3813
+ });
3814
+ return {
3815
+ success: false,
3816
+ error: errorMessage,
3817
+ code: errorCode,
3818
+ data: {
3819
+ success: false,
3820
+ error: errorMessage,
3821
+ failureDetails,
3822
+ durationMs: Date.now() - startTime,
3823
+ timestamp: Date.now()
3824
+ },
3825
+ timestamp: Date.now()
3826
+ };
3827
+ }
3828
+ },
3829
+ // =========================================================================
3830
+ // Component Handlers
3831
+ // =========================================================================
3832
+ getComponents: async () => {
3833
+ try {
3834
+ const components = registry.getAllComponents();
3835
+ return success(components);
3836
+ } catch (err) {
3837
+ return error(err.message, "COMPONENTS_ERROR");
3838
+ }
3839
+ },
3840
+ getComponent: async (id) => {
3841
+ try {
3842
+ const component = registry.getComponent(id);
3843
+ if (!component) {
3844
+ return error(`Component not found: ${id}`, "NOT_FOUND");
3845
+ }
3846
+ return success(component);
3847
+ } catch (err) {
3848
+ return error(err.message, "COMPONENT_ERROR");
3849
+ }
3850
+ },
3851
+ getComponentState: async (id) => {
3852
+ try {
3853
+ const component = registry.getComponent(id);
3854
+ if (!component) {
3855
+ return error(`Component not found: ${id}`, "NOT_FOUND");
3856
+ }
3857
+ if (registry.getComponentState) {
3858
+ const stateResponse = registry.getComponentState(id);
3859
+ if (!stateResponse) {
3860
+ return error(`Component not found or not mounted: ${id}`, "NOT_FOUND");
3861
+ }
3862
+ return success(stateResponse);
3863
+ }
3864
+ const comp = component;
3865
+ return success({
3866
+ state: comp.getState?.() ?? {},
3867
+ computed: comp.getComputed?.() ?? {},
3868
+ timestamp: Date.now()
3869
+ });
3870
+ } catch (err) {
3871
+ return error(err.message, "COMPONENT_STATE_ERROR");
3872
+ }
3873
+ },
3874
+ executeComponentAction: async (id, request) => {
3875
+ try {
3876
+ const result = await actionExecutor.executeComponentAction(id, {
3877
+ action: request.action,
3878
+ params: request.params
3879
+ });
3880
+ return success(result);
3881
+ } catch (err) {
3882
+ return error(err.message, "COMPONENT_ACTION_ERROR");
3883
+ }
3884
+ },
3885
+ // =========================================================================
3886
+ // Find/Discovery Handlers
3887
+ // =========================================================================
3888
+ find: async (request) => {
3889
+ try {
3890
+ const findRequest = request;
3891
+ const elements = registry.findElements?.(findRequest) ?? registry.getAllElements();
3892
+ return success({ elements, timestamp: Date.now(), total: elements.length, durationMs: 0 });
3893
+ } catch (err) {
3894
+ return error(err.message, "FIND_ERROR");
3895
+ }
3896
+ },
3897
+ discover: async (request) => {
3898
+ try {
3899
+ const findRequest = request;
3900
+ const elements = registry.findElements?.(findRequest) ?? registry.getAllElements();
3901
+ return success({ elements, timestamp: Date.now(), total: elements.length, durationMs: 0 });
3902
+ } catch (err) {
3903
+ return error(err.message, "DISCOVER_ERROR");
3904
+ }
3905
+ },
3906
+ getControlSnapshot: async () => {
3907
+ try {
3908
+ const snapshot = registry.createSnapshot();
3909
+ return success(snapshot);
3910
+ } catch (err) {
3911
+ return error(err.message, "SNAPSHOT_ERROR");
3912
+ }
3913
+ },
3914
+ // =========================================================================
3915
+ // Workflow Handlers
3916
+ // =========================================================================
3917
+ getWorkflows: async () => {
3918
+ try {
3919
+ const workflows = registry.getAllWorkflows?.() ?? [];
3920
+ return success(workflows);
3921
+ } catch (err) {
3922
+ return error(err.message, "WORKFLOWS_ERROR");
3923
+ }
3924
+ },
3925
+ runWorkflow: async (id, _request) => {
3926
+ try {
3927
+ const workflow = registry.getWorkflow?.(id);
3928
+ if (!workflow) {
3929
+ return error(`Workflow not found: ${id}`, "NOT_FOUND");
3930
+ }
3931
+ const runId = `run-${Date.now()}`;
3932
+ return success({
3933
+ runId,
3934
+ workflowId: id,
3935
+ status: "pending",
3936
+ startedAt: Date.now(),
3937
+ steps: [],
3938
+ totalSteps: 0
3939
+ });
3940
+ } catch (err) {
3941
+ return error(err.message, "WORKFLOW_ERROR");
3942
+ }
3943
+ },
3944
+ getWorkflowStatus: async (runId) => {
3945
+ try {
3946
+ return success({
3947
+ runId,
3948
+ workflowId: "",
3949
+ status: "completed",
3950
+ completedAt: Date.now(),
3951
+ startedAt: Date.now(),
3952
+ steps: [],
3953
+ totalSteps: 0
3954
+ });
3955
+ } catch (err) {
3956
+ return error(err.message, "WORKFLOW_STATUS_ERROR");
3957
+ }
3958
+ },
3959
+ // =========================================================================
3960
+ // Debug Handlers
3961
+ // =========================================================================
3962
+ getActionHistory: async (limit) => {
3963
+ try {
3964
+ const history = registry.getActionHistory?.() ?? [];
3965
+ const limited = limit ? history.slice(-limit) : history;
3966
+ return success(limited);
3967
+ } catch (err) {
3968
+ return error(err.message, "ACTION_HISTORY_ERROR");
3969
+ }
3970
+ },
3971
+ getMetrics: async () => {
3972
+ try {
3973
+ const metrics = registry.getMetrics?.() ?? {
3974
+ elementCount: registry.getAllElements().length,
3975
+ componentCount: registry.getAllComponents().length
3976
+ };
3977
+ return success(metrics);
3978
+ } catch (err) {
3979
+ return error(err.message, "METRICS_ERROR");
3980
+ }
3981
+ },
3982
+ highlightElement: async (id) => {
3983
+ try {
3984
+ registry.highlightElement?.(id);
3985
+ return success(void 0);
3986
+ } catch (err) {
3987
+ return error(err.message, "HIGHLIGHT_ERROR");
3988
+ }
3989
+ },
3990
+ getElementTree: async () => {
3991
+ try {
3992
+ const tree = registry.getElementTree?.() ?? { root: null, elements: [] };
3993
+ return success(tree);
3994
+ } catch (err) {
3995
+ return error(err.message, "ELEMENT_TREE_ERROR");
3996
+ }
3997
+ },
3998
+ // =========================================================================
3999
+ // AI-Native Handlers
4000
+ // =========================================================================
4001
+ aiSearch: async (criteria) => {
4002
+ try {
4003
+ refreshElements();
4004
+ const response = searchEngine.search(criteria);
4005
+ return success(response);
4006
+ } catch (err) {
4007
+ return error(err.message, "AI_SEARCH_ERROR");
4008
+ }
4009
+ },
4010
+ aiExecute: async (request) => {
4011
+ try {
4012
+ refreshElements();
4013
+ const response = await nlExecutor.execute(request);
4014
+ return success(response);
4015
+ } catch (err) {
4016
+ return error(err.message, "AI_EXECUTE_ERROR");
4017
+ }
4018
+ },
4019
+ aiAssert: async (request) => {
4020
+ try {
4021
+ refreshElements();
4022
+ const result = await assertionExecutor.assert(request);
4023
+ return success(result);
4024
+ } catch (err) {
4025
+ return error(err.message, "AI_ASSERT_ERROR");
4026
+ }
4027
+ },
4028
+ aiAssertBatch: async (request) => {
4029
+ try {
4030
+ refreshElements();
4031
+ const result = await assertionExecutor.assertBatch(request);
4032
+ return success(result);
4033
+ } catch (err) {
4034
+ return error(err.message, "AI_ASSERT_BATCH_ERROR");
4035
+ }
4036
+ },
4037
+ getSemanticSnapshot: async () => {
4038
+ try {
4039
+ const controlSnapshot = registry.createSnapshot();
4040
+ const snapshot = snapshotManager.createSnapshot(controlSnapshot);
4041
+ return success(snapshot);
4042
+ } catch (err) {
4043
+ return error(err.message, "SEMANTIC_SNAPSHOT_ERROR");
4044
+ }
4045
+ },
4046
+ getSemanticDiff: async (_since) => {
4047
+ try {
4048
+ const controlSnapshot = registry.createSnapshot();
4049
+ const currentSnapshot = snapshotManager.createSnapshot(controlSnapshot);
4050
+ const diff = diffManager.update(currentSnapshot);
4051
+ return success(diff);
4052
+ } catch (err) {
4053
+ return error(err.message, "SEMANTIC_DIFF_ERROR");
4054
+ }
4055
+ },
4056
+ getPageSummary: async () => {
4057
+ try {
4058
+ const snapshot = registry.createSnapshot();
4059
+ const elements = snapshot.elements.map((el) => ({
4060
+ ...el,
4061
+ description: el.label || el.id,
4062
+ aliases: [],
4063
+ suggestedActions: [],
4064
+ tagName: el.type,
4065
+ accessibleName: el.label,
4066
+ registered: true
4067
+ }));
4068
+ const summary = generatePageSummary(elements);
4069
+ return success(summary);
4070
+ } catch (err) {
4071
+ return error(err.message, "PAGE_SUMMARY_ERROR");
4072
+ }
4073
+ },
4074
+ // =========================================================================
4075
+ // Semantic Search Handler (Embedding-based)
4076
+ // =========================================================================
4077
+ aiSemanticSearch: async (criteria) => {
4078
+ const startTime = performance.now();
4079
+ try {
4080
+ refreshElements();
4081
+ const allElements = registry.getAllElements();
4082
+ const aiElements = allElements.map((el) => {
4083
+ const textParts = [];
4084
+ const state = "getState" in el ? el.getState() : el.state;
4085
+ const textContent = state?.textContent || "";
4086
+ const label = el.label || "";
4087
+ const accessibleName = el.accessibleName || "";
4088
+ const placeholder = el.placeholder || "";
4089
+ const title = el.title || "";
4090
+ if (label) textParts.push(label);
4091
+ if (accessibleName && accessibleName !== label) textParts.push(accessibleName);
4092
+ if (textContent && textContent !== label && textContent !== accessibleName) {
4093
+ textParts.push(textContent);
4094
+ }
4095
+ if (placeholder) textParts.push(`placeholder: ${placeholder}`);
4096
+ if (title) textParts.push(title);
4097
+ const combinedText = textParts.join(" ").trim() || el.id;
4098
+ return {
4099
+ element: {
4100
+ id: el.id,
4101
+ type: el.type,
4102
+ label: el.label,
4103
+ tagName: el.tagName || el.type,
4104
+ role: el.role,
4105
+ accessibleName: el.accessibleName,
4106
+ actions: el.actions || [],
4107
+ state: state || {},
4108
+ registered: true,
4109
+ description: label || el.id,
4110
+ aliases: [],
4111
+ suggestedActions: []
4112
+ },
4113
+ text: combinedText
4114
+ };
4115
+ });
4116
+ let filteredElements = aiElements;
4117
+ if (criteria.type) {
4118
+ filteredElements = filteredElements.filter(
4119
+ ({ element }) => element.type.toLowerCase() === criteria.type.toLowerCase()
4120
+ );
4121
+ }
4122
+ if (criteria.role) {
4123
+ filteredElements = filteredElements.filter(
4124
+ ({ element }) => element.role?.toLowerCase() === criteria.role.toLowerCase()
4125
+ );
4126
+ }
4127
+ const query = criteria.query.toLowerCase();
4128
+ const threshold = criteria.threshold ?? 0.5;
4129
+ const limit = criteria.limit ?? 10;
4130
+ const scoredResults = filteredElements.map(({ element, text }) => {
4131
+ const textLower = text.toLowerCase();
4132
+ let similarity = 0;
4133
+ if (textLower.includes(query)) {
4134
+ similarity = 0.9;
4135
+ } else {
4136
+ const queryWords = new Set(query.split(/\s+/).filter((w) => w.length > 2));
4137
+ const textWords = new Set(textLower.split(/\s+/).filter((w) => w.length > 2));
4138
+ if (queryWords.size > 0 && textWords.size > 0) {
4139
+ let matchCount = 0;
4140
+ for (const word of queryWords) {
4141
+ for (const textWord of textWords) {
4142
+ if (textWord.includes(word) || word.includes(textWord)) {
4143
+ matchCount++;
4144
+ break;
4145
+ }
4146
+ }
4147
+ }
4148
+ similarity = matchCount / queryWords.size * 0.7;
4149
+ }
4150
+ }
4151
+ return {
4152
+ element,
4153
+ similarity,
4154
+ rank: 0,
4155
+ // Will be set after sorting
4156
+ embeddedText: text
4157
+ };
4158
+ });
4159
+ const filteredResults = scoredResults.filter((r) => r.similarity >= threshold).sort((a, b) => b.similarity - a.similarity).slice(0, limit);
4160
+ filteredResults.forEach((result, index) => {
4161
+ result.rank = index + 1;
4162
+ });
4163
+ const response = {
4164
+ results: filteredResults,
4165
+ bestMatch: filteredResults.length > 0 ? filteredResults[0] : null,
4166
+ scannedCount: filteredElements.length,
4167
+ durationMs: performance.now() - startTime,
4168
+ query: criteria.query,
4169
+ providerInfo: {
4170
+ provider: "text-fallback",
4171
+ model: "simple-similarity",
4172
+ dimension: 0
4173
+ },
4174
+ timestamp: Date.now()
4175
+ };
4176
+ return success(response);
4177
+ } catch (err) {
4178
+ return error(err.message, "AI_SEMANTIC_SEARCH_ERROR");
4179
+ }
4180
+ }
4181
+ };
4182
+ }
4183
+ function createAIHandlers(registry, actionExecutor) {
4184
+ const searchEngine = new SearchEngine();
4185
+ const nlExecutor = new NLActionExecutor();
4186
+ const assertionExecutor = new AssertionExecutor();
4187
+ const snapshotManager = new SemanticSnapshotManager();
4188
+ const diffManager = new SemanticDiffManager();
4189
+ function refreshElements() {
4190
+ const elements = registry.getAllElements();
4191
+ searchEngine.updateElements(elements);
4192
+ nlExecutor.updateElements(elements);
4193
+ nlExecutor.setActionExecutor(actionExecutor);
4194
+ assertionExecutor.updateElements(elements);
4195
+ }
4196
+ return {
4197
+ aiSearch: async (criteria) => {
4198
+ try {
4199
+ refreshElements();
4200
+ const response = searchEngine.search(criteria);
4201
+ return { success: true, data: response, timestamp: Date.now() };
4202
+ } catch (err) {
4203
+ return { success: false, error: err.message, code: "AI_SEARCH_ERROR", timestamp: Date.now() };
4204
+ }
4205
+ },
4206
+ aiExecute: async (request) => {
4207
+ try {
4208
+ refreshElements();
4209
+ const response = await nlExecutor.execute(request);
4210
+ return { success: true, data: response, timestamp: Date.now() };
4211
+ } catch (err) {
4212
+ return { success: false, error: err.message, code: "AI_EXECUTE_ERROR", timestamp: Date.now() };
4213
+ }
4214
+ },
4215
+ aiAssert: async (request) => {
4216
+ try {
4217
+ refreshElements();
4218
+ const result = await assertionExecutor.assert(request);
4219
+ return { success: true, data: result, timestamp: Date.now() };
4220
+ } catch (err) {
4221
+ return { success: false, error: err.message, code: "AI_ASSERT_ERROR", timestamp: Date.now() };
4222
+ }
4223
+ },
4224
+ aiAssertBatch: async (request) => {
4225
+ try {
4226
+ refreshElements();
4227
+ const result = await assertionExecutor.assertBatch(request);
4228
+ return { success: true, data: result, timestamp: Date.now() };
4229
+ } catch (err) {
4230
+ return { success: false, error: err.message, code: "AI_ASSERT_BATCH_ERROR", timestamp: Date.now() };
4231
+ }
4232
+ },
4233
+ getSemanticSnapshot: async () => {
4234
+ try {
4235
+ const controlSnapshot = registry.createSnapshot();
4236
+ const snapshot = snapshotManager.createSnapshot(controlSnapshot);
4237
+ return { success: true, data: snapshot, timestamp: Date.now() };
4238
+ } catch (err) {
4239
+ return { success: false, error: err.message, code: "SEMANTIC_SNAPSHOT_ERROR", timestamp: Date.now() };
4240
+ }
4241
+ },
4242
+ getSemanticDiff: async (_since) => {
4243
+ try {
4244
+ const controlSnapshot = registry.createSnapshot();
4245
+ const currentSnapshot = snapshotManager.createSnapshot(controlSnapshot);
4246
+ const diff = diffManager.update(currentSnapshot);
4247
+ return { success: true, data: diff, timestamp: Date.now() };
4248
+ } catch (err) {
4249
+ return { success: false, error: err.message, code: "SEMANTIC_DIFF_ERROR", timestamp: Date.now() };
4250
+ }
4251
+ },
4252
+ getPageSummary: async () => {
4253
+ try {
4254
+ const snapshot = registry.createSnapshot();
4255
+ const elements = snapshot.elements.map((el) => ({
4256
+ ...el,
4257
+ description: el.label || el.id,
4258
+ aliases: [],
4259
+ suggestedActions: [],
4260
+ tagName: el.type,
4261
+ accessibleName: el.label,
4262
+ registered: true
4263
+ }));
4264
+ const summary = generatePageSummary(elements);
4265
+ return { success: true, data: summary, timestamp: Date.now() };
4266
+ } catch (err) {
4267
+ return { success: false, error: err.message, code: "PAGE_SUMMARY_ERROR", timestamp: Date.now() };
4268
+ }
4269
+ }
4270
+ };
4271
+ }
4272
+
4273
+ export { createAIHandlers, createHandlers };
4274
+ //# sourceMappingURL=handlers.mjs.map
4275
+ //# sourceMappingURL=handlers.mjs.map