synthux-mcp 0.0.0-stage → 2.1.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.
package/dist/cli.js ADDED
@@ -0,0 +1,3086 @@
1
+ #!/usr/bin/env node
2
+
3
+ // mcp/server.js
4
+ import http from "node:http";
5
+ import crypto from "node:crypto";
6
+ import readline from "node:readline";
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+
11
+ // extension/core/profiles.js
12
+ var PROFILES = {
13
+ "first-time": {
14
+ id: "first-time",
15
+ icon: "\u{1F195}",
16
+ name: {
17
+ en: "First-Time Visitor",
18
+ tr: "\u0130lk Kez Gelen Ziyaret\xE7i"
19
+ },
20
+ description: {
21
+ en: "A user who has never visited this website before. They are in exploration mode, unfamiliar with the site's navigation, terminology, and layout.",
22
+ tr: "Bu web sitesini daha \xF6nce hi\xE7 ziyaret etmemi\u015F bir kullan\u0131c\u0131. Ke\u015Fif modunda, sitenin navigasyonu, terminolojisi ve d\xFCzeni hakk\u0131nda bilgi sahibi de\u011Fil."
23
+ },
24
+ systemPrompt: `You are a first-time visitor who has never seen this website before. You are:
25
+ - Unfamiliar with the site's navigation, layout, and terminology
26
+ - Trying to understand what this site/product does within the first few seconds
27
+ - Looking for clear visual hierarchy and obvious entry points
28
+ - Easily confused by jargon, abbreviations, or insider language
29
+ - Expecting intuitive navigation without needing external help
30
+ - Judging trustworthiness based on design quality and professionalism
31
+
32
+ When evaluating, focus on:
33
+ - First impressions and clarity of purpose
34
+ - Navigation discoverability
35
+ - Terminology accessibility
36
+ - Visual hierarchy effectiveness
37
+ - Call-to-action clarity
38
+ - Error prevention for unfamiliar users`,
39
+ priorityHeuristics: [
40
+ "visibility-of-system-status",
41
+ "match-real-world",
42
+ "recognition-over-recall",
43
+ "aesthetic-minimalist"
44
+ ],
45
+ weight: 1
46
+ },
47
+ "power-user": {
48
+ id: "power-user",
49
+ icon: "\u{1F468}\u200D\u{1F4BB}",
50
+ name: {
51
+ en: "Power User",
52
+ tr: "Uzman Kullan\u0131c\u0131"
53
+ },
54
+ description: {
55
+ en: "An experienced user who values speed and efficiency above all. They look for keyboard shortcuts, advanced features, and gets frustrated by unnecessary steps.",
56
+ tr: "H\u0131z ve verimlili\u011Fe her \u015Feyin \xFCst\xFCnde de\u011Fer veren deneyimli bir kullan\u0131c\u0131. Klavye k\u0131sayollar\u0131, geli\u015Fmi\u015F \xF6zellikler arar ve gereksiz ad\u0131mlardan rahats\u0131z olur."
57
+ },
58
+ systemPrompt: `You are an experienced power user who values speed and efficiency above everything. You are:
59
+ - Impatient with unnecessary steps, confirmations, or animations
60
+ - Looking for keyboard shortcuts, batch actions, and quick access features
61
+ - Expecting consistent behavior across similar interactive elements
62
+ - Frustrated by lack of undo/redo or recovery options
63
+ - Wanting customization and flexibility in workflows
64
+ - Expecting search functionality and filtering options
65
+
66
+ When evaluating, focus on:
67
+ - Efficiency of common tasks
68
+ - Keyboard accessibility and shortcuts
69
+ - Consistency of UI patterns
70
+ - Undo/redo availability
71
+ - Search and filtering capabilities
72
+ - Customization options
73
+ - Error recovery speed`,
74
+ priorityHeuristics: [
75
+ "flexibility-efficiency",
76
+ "consistency-standards",
77
+ "error-recovery",
78
+ "user-control-freedom"
79
+ ],
80
+ weight: 1
81
+ },
82
+ "accessibility": {
83
+ id: "accessibility",
84
+ icon: "\u267F",
85
+ name: {
86
+ en: "Accessibility User",
87
+ tr: "Eri\u015Filebilirlik Kullan\u0131c\u0131s\u0131"
88
+ },
89
+ description: {
90
+ en: "A user who relies on assistive technologies like screen readers and keyboard-only navigation. They have low vision and need high contrast and clear structure.",
91
+ tr: "Ekran okuyucu ve yaln\u0131zca klavye navigasyonu gibi yard\u0131mc\u0131 teknolojilere g\xFCvenen bir kullan\u0131c\u0131. D\xFC\u015F\xFCk g\xF6rme kapasitesine sahip, y\xFCksek kontrast ve net yap\u0131 gerektirir."
92
+ },
93
+ systemPrompt: `You are a user who relies on assistive technologies. You are:
94
+ - Using a screen reader (like JAWS, NVDA, or VoiceOver) to navigate
95
+ - Navigating entirely with keyboard (Tab, Enter, Arrow keys, Escape)
96
+ - Dependent on proper heading structure for page comprehension
97
+ - Needing high color contrast (WCAG AA: 4.5:1 minimum)
98
+ - Requiring all interactive elements to have accessible names
99
+ - Expecting all images to have descriptive alt text
100
+ - Needing clear focus indicators to know where you are on the page
101
+ - Requiring form fields to have associated labels
102
+
103
+ When evaluating, focus on:
104
+ - Semantic HTML structure (headings, landmarks, lists)
105
+ - ARIA roles and labels completeness
106
+ - Keyboard navigability (Tab order, focus management)
107
+ - Color contrast ratios
108
+ - Alternative text for images
109
+ - Form accessibility (labels, error messages)
110
+ - Focus indicator visibility
111
+ - Skip navigation links`,
112
+ priorityHeuristics: [
113
+ "error-prevention",
114
+ "help-documentation",
115
+ "visibility-of-system-status",
116
+ "recognition-over-recall"
117
+ ],
118
+ weight: 1
119
+ }
120
+ };
121
+ function getProfile(id) {
122
+ return PROFILES[id] || null;
123
+ }
124
+ function buildCustomSystemPrompt(profile) {
125
+ const techLabels = {
126
+ low: "not very comfortable with technology, prefers simple interfaces",
127
+ medium: "moderately comfortable with technology, uses common apps regularly",
128
+ high: "very tech-savvy, comfortable with complex interfaces and shortcuts"
129
+ };
130
+ const ageLabels = {
131
+ "18-25": "a young adult (18-25) who is digitally native",
132
+ "25-35": "an adult (25-35) with regular internet experience",
133
+ "35-50": "a middle-aged adult (35-50) with moderate tech familiarity",
134
+ "50-65": "an older adult (50-65) who may prefer larger text and simpler layouts",
135
+ "65+": "a senior user (65+) who needs high contrast, large click targets, and simple navigation"
136
+ };
137
+ const disabilityDescriptions = {
138
+ vision: "low vision \u2014 needs high contrast, large text, and screen reader support",
139
+ hearing: "hearing impairment \u2014 relies on captions and visual cues instead of audio",
140
+ motor: "motor disability \u2014 uses keyboard or switch device, needs large click targets",
141
+ cognitive: "cognitive disability \u2014 needs simple language, clear structure, and minimal distractions",
142
+ none: "no disabilities"
143
+ };
144
+ const age = ageLabels[profile.ageRange] || ageLabels["25-35"];
145
+ const tech = techLabels[profile.techLevel] || techLabels["medium"];
146
+ const disabilities = (profile.disabilities || []).length > 0 ? profile.disabilities.map((d) => disabilityDescriptions[d] || d).join("; ") : disabilityDescriptions.none;
147
+ const goal = profile.goal || "browsing the page to accomplish a task";
148
+ return `You are ${age}. You are ${tech}.
149
+ Your accessibility needs: ${disabilities}.
150
+ Your goal on this page: ${goal}.
151
+
152
+ When evaluating this web page, adopt this persona fully. Consider:
153
+ - How would someone with your age, tech level, and abilities experience this page?
154
+ - Are there barriers that would prevent you from accomplishing your goal?
155
+ - Is the language, layout, and interaction design appropriate for your profile?
156
+ - Would you feel confident, confused, or frustrated using this page?
157
+
158
+ Evaluate from YOUR perspective \u2014 not as a generic user.`;
159
+ }
160
+
161
+ // extension/core/heuristics.js
162
+ var BUILT_IN_RULE_PACKS = [
163
+ {
164
+ id: "nielsen-10",
165
+ name: "Nielsen's 10 Usability Heuristics",
166
+ shortName: "Nielsen 10",
167
+ category: "General UX",
168
+ description: "Industry-standard general usability framework by Jakob Nielsen.",
169
+ file: "rules/nielsen-10.json",
170
+ ruleCount: 10,
171
+ isBuiltIn: true
172
+ },
173
+ {
174
+ id: "ecommerce",
175
+ name: "E-Commerce & Conversion UX",
176
+ shortName: "E-Commerce",
177
+ category: "E-Commerce & Retail",
178
+ description: "Specialized UX rules for online stores, product pages, carts, and checkout flows.",
179
+ file: "rules/ecommerce.json",
180
+ ruleCount: 8,
181
+ isBuiltIn: true
182
+ },
183
+ {
184
+ id: "saas",
185
+ name: "SaaS & Web Application UX",
186
+ shortName: "SaaS",
187
+ category: "SaaS & Dashboards",
188
+ description: "Specialized UX rules for SaaS apps, dashboards, onboarding, and self-service workflows.",
189
+ file: "rules/saas.json",
190
+ ruleCount: 8,
191
+ isBuiltIn: true
192
+ },
193
+ {
194
+ id: "fintech",
195
+ name: "Fintech, Banking & Web3 UX",
196
+ shortName: "Fintech",
197
+ category: "Finance & Banking",
198
+ description: "High-trust financial UX rules covering transaction safety, fee transparency, and numerical legibility.",
199
+ file: "rules/fintech.json",
200
+ ruleCount: 8,
201
+ isBuiltIn: true
202
+ }
203
+ ];
204
+ var DEFAULT_SCORING_RUBRIC = {
205
+ "0-20": "Critical violations \u2014 severe usability barriers",
206
+ "21-40": "Major issues \u2014 frequent user friction and confusion",
207
+ "41-60": "Moderate \u2014 functional but with notable UX gaps",
208
+ "61-80": "Good \u2014 solid implementation with minor issues",
209
+ "81-100": "Excellent \u2014 best-in-class user experience"
210
+ };
211
+ function validateAndNormalizeRulePack(rawInput) {
212
+ let parsed = rawInput;
213
+ if (typeof rawInput === "string") {
214
+ try {
215
+ parsed = JSON.parse(rawInput);
216
+ } catch (e) {
217
+ throw new Error("Invalid JSON syntax in rule pack.");
218
+ }
219
+ }
220
+ if (!parsed || typeof parsed !== "object") {
221
+ throw new Error("Rule pack must be a JSON object.");
222
+ }
223
+ const packName = String(parsed.name || parsed.shortName || "").trim();
224
+ if (!packName) {
225
+ throw new Error('Rule pack must include a "name" field.');
226
+ }
227
+ if (!Array.isArray(parsed.rules) || parsed.rules.length === 0) {
228
+ throw new Error('Rule pack must contain a non-empty "rules" array.');
229
+ }
230
+ if (parsed.rules.length > 25) {
231
+ throw new Error("Rule pack can contain at most 25 rules.");
232
+ }
233
+ const slug = String(parsed.id || packName).toLowerCase().replace(/[^a-z0-9-_]+/g, "-").replace(/^-+|-+$/g, "") || `custom-pack-${Date.now()}`;
234
+ const builtInIds = new Set(BUILT_IN_RULE_PACKS.map((p) => p.id));
235
+ const id = builtInIds.has(slug) ? `custom-${slug}` : slug;
236
+ const normalizedRules = parsed.rules.map((r, idx) => {
237
+ const ruleNameEn = typeof r.name === "object" && r.name !== null ? String(r.name.en || r.name.tr || `Rule ${idx + 1}`).trim() : String(r.name || `Rule ${idx + 1}`).trim();
238
+ const ruleNameTr = typeof r.name === "object" && r.name !== null ? String(r.name.tr || ruleNameEn).trim() : ruleNameEn;
239
+ const descEn = typeof r.description === "object" && r.description !== null ? String(r.description.en || r.description.tr || ruleNameEn).trim() : String(r.description || ruleNameEn).trim();
240
+ const descTr = typeof r.description === "object" && r.description !== null ? String(r.description.tr || descEn).trim() : descEn;
241
+ const ruleId = String(r.id || `${id}-rule-${idx + 1}`).toLowerCase().replace(/[^a-z0-9-_]+/g, "-");
242
+ const weight = Number.isFinite(Number(r.weight)) ? Math.max(0.1, Math.min(3, Number(r.weight))) : 1;
243
+ return {
244
+ id: ruleId,
245
+ name: { en: ruleNameEn, tr: ruleNameTr },
246
+ description: { en: descEn, tr: descTr },
247
+ weight,
248
+ automated_checks: Array.isArray(r.automated_checks) ? r.automated_checks : [],
249
+ evaluation_guide: String(r.evaluation_guide || r.criteria?.join(", ") || descEn).trim(),
250
+ prompt_template: String(r.prompt_template || `Evaluate this web page for '${ruleNameEn}'.`).trim(),
251
+ scoring_rubric: r.scoring_rubric && typeof r.scoring_rubric === "object" ? r.scoring_rubric : DEFAULT_SCORING_RUBRIC
252
+ };
253
+ });
254
+ return {
255
+ id,
256
+ name: packName,
257
+ shortName: String(parsed.shortName || packName.slice(0, 22)).trim(),
258
+ category: String(parsed.category || "Custom Pack").trim(),
259
+ description: String(parsed.description || `Custom UX rule pack (${normalizedRules.length} rules)`).trim(),
260
+ version: String(parsed.version || "1.0.0").trim(),
261
+ source: String(parsed.source || "custom").trim(),
262
+ ruleCount: normalizedRules.length,
263
+ isCustom: true,
264
+ rules: normalizedRules
265
+ };
266
+ }
267
+ function selectHeuristics(rules, mode = "deep", profileId = null) {
268
+ const allRules = rules.rules || [];
269
+ if (mode === "quick") {
270
+ const profile = getProfile(profileId);
271
+ if (profile?.priorityHeuristics) {
272
+ const matched = allRules.filter((r) => profile.priorityHeuristics.includes(r.id));
273
+ if (matched.length >= 3) {
274
+ return matched.slice(0, 3);
275
+ }
276
+ }
277
+ return [...allRules].sort((a, b) => (b.weight || 1) - (a.weight || 1)).slice(0, 3);
278
+ }
279
+ return allRules;
280
+ }
281
+ function buildPrompt(heuristic, profile, pageData, hasVision = false) {
282
+ const pageSummary = summarizePageData(pageData);
283
+ const visionBlock = hasVision ? `
284
+ ## Visual Analysis (Screenshot Attached)
285
+ A screenshot of the page is attached. Analyze BOTH the structural DOM data AND the visual screenshot together.
286
+ Pay special attention to:
287
+ - Visual hierarchy: Are headings, CTAs, and key content visually prominent?
288
+ - Color harmony: Do colors work well together? Is contrast sufficient?
289
+ - Layout & spacing: Is whitespace balanced? Are elements aligned properly?
290
+ - CTA visibility: Are call-to-action buttons visually discoverable?
291
+ - Typography: Is text readable? Are font sizes appropriate?
292
+ - Visual clutter: Is the page too busy or well-organized?
293
+ - Responsive feel: Does the layout look intentional and well-structured?
294
+ Include visual observations in your issue descriptions when relevant (e.g., "The CTA button blends into the background").
295
+ ` : "";
296
+ const heuristicName = typeof heuristic.name === "object" ? heuristic.name.en || heuristic.name.tr : String(heuristic.name || "");
297
+ const heuristicDesc = typeof heuristic.description === "object" ? heuristic.description.en || heuristic.description.tr : String(heuristic.description || "");
298
+ const rubric = heuristic.scoring_rubric || DEFAULT_SCORING_RUBRIC;
299
+ const prompt = `You are a UX evaluation expert. Evaluate the following web page against the heuristic "${heuristicName}".
300
+
301
+ ## Heuristic Definition
302
+ ${heuristicDesc}
303
+
304
+ ## Evaluation Criteria
305
+ ${heuristic.evaluation_guide || "Evaluate based on the heuristic definition and common UX best practices."}
306
+
307
+ ## Scoring Rubric
308
+ ${Object.entries(rubric).map(([range, desc]) => `- ${range}: ${desc}`).join("\n")}
309
+
310
+ ## Page Data
311
+ ${pageSummary}
312
+ ${visionBlock}
313
+ ## Your Perspective
314
+ ${profile.systemPrompt}
315
+
316
+ ## STRICT Response Rules
317
+ 1. Respond with ONLY a valid JSON object. No markdown, no code fences, no comments.
318
+ 2. Do NOT use JavaScript comments (// or /* */) anywhere in the response.
319
+ 3. Every field must have a meaningful, non-empty value. Do not leave any field blank.
320
+ 4. Each issue must have a clear description, the affected element, and a specific recommendation.
321
+ 5. Score must be a number between 0 and 100.
322
+ 6. For each issue, provide a concrete code fix showing the before/after code change. Use CSS, HTML, or JavaScript as appropriate.
323
+ 7. For each issue, rate the priority (impact on users: high/medium/low) and fix_effort (how hard it is to fix: easy/moderate/hard).
324
+ 8. For each issue, the "element" field MUST be a valid CSS selector that uniquely identifies the problematic element on the page (e.g. "nav.main-menu > ul > li:nth-child(2)", "input#email", ".hero-section .cta-button"). This is critical for page highlighting.${hasVision ? "\n9. When the screenshot reveals visual issues not apparent from DOM data alone, include them as findings." : ""}
325
+
326
+ ## Required JSON Structure
327
+ {
328
+ "score": 72,
329
+ "summary": "The page provides good visual feedback but lacks loading states for dynamic content.",
330
+ "issues": [
331
+ {
332
+ "severity": "critical",
333
+ "priority": "high",
334
+ "fix_effort": "easy",
335
+ "description": "Form inputs in the search section have no associated label elements",
336
+ "element": "input.search-field",
337
+ "recommendation": "Add a visible label element or aria-label attribute to each form input",
338
+ "code_fix": {
339
+ "language": "html",
340
+ "before": "<input type=\\"text\\" class=\\"search-field\\" placeholder=\\"Search...\\">",
341
+ "after": "<label for=\\"search\\">Search</label>\\n<input type=\\"text\\" id=\\"search\\" class=\\"search-field\\" placeholder=\\"Search...\\">"
342
+ }
343
+ }
344
+ ],
345
+ "positives": ["Clear navigation structure", "Good use of breadcrumbs"],
346
+ "score_justification": "Score reflects strong navigation but weak form accessibility"
347
+ }`;
348
+ return prompt;
349
+ }
350
+ function parseEvaluation(response) {
351
+ try {
352
+ let data;
353
+ const rawText = typeof response === "string" ? response : response?.raw || JSON.stringify(response);
354
+ data = tryParseJSON(rawText);
355
+ if (!data || typeof data !== "object") {
356
+ throw new Error("Could not extract valid JSON");
357
+ }
358
+ const validIssues = (data.issues || []).map((issue) => {
359
+ const priority = ["high", "medium", "low"].includes(issue.priority) ? issue.priority : "medium";
360
+ const fixEffort = ["easy", "moderate", "hard"].includes(issue.fix_effort) ? issue.fix_effort : "moderate";
361
+ return {
362
+ severity: ["critical", "moderate", "minor"].includes(issue.severity) ? issue.severity : "moderate",
363
+ priority,
364
+ fixEffort,
365
+ isQuickWin: priority === "high" && fixEffort === "easy",
366
+ description: String(issue.description || "").trim(),
367
+ element: String(issue.element || "").trim(),
368
+ recommendation: String(issue.recommendation || "").trim(),
369
+ codeFix: parseCodeFix(issue.code_fix)
370
+ };
371
+ }).filter((issue) => {
372
+ if (!issue.description || issue.description.length < 5) return false;
373
+ if (isPlaceholder(issue.description)) return false;
374
+ if (isPlaceholder(issue.recommendation)) return false;
375
+ const filledFields = [issue.description, issue.element, issue.recommendation].filter((f) => f && f.length > 3 && !isPlaceholder(f)).length;
376
+ return filledFields >= 2;
377
+ });
378
+ const validPositives = (data.positives || []).map((p) => String(p).trim()).filter((p) => p.length > 3 && !isPlaceholder(p));
379
+ return {
380
+ score: Math.max(0, Math.min(100, parseInt(data.score) || 50)),
381
+ summary: isPlaceholder(data.summary) ? "Evaluation completed" : String(data.summary || "Evaluation completed").trim(),
382
+ issues: validIssues,
383
+ positives: validPositives,
384
+ scoreJustification: String(data.score_justification || "").trim()
385
+ };
386
+ } catch (err) {
387
+ console.error("[synthux] Failed to parse evaluation:", err);
388
+ return {
389
+ score: 50,
390
+ summary: "Unable to parse AI evaluation response",
391
+ issues: [],
392
+ positives: [],
393
+ scoreJustification: "Default score due to parse error"
394
+ };
395
+ }
396
+ }
397
+ function calculateOverallScore(evaluations, rules) {
398
+ if (!evaluations || evaluations.length === 0) return 0;
399
+ const allRules = rules.rules || [];
400
+ let totalWeight = 0;
401
+ let weightedSum = 0;
402
+ evaluations.forEach((evaluation) => {
403
+ const rule = allRules.find((r) => r.id === evaluation.heuristicId);
404
+ const weight = rule?.weight || 1;
405
+ weightedSum += evaluation.score * weight;
406
+ totalWeight += weight;
407
+ });
408
+ return totalWeight > 0 ? Math.round(weightedSum / totalWeight) : 0;
409
+ }
410
+ function sanitizeLLMOutput(text) {
411
+ if (!text || typeof text !== "string") return "";
412
+ let cleaned = text;
413
+ cleaned = cleaned.replace(/<think>[\s\S]*?<\/think>/gi, "");
414
+ cleaned = cleaned.replace(/^[\s\S]*?<\/think>/gi, "");
415
+ cleaned = cleaned.replace(/,\s*\/\/[^\n]*/g, ",");
416
+ cleaned = cleaned.replace(/{\s*\/\/[^\n]*/g, "{");
417
+ cleaned = cleaned.replace(/^\s*\/\/[^\n]*/gm, "");
418
+ cleaned = cleaned.replace(/\/\*[\s\S]*?\*\//g, "");
419
+ cleaned = cleaned.replace(/,\s*([\]}])/g, "$1");
420
+ cleaned = cleaned.replace(/```json\s*/gi, "");
421
+ cleaned = cleaned.replace(/```\s*/g, "");
422
+ return cleaned.trim();
423
+ }
424
+ function tryParseJSON(text) {
425
+ if (!text || typeof text !== "string") {
426
+ if (typeof text === "object" && text !== null) return text;
427
+ return null;
428
+ }
429
+ const strippedText = text.replace(/<think>[\s\S]*?<\/think>/gi, "").replace(/^[\s\S]*?<\/think>/gi, "").trim();
430
+ try {
431
+ return JSON.parse(strippedText);
432
+ } catch {
433
+ }
434
+ const jsonMatch = strippedText.match(/\{[\s\S]*\}/);
435
+ if (jsonMatch) {
436
+ try {
437
+ return JSON.parse(jsonMatch[0]);
438
+ } catch {
439
+ }
440
+ try {
441
+ const cleaned = sanitizeLLMOutput(jsonMatch[0]);
442
+ return JSON.parse(cleaned);
443
+ } catch {
444
+ }
445
+ try {
446
+ const repaired = repairJSON(sanitizeLLMOutput(jsonMatch[0]));
447
+ return JSON.parse(repaired);
448
+ } catch {
449
+ }
450
+ }
451
+ const scoreMatch = strippedText.match(/"score"\s*:\s*(\d+)/);
452
+ const summaryMatch = strippedText.match(/"summary"\s*:\s*"([^"]+)"/);
453
+ const justificationMatch = strippedText.match(/"score_justification"\s*:\s*"([^"]+)"/);
454
+ if (scoreMatch) {
455
+ let issues = [];
456
+ const issuesBlockMatch = strippedText.match(/"issues"\s*:\s*\[([\s\S]*?)\]/);
457
+ if (issuesBlockMatch) {
458
+ try {
459
+ const cleaned = sanitizeLLMOutput(`[${issuesBlockMatch[1]}]`);
460
+ issues = JSON.parse(cleaned);
461
+ } catch {
462
+ const issueMatches = issuesBlockMatch[1].match(/\{[^{}]*\}/g);
463
+ if (issueMatches) {
464
+ issues = issueMatches.map((m) => {
465
+ try {
466
+ return JSON.parse(sanitizeLLMOutput(m));
467
+ } catch {
468
+ return null;
469
+ }
470
+ }).filter(Boolean);
471
+ }
472
+ }
473
+ }
474
+ let positives = [];
475
+ const positivesMatch = text.match(/"positives"\s*:\s*\[([\s\S]*?)\]/);
476
+ if (positivesMatch) {
477
+ try {
478
+ positives = JSON.parse(`[${positivesMatch[1]}]`);
479
+ } catch {
480
+ }
481
+ }
482
+ return {
483
+ score: parseInt(scoreMatch[1]),
484
+ summary: summaryMatch ? summaryMatch[1] : "Evaluation completed (recovered)",
485
+ issues,
486
+ positives,
487
+ score_justification: justificationMatch ? justificationMatch[1] : "Recovered from malformed response"
488
+ };
489
+ }
490
+ return null;
491
+ }
492
+ function repairJSON(text) {
493
+ let json = text;
494
+ json = json.replace(/}\s*{/g, "},{");
495
+ json = json.replace(/"\s*"/g, (match, offset) => {
496
+ const before = json.substring(Math.max(0, offset - 20), offset);
497
+ if (/[\[,]\s*"[^"]*$/.test(before)) return '","';
498
+ return match;
499
+ });
500
+ json = json.replace(/("[^"]*")\s+("[^"]*")/g, "$1,$2");
501
+ json = json.replace(/,\s*([\]}])/g, "$1");
502
+ const opens = (json.match(/{/g) || []).length;
503
+ const closes = (json.match(/}/g) || []).length;
504
+ const arrOpens = (json.match(/\[/g) || []).length;
505
+ const arrCloses = (json.match(/\]/g) || []).length;
506
+ for (let i = 0; i < arrOpens - arrCloses; i++) json += "]";
507
+ for (let i = 0; i < opens - closes; i++) json += "}";
508
+ const quoteCount = (json.match(/(?<!\\)"/g) || []).length;
509
+ if (quoteCount % 2 !== 0) {
510
+ json += '"';
511
+ }
512
+ return json;
513
+ }
514
+ function isPlaceholder(str) {
515
+ if (!str || typeof str !== "string") return true;
516
+ const s = str.trim().toLowerCase();
517
+ if (s.length < 3) return true;
518
+ const placeholders = [
519
+ "no description",
520
+ "no recommendation",
521
+ "no summary",
522
+ "n/a",
523
+ "none",
524
+ "unknown",
525
+ "not available",
526
+ "not applicable",
527
+ "no issues",
528
+ "no information",
529
+ "description",
530
+ "recommendation",
531
+ "tbd",
532
+ "todo",
533
+ "placeholder"
534
+ ];
535
+ return placeholders.includes(s);
536
+ }
537
+ function parseCodeFix(codeFix) {
538
+ if (!codeFix || typeof codeFix !== "object") return null;
539
+ const language = String(codeFix.language || "css").toLowerCase();
540
+ const before = String(codeFix.before || "").trim();
541
+ const after = String(codeFix.after || "").trim();
542
+ if (!after || after.length < 3 || isPlaceholder(after)) return null;
543
+ const validLangs = ["css", "html", "javascript", "js", "jsx", "scss"];
544
+ return {
545
+ language: validLangs.includes(language) ? language : "css",
546
+ before: before || "",
547
+ after
548
+ };
549
+ }
550
+ function summarizePageData(pageData) {
551
+ const parts = [];
552
+ if (pageData.meta) {
553
+ parts.push(`**Page Title:** ${pageData.meta.title || "None"}`);
554
+ parts.push(`**Language:** ${pageData.meta.lang || "Not set"}`);
555
+ parts.push(`**Description:** ${pageData.meta.description || "None"}`);
556
+ }
557
+ if (pageData.structure) {
558
+ const { headings, landmarks, forms } = pageData.structure;
559
+ parts.push(`
560
+ **Headings:** ${headings?.length || 0} total`);
561
+ if (headings?.length > 0) {
562
+ const h1Count = headings.filter((h) => h.level === 1).length;
563
+ parts.push(` - H1 count: ${h1Count}`);
564
+ const headingOrder = headings.map((h) => `H${h.level}`).join(" \u2192 ");
565
+ parts.push(` - Order: ${headingOrder}`);
566
+ }
567
+ parts.push(`**Landmarks:** ${landmarks?.length || 0} (${landmarks?.map((l) => l.role).join(", ") || "none"})`);
568
+ parts.push(`**Forms:** ${forms?.length || 0}`);
569
+ if (forms?.length > 0) {
570
+ forms.forEach((f, i) => {
571
+ parts.push(` Form ${i + 1}: ${f.fields?.length || 0} fields, submit button: ${f.hasSubmitButton ? "yes" : "no"}`);
572
+ const unlabeled = f.fields?.filter((field) => !field.label).length || 0;
573
+ if (unlabeled > 0) parts.push(` ${unlabeled} fields without labels`);
574
+ });
575
+ }
576
+ }
577
+ if (pageData.navigation) {
578
+ parts.push(`
579
+ **Navigation:**`);
580
+ parts.push(` - Nav elements: ${pageData.navigation.navCount || 0}`);
581
+ parts.push(` - Menu depth: ${pageData.navigation.mainMenu?.depth || 0}`);
582
+ parts.push(` - Breadcrumbs: ${pageData.navigation.breadcrumb ? "yes" : "no"}`);
583
+ parts.push(` - Skip links: ${pageData.navigation.skipLinks ? "yes" : "no"}`);
584
+ parts.push(` - Search: ${pageData.navigation.hasSearch ? "yes" : "no"}`);
585
+ }
586
+ if (pageData.content) {
587
+ parts.push(`
588
+ **Content:**`);
589
+ parts.push(` - Text length: ${pageData.content.textLength || 0} chars, ${pageData.content.wordCount || 0} words`);
590
+ parts.push(` - Images: ${pageData.content.imageCount || 0} total, ${pageData.content.imagesWithoutAlt || 0} without alt text`);
591
+ parts.push(` - CTAs: ${pageData.content.ctas?.length || 0}`);
592
+ parts.push(` - Links: ${pageData.content.internalLinks || 0} internal, ${pageData.content.externalLinks || 0} external`);
593
+ }
594
+ if (pageData.accessibility) {
595
+ parts.push(`
596
+ **Accessibility:**`);
597
+ parts.push(` - ARIA roles used: ${pageData.accessibility.ariaRoles?.join(", ") || "none"}`);
598
+ parts.push(` - Tab order issues: ${pageData.accessibility.tabOrderIssues?.length || 0}`);
599
+ parts.push(` - Lang attribute: ${pageData.accessibility.hasLangAttr ? "yes" : "no"}`);
600
+ parts.push(` - Unlabeled interactive elements: ${pageData.accessibility.unlabeledInteractives?.length || 0}`);
601
+ const contrastResults = pageData.accessibility.contrastResults || [];
602
+ const failing = contrastResults.filter((c) => !c.passes).length;
603
+ parts.push(` - Color contrast: ${contrastResults.length} sampled, ${failing} failing`);
604
+ parts.push(` - Focus indicators: ${pageData.accessibility.focusIndicators?.note || "unknown"}`);
605
+ }
606
+ if (pageData.performance) {
607
+ parts.push(`
608
+ **Performance:**`);
609
+ parts.push(` - DOM elements: ${pageData.performance.domSize || 0}`);
610
+ parts.push(` - Scripts: ${pageData.performance.scriptCount || 0}`);
611
+ parts.push(` - Stylesheets: ${pageData.performance.styleSheetCount || 0}`);
612
+ parts.push(` - Loading indicators: ${pageData.performance.loadingState?.hasLoadingIndicators ? "present" : "none detected"}`);
613
+ }
614
+ return parts.join("\n");
615
+ }
616
+
617
+ // extension/core/accessibility.js
618
+ function runAccessibilityChecks(pageData) {
619
+ const checks = [];
620
+ checks.push(checkAltText(pageData));
621
+ checks.push(checkHeadingHierarchy(pageData));
622
+ checks.push(checkColorContrast(pageData));
623
+ checks.push(checkFormLabels(pageData));
624
+ checks.push(checkLanguageAttribute(pageData));
625
+ checks.push(checkSkipNavigation(pageData));
626
+ checks.push(checkLandmarks(pageData));
627
+ checks.push(checkTabOrder(pageData));
628
+ checks.push(checkFocusIndicators(pageData));
629
+ checks.push(checkInteractiveLabels(pageData));
630
+ const passCount = checks.filter((c) => c.status === "pass").length;
631
+ const warnCount = checks.filter((c) => c.status === "warning").length;
632
+ const failCount = checks.filter((c) => c.status === "fail").length;
633
+ const totalChecks = checks.length;
634
+ const score = Math.round(
635
+ (passCount * 100 + warnCount * 50 + failCount * 0) / totalChecks
636
+ );
637
+ return {
638
+ score,
639
+ passCount,
640
+ warnCount,
641
+ failCount,
642
+ totalChecks,
643
+ checks
644
+ };
645
+ }
646
+ function checkAltText(pageData) {
647
+ const images = pageData.content?.images || [];
648
+ const total = images.length;
649
+ const withAlt = images.filter((i) => i.hasAlt).length;
650
+ const withoutAlt = images.filter((i) => !i.hasAlt).length;
651
+ if (total === 0) {
652
+ return {
653
+ id: "alt-text",
654
+ name: "Image Alt Text",
655
+ status: "pass",
656
+ message: "No images found on page",
657
+ details: { total: 0, withAlt: 0, withoutAlt: 0 }
658
+ };
659
+ }
660
+ const ratio = withAlt / total;
661
+ return {
662
+ id: "alt-text",
663
+ name: "Image Alt Text",
664
+ status: ratio >= 1 ? "pass" : ratio >= 0.8 ? "warning" : "fail",
665
+ message: `${withAlt}/${total} images have alt text (${Math.round(ratio * 100)}%)`,
666
+ details: {
667
+ total,
668
+ withAlt,
669
+ withoutAlt,
670
+ missingElements: images.filter((i) => !i.hasAlt).slice(0, 5).map((i) => i.src?.substring(0, 80))
671
+ }
672
+ };
673
+ }
674
+ function checkHeadingHierarchy(pageData) {
675
+ const headings = pageData.structure?.headings || [];
676
+ if (headings.length === 0) {
677
+ return {
678
+ id: "heading-hierarchy",
679
+ name: "Heading Hierarchy",
680
+ status: "warning",
681
+ message: "No headings found on page",
682
+ details: { headings: [] }
683
+ };
684
+ }
685
+ const issues = [];
686
+ const h1Count = headings.filter((h) => h.level === 1).length;
687
+ if (h1Count === 0) {
688
+ issues.push("No H1 heading found");
689
+ } else if (h1Count > 1) {
690
+ issues.push(`Multiple H1 headings found (${h1Count})`);
691
+ }
692
+ for (let i = 1; i < headings.length; i++) {
693
+ const prev = headings[i - 1].level;
694
+ const curr = headings[i].level;
695
+ if (curr > prev + 1) {
696
+ issues.push(`Heading level skipped: H${prev} \u2192 H${curr} (expected H${prev + 1})`);
697
+ }
698
+ }
699
+ return {
700
+ id: "heading-hierarchy",
701
+ name: "Heading Hierarchy",
702
+ status: issues.length === 0 ? "pass" : issues.length <= 1 ? "warning" : "fail",
703
+ message: issues.length === 0 ? `${headings.length} headings in correct order` : `${issues.length} heading issues found`,
704
+ details: {
705
+ headingCount: headings.length,
706
+ h1Count,
707
+ issues,
708
+ structure: headings.map((h) => `H${h.level}: ${h.text.substring(0, 60)}`)
709
+ }
710
+ };
711
+ }
712
+ function checkColorContrast(pageData) {
713
+ const results = pageData.accessibility?.contrastResults || [];
714
+ if (results.length === 0) {
715
+ return {
716
+ id: "color-contrast",
717
+ name: "Color Contrast (WCAG AA)",
718
+ status: "warning",
719
+ message: "Unable to sample color contrast",
720
+ details: { sampled: 0 }
721
+ };
722
+ }
723
+ const passing = results.filter((r) => r.passes).length;
724
+ const failing = results.filter((r) => !r.passes).length;
725
+ const ratio = passing / results.length;
726
+ return {
727
+ id: "color-contrast",
728
+ name: "Color Contrast (WCAG AA)",
729
+ status: ratio >= 1 ? "pass" : ratio >= 0.8 ? "warning" : "fail",
730
+ message: `${passing}/${results.length} sampled elements pass WCAG AA`,
731
+ details: {
732
+ sampled: results.length,
733
+ passing,
734
+ failing,
735
+ failingElements: results.filter((r) => !r.passes).slice(0, 5).map((r) => ({
736
+ element: r.element,
737
+ ratio: r.ratio,
738
+ required: r.required
739
+ }))
740
+ }
741
+ };
742
+ }
743
+ function checkFormLabels(pageData) {
744
+ const forms = pageData.structure?.forms || [];
745
+ if (forms.length === 0) {
746
+ return {
747
+ id: "form-labels",
748
+ name: "Form Field Labels",
749
+ status: "pass",
750
+ message: "No forms found on page",
751
+ details: { formCount: 0 }
752
+ };
753
+ }
754
+ let totalFields = 0;
755
+ let labeledFields = 0;
756
+ const unlabeledFields = [];
757
+ forms.forEach((form) => {
758
+ (form.fields || []).forEach((field) => {
759
+ if (field.type === "hidden" || field.type === "submit") return;
760
+ totalFields++;
761
+ if (field.label) {
762
+ labeledFields++;
763
+ } else {
764
+ unlabeledFields.push(`${field.type}${field.name ? `[name="${field.name}"]` : ""}`);
765
+ }
766
+ });
767
+ });
768
+ if (totalFields === 0) {
769
+ return {
770
+ id: "form-labels",
771
+ name: "Form Field Labels",
772
+ status: "pass",
773
+ message: "No input fields found",
774
+ details: { formCount: forms.length, totalFields: 0 }
775
+ };
776
+ }
777
+ const ratio = labeledFields / totalFields;
778
+ return {
779
+ id: "form-labels",
780
+ name: "Form Field Labels",
781
+ status: ratio >= 1 ? "pass" : ratio >= 0.8 ? "warning" : "fail",
782
+ message: `${labeledFields}/${totalFields} form fields have labels`,
783
+ details: {
784
+ formCount: forms.length,
785
+ totalFields,
786
+ labeledFields,
787
+ unlabeledFields: unlabeledFields.slice(0, 10)
788
+ }
789
+ };
790
+ }
791
+ function checkLanguageAttribute(pageData) {
792
+ const hasLang = pageData.accessibility?.hasLangAttr;
793
+ return {
794
+ id: "lang-attribute",
795
+ name: "Language Attribute",
796
+ status: hasLang ? "pass" : "fail",
797
+ message: hasLang ? `Page language is set to "${pageData.meta?.lang}"` : "No lang attribute on <html> element",
798
+ details: { lang: pageData.meta?.lang || null }
799
+ };
800
+ }
801
+ function checkSkipNavigation(pageData) {
802
+ const hasSkip = pageData.navigation?.skipLinks;
803
+ return {
804
+ id: "skip-nav",
805
+ name: "Skip Navigation",
806
+ status: hasSkip ? "pass" : "warning",
807
+ message: hasSkip ? "Skip navigation link found" : "No skip navigation link detected",
808
+ details: {}
809
+ };
810
+ }
811
+ function checkLandmarks(pageData) {
812
+ const landmarks = pageData.structure?.landmarks || [];
813
+ const roles = landmarks.map((l) => l.role);
814
+ const hasMain = roles.includes("main");
815
+ const hasNav = roles.includes("navigation");
816
+ const hasBanner = roles.includes("banner");
817
+ const issues = [];
818
+ if (!hasMain) issues.push('No <main> or role="main" landmark');
819
+ if (!hasNav) issues.push('No <nav> or role="navigation" landmark');
820
+ return {
821
+ id: "landmarks",
822
+ name: "ARIA Landmarks",
823
+ status: issues.length === 0 ? "pass" : issues.length === 1 ? "warning" : "fail",
824
+ message: `${landmarks.length} landmarks found (${roles.join(", ") || "none"})`,
825
+ details: {
826
+ landmarkCount: landmarks.length,
827
+ roles,
828
+ hasMain,
829
+ hasNav,
830
+ hasBanner,
831
+ issues
832
+ }
833
+ };
834
+ }
835
+ function checkTabOrder(pageData) {
836
+ const issues = pageData.accessibility?.tabOrderIssues || [];
837
+ return {
838
+ id: "tab-order",
839
+ name: "Tab Order",
840
+ status: issues.length === 0 ? "pass" : "warning",
841
+ message: issues.length === 0 ? "No positive tabindex values found" : `${issues.length} elements use positive tabindex (disrupts natural order)`,
842
+ details: {
843
+ issues: issues.slice(0, 5)
844
+ }
845
+ };
846
+ }
847
+ function checkFocusIndicators(pageData) {
848
+ const focusInfo = pageData.accessibility?.focusIndicators || {};
849
+ return {
850
+ id: "focus-indicators",
851
+ name: "Focus Indicators",
852
+ status: focusInfo.removesOutlines ? "fail" : "pass",
853
+ message: focusInfo.note || "Unable to check focus indicators",
854
+ details: focusInfo
855
+ };
856
+ }
857
+ function checkInteractiveLabels(pageData) {
858
+ const unlabeled = pageData.accessibility?.unlabeledInteractives || [];
859
+ return {
860
+ id: "interactive-labels",
861
+ name: "Interactive Element Labels",
862
+ status: unlabeled.length === 0 ? "pass" : unlabeled.length <= 3 ? "warning" : "fail",
863
+ message: unlabeled.length === 0 ? "All interactive elements have accessible names" : `${unlabeled.length} interactive elements lack accessible names`,
864
+ details: {
865
+ unlabeledCount: unlabeled.length,
866
+ elements: unlabeled.slice(0, 10)
867
+ }
868
+ };
869
+ }
870
+
871
+ // extension/core/report-generator.js
872
+ function generateReport(data) {
873
+ const {
874
+ url,
875
+ title,
876
+ timestamp,
877
+ model,
878
+ mode,
879
+ provider,
880
+ rulePackId = "nielsen-10",
881
+ rulePackName = "Nielsen's 10 Usability Heuristics",
882
+ rulePackShortName = "Nielsen 10",
883
+ ruleCount = 10,
884
+ overallScore,
885
+ profileResults,
886
+ accessibilityResults,
887
+ issues,
888
+ screenshot,
889
+ annotatedScreenshot = null,
890
+ costSummary
891
+ } = data;
892
+ return {
893
+ version: "2.0.0",
894
+ url,
895
+ title,
896
+ timestamp,
897
+ model,
898
+ mode,
899
+ provider: provider || "ollama",
900
+ rulePackId,
901
+ rulePackName,
902
+ rulePackShortName,
903
+ ruleCount,
904
+ overallScore,
905
+ profileResults,
906
+ accessibilityResults,
907
+ issues,
908
+ annotatedScreenshot: annotatedScreenshot || null,
909
+ visionEnabled: !!screenshot,
910
+ costSummary: costSummary || null,
911
+ markdown: generateMarkdown(data),
912
+ json: generateJSON(data)
913
+ };
914
+ }
915
+ function generateMarkdown(data) {
916
+ const {
917
+ url,
918
+ title,
919
+ timestamp,
920
+ model,
921
+ mode,
922
+ rulePackName = "Nielsen's 10 Usability Heuristics",
923
+ ruleCount = 10,
924
+ overallScore,
925
+ profileResults = {},
926
+ accessibilityResults,
927
+ issues = []
928
+ } = data;
929
+ const lines = [];
930
+ const critical = issues.filter((i) => i.severity === "critical");
931
+ const moderate = issues.filter((i) => i.severity === "moderate");
932
+ const minor = issues.filter((i) => i.severity === "minor");
933
+ const quickWins = issues.filter((i) => i.isQuickWin || i.priority === "high" && i.fixEffort === "easy");
934
+ lines.push("# \u{1F4CA} synthux UX Audit Report");
935
+ lines.push("");
936
+ lines.push("| Audit Property | Details |");
937
+ lines.push("|:---|:---|");
938
+ lines.push(`| **URL** | ${url} |`);
939
+ lines.push(`| **Page Title** | ${title || "N/A"} |`);
940
+ lines.push(`| **Date** | ${new Date(timestamp).toLocaleString()} |`);
941
+ lines.push(`| **Rule Pack** | **${rulePackName}** |`);
942
+ const modeLabel = mode === "deep" ? `\u{1F52C} Deep (${ruleCount} rules)` : mode === "custom" ? "\u{1F3AF} Custom Selection" : `\u26A1 Quick (${Math.min(3, ruleCount)} rules)`;
943
+ lines.push(`| **Analysis Mode** | ${modeLabel} |`);
944
+ lines.push(`| **AI Engine** | \`${model}\` (${data.provider || "ollama"}${data.screenshot ? " \xB7 Vision" : ""}) |`);
945
+ if (data.costSummary) {
946
+ lines.push(`| **Token / Cost** | ${data.costSummary.formatted} |`);
947
+ }
948
+ lines.push("");
949
+ lines.push("## \u{1F4C8} Executive Summary & KPI Scorecard");
950
+ lines.push("");
951
+ lines.push("| Metric | Score / Count | Visual Bar / Breakdown |");
952
+ lines.push("|:---|:---|:---|");
953
+ lines.push(`| **Overall UX Score** | **${overallScore}/100** ${getScoreEmoji(overallScore)} | \`${renderScoreBar(overallScore)}\` (${getScoreGrade(overallScore)}) |`);
954
+ if (accessibilityResults) {
955
+ lines.push(`| **Accessibility (WCAG)** | **${accessibilityResults.score}/100** ${getScoreEmoji(accessibilityResults.score)} | \`${renderScoreBar(accessibilityResults.score)}\` (${accessibilityResults.wcagViolations?.length || 0} WCAG violations) |`);
956
+ }
957
+ Object.values(profileResults).forEach((pr) => {
958
+ const pName = pr.profile?.name?.en || pr.profile?.name || "Profile";
959
+ lines.push(`| **${pr.profile?.icon || "\u{1F464}"} ${pName}** | **${pr.score}/100** ${getScoreEmoji(pr.score)} | \`${renderScoreBar(pr.score)}\` |`);
960
+ });
961
+ lines.push(`| **Total Unique Issues** | **${issues.length}** | \u{1F534} ${critical.length} Critical \xB7 \u{1F7E1} ${moderate.length} Moderate \xB7 \u{1F7E2} ${minor.length} Minor |`);
962
+ lines.push(`| **Quick Wins** | **${quickWins.length}** | \u26A1 High-impact, easy-effort fixes ready for immediate action |`);
963
+ lines.push("");
964
+ if (issues.length > 0) {
965
+ const majorProjects = issues.filter((i) => i.priority === "high" && i.fixEffort !== "easy");
966
+ const fillIns = issues.filter((i) => i.priority !== "high" && i.fixEffort === "easy");
967
+ const backlog = issues.filter((i) => i.priority !== "high" && i.fixEffort !== "easy");
968
+ lines.push("---");
969
+ lines.push("");
970
+ lines.push("## \u{1F9ED} 2\xD72 Impact \xD7 Effort Priority Matrix");
971
+ lines.push("");
972
+ lines.push("| Quadrant | Impact \xD7 Effort | Count | Top Actionable Focus |");
973
+ lines.push("|:---|:---|:---:|:---|");
974
+ lines.push(`| **\u26A1 1. Quick Wins** | High Impact \xB7 Easy Fix | **${quickWins.length}** | ${quickWins[0]?.description || "None identified"} |`);
975
+ lines.push(`| **\u{1F680} 2. Major Projects** | High Impact \xB7 Mod/Hard Fix | **${majorProjects.length}** | ${majorProjects[0]?.description || "None identified"} |`);
976
+ lines.push(`| **\u{1F527} 3. Fill-Ins** | Med/Low Impact \xB7 Easy Fix | **${fillIns.length}** | ${fillIns[0]?.description || "None identified"} |`);
977
+ lines.push(`| **\u{1F4CB} 4. Backlog** | Med/Low Impact \xB7 Mod/Hard Fix | **${backlog.length}** | ${backlog[0]?.description || "None identified"} |`);
978
+ lines.push("");
979
+ if (quickWins.length > 0) {
980
+ lines.push("### \u26A1 Top Quick Wins (Do First)");
981
+ lines.push("");
982
+ quickWins.forEach((issue, idx) => {
983
+ lines.push(`${idx + 1}. **[${issue.severity.toUpperCase()}] ${issue.description}**`);
984
+ if (issue.element) lines.push(` - **Selector:** \`${issue.element}\``);
985
+ lines.push(` - **Action:** ${issue.recommendation}`);
986
+ if (issue.codeFix) {
987
+ lines.push(` - **Fix (\`${issue.codeFix.language}\`):** \`${issue.codeFix.after.replace(/\n/g, " ")}\``);
988
+ }
989
+ });
990
+ lines.push("");
991
+ }
992
+ }
993
+ Object.values(profileResults).forEach((pr) => {
994
+ const pName = pr.profile?.name?.en || pr.profile?.name || "Profile";
995
+ lines.push("---");
996
+ lines.push("");
997
+ lines.push(`## ${pr.profile?.icon || "\u{1F464}"} ${pName} \u2014 ${pr.score}/100 (${getScoreGrade(pr.score)})`);
998
+ lines.push("");
999
+ if (pr.profile?.custom) {
1000
+ const details = [];
1001
+ if (pr.profile.ageRange) details.push(`**Age:** ${pr.profile.ageRange}`);
1002
+ if (pr.profile.techLevel) details.push(`**Tech Level:** ${pr.profile.techLevel}`);
1003
+ if (pr.profile.disabilities?.length) details.push(`**Accessibility:** ${pr.profile.disabilities.join(", ")}`);
1004
+ if (pr.profile.goal) details.push(`**Goal:** ${pr.profile.goal}`);
1005
+ if (details.length > 0) {
1006
+ lines.push(`> \u{1F464} **Custom Persona** \u2014 ${details.join(" \xB7 ")}`);
1007
+ lines.push("");
1008
+ }
1009
+ }
1010
+ lines.push("| Heuristic / Rule | Score | Bar | Summary |");
1011
+ lines.push("|:---|:---:|:---|:---|");
1012
+ pr.evaluations.forEach((ev) => {
1013
+ const name = ev.heuristicName?.en || ev.heuristicName;
1014
+ const emoji = getScoreEmoji(ev.score);
1015
+ const summary = String(ev.summary || "").replace(/\|/g, "\\|");
1016
+ lines.push(`| **${name}** | ${ev.score}/100 ${emoji} | \`${renderScoreBar(ev.score, 8)}\` | ${summary} |`);
1017
+ });
1018
+ lines.push("");
1019
+ const profileIssues = pr.evaluations.flatMap(
1020
+ (ev) => (ev.issues || []).map((i) => ({ ...i, heuristic: ev.heuristicName?.en || ev.heuristicName }))
1021
+ );
1022
+ if (profileIssues.length > 0) {
1023
+ lines.push("### \u{1F50D} Identified Issues & Code Fixes");
1024
+ lines.push("");
1025
+ profileIssues.forEach((issue) => {
1026
+ const icon = issue.severity === "critical" ? "\u{1F534}" : issue.severity === "moderate" ? "\u{1F7E1}" : "\u{1F7E2}";
1027
+ const priorityTag = issue.priority === "high" ? " \xB7 `HIGH IMPACT`" : issue.priority === "low" ? " \xB7 `low impact`" : "";
1028
+ const effortTag = issue.fixEffort === "easy" ? " \xB7 `EASY FIX`" : issue.fixEffort === "hard" ? " \xB7 `HARD FIX`" : "";
1029
+ const qwTag = issue.priority === "high" && issue.fixEffort === "easy" ? " \xB7 \u{1F3C6} **Quick Win**" : "";
1030
+ lines.push(`- ${icon} **[${issue.severity.toUpperCase()}]** *(${issue.heuristic})*${priorityTag}${effortTag}${qwTag}`);
1031
+ lines.push(` - **Issue:** ${issue.description}`);
1032
+ if (issue.element) lines.push(` - **Element:** \`${issue.element}\``);
1033
+ lines.push(` - **Recommendation:** ${issue.recommendation}`);
1034
+ if (issue.codeFix) {
1035
+ lines.push(` - <details><summary>\u{1F4BB} Suggested Code Fix (${issue.codeFix.language})</summary>`);
1036
+ lines.push("");
1037
+ if (issue.codeFix.before) {
1038
+ lines.push(` **Before:**`);
1039
+ lines.push(` \`\`\`${issue.codeFix.language}`);
1040
+ lines.push(` ${issue.codeFix.before}`);
1041
+ lines.push(` \`\`\``);
1042
+ }
1043
+ lines.push(` **After:**`);
1044
+ lines.push(` \`\`\`${issue.codeFix.language}`);
1045
+ lines.push(` ${issue.codeFix.after}`);
1046
+ lines.push(` \`\`\``);
1047
+ lines.push(` </details>`);
1048
+ }
1049
+ });
1050
+ lines.push("");
1051
+ }
1052
+ const positives = pr.evaluations.flatMap((ev) => ev.positives || []);
1053
+ if (positives.length > 0) {
1054
+ lines.push("### \u2705 Strengths & Positives");
1055
+ lines.push("");
1056
+ positives.forEach((p) => {
1057
+ lines.push(`- \u2705 ${p}`);
1058
+ });
1059
+ lines.push("");
1060
+ }
1061
+ });
1062
+ if (accessibilityResults) {
1063
+ lines.push("---");
1064
+ lines.push("");
1065
+ lines.push(`## \u267F Accessibility & WCAG 2.2 AA Audit \u2014 ${accessibilityResults.score}/100`);
1066
+ lines.push("");
1067
+ lines.push("| Automated Check | Status | Details |");
1068
+ lines.push("|:---|:---|:---|");
1069
+ (accessibilityResults.checks || []).forEach((check) => {
1070
+ const icon = check.status === "pass" ? "\u2705" : check.status === "warning" ? "\u26A0\uFE0F" : "\u274C";
1071
+ lines.push(`| **${check.name}** | ${icon} ${check.status} | ${check.message} |`);
1072
+ });
1073
+ lines.push("");
1074
+ if (accessibilityResults.wcagViolations?.length > 0) {
1075
+ lines.push(`### WCAG Violations (axe-core) \u2014 ${accessibilityResults.wcagViolations.length} issue${accessibilityResults.wcagViolations.length > 1 ? "s" : ""}`);
1076
+ lines.push("");
1077
+ accessibilityResults.wcagViolations.forEach((v) => {
1078
+ const impactIcon = v.impact === "critical" ? "\u{1F534}" : v.impact === "serious" ? "\u{1F7E1}" : v.impact === "moderate" ? "\u{1F535}" : "\u26AA";
1079
+ lines.push(`- ${impactIcon} **[${v.impact}]** **${v.help}**`);
1080
+ lines.push(` - ${v.description}`);
1081
+ if (v.tags?.length) lines.push(` - **Standard:** \`${v.tags.join("`, `")}\``);
1082
+ if (v.nodes?.length) {
1083
+ v.nodes.slice(0, 3).forEach((n) => {
1084
+ lines.push(` - **Element:** \`${n.target || n.html}\``);
1085
+ });
1086
+ }
1087
+ if (v.helpUrl) lines.push(` - [WCAG Reference](${v.helpUrl})`);
1088
+ });
1089
+ lines.push("");
1090
+ }
1091
+ if (accessibilityResults.wcagPasses) {
1092
+ lines.push(`> \u2713 **${accessibilityResults.wcagPasses}** automated WCAG 2.2 rules passed`);
1093
+ lines.push("");
1094
+ }
1095
+ }
1096
+ if (issues.length > 0) {
1097
+ lines.push("---");
1098
+ lines.push("");
1099
+ lines.push("## \u{1F3AF} Consolidated Issues by Severity");
1100
+ lines.push("");
1101
+ if (critical.length > 0) {
1102
+ lines.push(`### \u{1F534} Critical (${critical.length})`);
1103
+ critical.forEach((issue, idx) => {
1104
+ lines.push(`${idx + 1}. **${issue.description}** ${issue.element ? `(\`${issue.element}\`)` : ""}`);
1105
+ lines.push(` - \u{1F4A1} ${issue.recommendation}`);
1106
+ });
1107
+ lines.push("");
1108
+ }
1109
+ if (moderate.length > 0) {
1110
+ lines.push(`### \u{1F7E1} Moderate (${moderate.length})`);
1111
+ moderate.forEach((issue, idx) => {
1112
+ lines.push(`${idx + 1}. **${issue.description}** ${issue.element ? `(\`${issue.element}\`)` : ""}`);
1113
+ lines.push(` - \u{1F4A1} ${issue.recommendation}`);
1114
+ });
1115
+ lines.push("");
1116
+ }
1117
+ if (minor.length > 0) {
1118
+ lines.push(`### \u{1F7E2} Minor (${minor.length})`);
1119
+ minor.forEach((issue, idx) => {
1120
+ lines.push(`${idx + 1}. **${issue.description}** ${issue.element ? `(\`${issue.element}\`)` : ""}`);
1121
+ lines.push(` - \u{1F4A1} ${issue.recommendation}`);
1122
+ });
1123
+ lines.push("");
1124
+ }
1125
+ }
1126
+ lines.push("---");
1127
+ lines.push("");
1128
+ lines.push("*Generated by [synthux v2.0](https://synthux.app) \u2014 Open Source AI-Powered UX Audit.*");
1129
+ return lines.join("\n");
1130
+ }
1131
+ function generateJSON(data) {
1132
+ return {
1133
+ version: "2.0.0",
1134
+ url: data.url,
1135
+ title: data.title,
1136
+ timestamp: data.timestamp,
1137
+ model: data.model,
1138
+ mode: data.mode,
1139
+ rulePackId: data.rulePackId || "nielsen-10",
1140
+ rulePackName: data.rulePackName || "Nielsen's 10 Usability Heuristics",
1141
+ overallScore: data.overallScore,
1142
+ profiles: Object.fromEntries(
1143
+ Object.entries(data.profileResults || {}).map(([id, pr]) => [
1144
+ id,
1145
+ {
1146
+ score: pr.score,
1147
+ evaluations: (pr.evaluations || []).map((ev) => ({
1148
+ heuristic: ev.heuristicId,
1149
+ score: ev.score,
1150
+ summary: ev.summary,
1151
+ issues: ev.issues,
1152
+ positives: ev.positives
1153
+ }))
1154
+ }
1155
+ ])
1156
+ ),
1157
+ accessibility: {
1158
+ score: data.accessibilityResults?.score,
1159
+ checks: data.accessibilityResults?.checks?.map((c) => ({
1160
+ id: c.id,
1161
+ name: c.name,
1162
+ status: c.status,
1163
+ message: c.message
1164
+ }))
1165
+ },
1166
+ topIssues: (data.issues || []).slice(0, 15).map((i) => ({
1167
+ severity: i.severity,
1168
+ priority: i.priority,
1169
+ fixEffort: i.fixEffort,
1170
+ isQuickWin: i.isQuickWin || false,
1171
+ element: i.element || "",
1172
+ description: i.description,
1173
+ recommendation: i.recommendation,
1174
+ codeFix: i.codeFix || null
1175
+ }))
1176
+ };
1177
+ }
1178
+ function getScoreEmoji(score) {
1179
+ if (score >= 81) return "\u2705";
1180
+ if (score >= 61) return "\u{1F7E1}";
1181
+ if (score >= 41) return "\u26A0\uFE0F";
1182
+ return "\u274C";
1183
+ }
1184
+ function getScoreGrade(score) {
1185
+ if (score >= 85) return "Excellent";
1186
+ if (score >= 70) return "Good";
1187
+ if (score >= 50) return "Needs Improvement";
1188
+ return "Critical";
1189
+ }
1190
+ function renderScoreBar(score, length = 10) {
1191
+ const clamped = Math.max(0, Math.min(100, Number(score) || 0));
1192
+ const filled = Math.round(clamped / 100 * length);
1193
+ return "\u2588".repeat(filled) + "\u2591".repeat(Math.max(0, length - filled));
1194
+ }
1195
+
1196
+ // extension/core/providers.js
1197
+ var PROVIDERS = {
1198
+ ollama: {
1199
+ id: "ollama",
1200
+ name: "Ollama (Local)",
1201
+ icon: "\u{1F5A5}\uFE0F",
1202
+ authType: "none",
1203
+ defaultEndpoint: "http://localhost:11434",
1204
+ models: [],
1205
+ // Dynamically fetched from local server
1206
+ modelsFetchable: true,
1207
+ buildRequest(prompt, model, options = {}) {
1208
+ const body = {
1209
+ model,
1210
+ prompt,
1211
+ system: options.systemPrompt || "",
1212
+ stream: false,
1213
+ format: options.format || "json",
1214
+ options: {
1215
+ temperature: options.temperature ?? 0.3,
1216
+ num_predict: options.maxTokens || 2048
1217
+ }
1218
+ };
1219
+ if (options.images?.length) {
1220
+ body.images = options.images.map((img) => img.replace(/^data:image\/\w+;base64,/, ""));
1221
+ }
1222
+ return {
1223
+ url: `${options.endpoint || this.defaultEndpoint}/api/generate`,
1224
+ method: "POST",
1225
+ headers: { "Content-Type": "application/json" },
1226
+ body
1227
+ };
1228
+ },
1229
+ parseResponse(data) {
1230
+ try {
1231
+ const parsed = JSON.parse(data.response);
1232
+ return {
1233
+ success: true,
1234
+ result: parsed,
1235
+ meta: {
1236
+ model: data.model,
1237
+ totalDuration: data.total_duration,
1238
+ inputTokens: data.prompt_eval_count || 0,
1239
+ outputTokens: data.eval_count || 0
1240
+ }
1241
+ };
1242
+ } catch {
1243
+ return {
1244
+ success: true,
1245
+ result: { raw: data.response },
1246
+ meta: {
1247
+ model: data.model,
1248
+ inputTokens: data.prompt_eval_count || 0,
1249
+ outputTokens: data.eval_count || 0
1250
+ }
1251
+ };
1252
+ }
1253
+ },
1254
+ async fetchModels(endpoint) {
1255
+ try {
1256
+ const res = await fetch(`${endpoint || this.defaultEndpoint}/api/tags`);
1257
+ if (!res.ok) return [];
1258
+ const data = await res.json();
1259
+ return (data.models || []).map((m) => ({
1260
+ id: m.name,
1261
+ name: m.name,
1262
+ size: m.size
1263
+ }));
1264
+ } catch {
1265
+ return [];
1266
+ }
1267
+ },
1268
+ async ping(endpoint) {
1269
+ const url = endpoint || this.defaultEndpoint;
1270
+ try {
1271
+ const res = await fetch(`${url}/api/tags`, {
1272
+ signal: AbortSignal.timeout(5e3)
1273
+ });
1274
+ if (res.ok) {
1275
+ try {
1276
+ const postProbe = await fetch(`${url}/api/generate`, {
1277
+ method: "POST",
1278
+ headers: { "Content-Type": "application/json" },
1279
+ body: JSON.stringify({ model: "" }),
1280
+ signal: AbortSignal.timeout(3e3)
1281
+ });
1282
+ if (postProbe.status === 403) {
1283
+ return { status: "cors-blocked" };
1284
+ }
1285
+ } catch {
1286
+ return { status: "cors-blocked" };
1287
+ }
1288
+ let version = null;
1289
+ try {
1290
+ const vRes = await fetch(`${url}/api/version`, { signal: AbortSignal.timeout(3e3) });
1291
+ if (vRes.ok) {
1292
+ const vData = await vRes.json();
1293
+ version = vData.version || null;
1294
+ }
1295
+ } catch {
1296
+ }
1297
+ return { status: "connected", version };
1298
+ }
1299
+ return { status: "error", code: res.status };
1300
+ } catch {
1301
+ try {
1302
+ await fetch(url, {
1303
+ mode: "no-cors",
1304
+ signal: AbortSignal.timeout(3e3)
1305
+ });
1306
+ return { status: "cors-blocked" };
1307
+ } catch {
1308
+ return { status: "offline" };
1309
+ }
1310
+ }
1311
+ }
1312
+ },
1313
+ openai: {
1314
+ id: "openai",
1315
+ name: "OpenAI",
1316
+ icon: "\u{1F7E2}",
1317
+ authType: "bearer",
1318
+ defaultEndpoint: "https://api.openai.com",
1319
+ models: [
1320
+ { id: "gpt-5.4", name: "GPT-5.4" },
1321
+ { id: "gpt-5.4-mini", name: "GPT-5.4 Mini" },
1322
+ { id: "gpt-5.4-nano", name: "GPT-5.4 Nano" },
1323
+ { id: "gpt-5.1", name: "GPT-5.1" }
1324
+ ],
1325
+ modelsFetchable: true,
1326
+ buildRequest(prompt, model, options = {}) {
1327
+ const userContent = [];
1328
+ if (options.images?.length) {
1329
+ options.images.forEach((img) => {
1330
+ userContent.push({
1331
+ type: "image_url",
1332
+ image_url: { url: img, detail: "low" }
1333
+ });
1334
+ });
1335
+ }
1336
+ userContent.push({ type: "text", text: prompt });
1337
+ return {
1338
+ url: `${options.endpoint || this.defaultEndpoint}/v1/chat/completions`,
1339
+ method: "POST",
1340
+ headers: {
1341
+ "Content-Type": "application/json",
1342
+ "Authorization": `Bearer ${options.apiKey}`
1343
+ },
1344
+ body: {
1345
+ model,
1346
+ messages: [
1347
+ ...options.systemPrompt ? [{ role: "system", content: options.systemPrompt }] : [],
1348
+ { role: "user", content: options.images?.length ? userContent : prompt }
1349
+ ],
1350
+ temperature: options.temperature ?? 0.3,
1351
+ max_tokens: options.maxTokens || 2048,
1352
+ response_format: options.format === "json" ? { type: "json_object" } : void 0
1353
+ }
1354
+ };
1355
+ },
1356
+ parseResponse(data) {
1357
+ const content = data.choices?.[0]?.message?.content || "";
1358
+ try {
1359
+ const parsed = JSON.parse(content);
1360
+ return {
1361
+ success: true,
1362
+ result: parsed,
1363
+ meta: {
1364
+ model: data.model,
1365
+ inputTokens: data.usage?.prompt_tokens || 0,
1366
+ outputTokens: data.usage?.completion_tokens || 0
1367
+ }
1368
+ };
1369
+ } catch {
1370
+ return {
1371
+ success: true,
1372
+ result: { raw: content },
1373
+ meta: {
1374
+ model: data.model,
1375
+ inputTokens: data.usage?.prompt_tokens || 0,
1376
+ outputTokens: data.usage?.completion_tokens || 0
1377
+ }
1378
+ };
1379
+ }
1380
+ },
1381
+ async fetchModels(endpoint, apiKey) {
1382
+ try {
1383
+ const res = await fetch(`${endpoint || this.defaultEndpoint}/v1/models`, {
1384
+ headers: { "Authorization": `Bearer ${apiKey}` }
1385
+ });
1386
+ if (!res.ok) return this.models;
1387
+ const data = await res.json();
1388
+ return (data.data || []).filter((m) => m.id.startsWith("gpt-5") || m.id.startsWith("gpt-4") || m.id.startsWith("o")).map((m) => ({ id: m.id, name: m.id })).sort((a, b) => a.name.localeCompare(b.name));
1389
+ } catch {
1390
+ return this.models;
1391
+ }
1392
+ },
1393
+ async ping(endpoint, apiKey) {
1394
+ try {
1395
+ const res = await fetch(`${endpoint || this.defaultEndpoint}/v1/models`, {
1396
+ headers: { "Authorization": `Bearer ${apiKey}` },
1397
+ signal: AbortSignal.timeout(8e3)
1398
+ });
1399
+ return res.ok;
1400
+ } catch {
1401
+ return false;
1402
+ }
1403
+ }
1404
+ },
1405
+ gemini: {
1406
+ id: "gemini",
1407
+ name: "Google Gemini",
1408
+ icon: "\u{1F535}",
1409
+ authType: "query_param",
1410
+ defaultEndpoint: "https://generativelanguage.googleapis.com",
1411
+ models: [
1412
+ { id: "gemini-2.5-flash", name: "Gemini 2.5 Flash" },
1413
+ { id: "gemini-2.5-pro", name: "Gemini 2.5 Pro" },
1414
+ { id: "gemini-2.5-flash-lite", name: "Gemini 2.5 Flash-Lite" },
1415
+ { id: "gemini-3-flash-preview", name: "Gemini 3 Flash (Preview)" },
1416
+ { id: "gemini-3.1-pro-preview", name: "Gemini 3.1 Pro (Preview)" },
1417
+ { id: "gemini-3.1-flash-lite-preview", name: "Gemini 3.1 Flash-Lite (Preview)" }
1418
+ ],
1419
+ modelsFetchable: true,
1420
+ buildRequest(prompt, model, options = {}) {
1421
+ const endpoint = options.endpoint || this.defaultEndpoint;
1422
+ const apiKey = options.apiKey || "";
1423
+ const userParts = [];
1424
+ if (options.images?.length) {
1425
+ options.images.forEach((img) => {
1426
+ userParts.push({
1427
+ inlineData: {
1428
+ mimeType: "image/jpeg",
1429
+ data: img.replace(/^data:image\/\w+;base64,/, "")
1430
+ }
1431
+ });
1432
+ });
1433
+ }
1434
+ userParts.push({ text: prompt });
1435
+ return {
1436
+ url: `${endpoint}/v1beta/models/${model}:generateContent?key=${apiKey}`,
1437
+ method: "POST",
1438
+ headers: { "Content-Type": "application/json" },
1439
+ body: {
1440
+ contents: [
1441
+ ...options.systemPrompt ? [{
1442
+ role: "model",
1443
+ parts: [{ text: `System: ${options.systemPrompt}` }]
1444
+ }] : [],
1445
+ { role: "user", parts: userParts }
1446
+ ],
1447
+ generationConfig: {
1448
+ temperature: options.temperature ?? 0.3,
1449
+ maxOutputTokens: options.maxTokens || 4096,
1450
+ responseMimeType: options.format === "json" ? "application/json" : "text/plain",
1451
+ // Disable thinking tokens for structured JSON output — saves ~60-80% output cost
1452
+ thinkingConfig: { thinkingBudget: 0 }
1453
+ }
1454
+ }
1455
+ };
1456
+ },
1457
+ parseResponse(data) {
1458
+ const content = data.candidates?.[0]?.content?.parts?.[0]?.text || "";
1459
+ const usage = data.usageMetadata || {};
1460
+ const outputTokens = (usage.candidatesTokenCount || 0) + (usage.thoughtsTokenCount || 0);
1461
+ try {
1462
+ const parsed = JSON.parse(content);
1463
+ return {
1464
+ success: true,
1465
+ result: parsed,
1466
+ meta: {
1467
+ model: data.modelVersion || "",
1468
+ inputTokens: usage.promptTokenCount || 0,
1469
+ outputTokens,
1470
+ thinkingTokens: usage.thoughtsTokenCount || 0
1471
+ }
1472
+ };
1473
+ } catch {
1474
+ return {
1475
+ success: true,
1476
+ result: { raw: content },
1477
+ meta: {
1478
+ model: data.modelVersion || "",
1479
+ inputTokens: usage.promptTokenCount || 0,
1480
+ outputTokens,
1481
+ thinkingTokens: usage.thoughtsTokenCount || 0
1482
+ }
1483
+ };
1484
+ }
1485
+ },
1486
+ async fetchModels(endpoint, apiKey) {
1487
+ try {
1488
+ const res = await fetch(
1489
+ `${endpoint || this.defaultEndpoint}/v1beta/models?key=${apiKey}`
1490
+ );
1491
+ if (!res.ok) return this.models;
1492
+ const data = await res.json();
1493
+ return (data.models || []).filter((m) => m.name.includes("gemini") && m.supportedGenerationMethods?.includes("generateContent")).map((m) => ({
1494
+ id: m.name.replace("models/", ""),
1495
+ name: m.displayName || m.name.replace("models/", "")
1496
+ }));
1497
+ } catch {
1498
+ return this.models;
1499
+ }
1500
+ },
1501
+ async ping(endpoint, apiKey) {
1502
+ try {
1503
+ const res = await fetch(
1504
+ `${endpoint || this.defaultEndpoint}/v1beta/models?key=${apiKey}`,
1505
+ { signal: AbortSignal.timeout(8e3) }
1506
+ );
1507
+ return res.ok;
1508
+ } catch {
1509
+ return false;
1510
+ }
1511
+ }
1512
+ },
1513
+ claude: {
1514
+ id: "claude",
1515
+ name: "Anthropic Claude",
1516
+ icon: "\u{1F7E0}",
1517
+ authType: "x-api-key",
1518
+ defaultEndpoint: "https://api.anthropic.com",
1519
+ models: [
1520
+ { id: "claude-opus-4-7", name: "Claude Opus 4.7" },
1521
+ { id: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },
1522
+ { id: "claude-haiku-4-5", name: "Claude Haiku 4.5" },
1523
+ { id: "claude-opus-4-6", name: "Claude Opus 4.6" }
1524
+ ],
1525
+ modelsFetchable: true,
1526
+ buildRequest(prompt, model, options = {}) {
1527
+ const userContent = [];
1528
+ if (options.images?.length) {
1529
+ options.images.forEach((img) => {
1530
+ userContent.push({
1531
+ type: "image",
1532
+ source: {
1533
+ type: "base64",
1534
+ media_type: "image/jpeg",
1535
+ data: img.replace(/^data:image\/\w+;base64,/, "")
1536
+ }
1537
+ });
1538
+ });
1539
+ }
1540
+ userContent.push({ type: "text", text: prompt });
1541
+ return {
1542
+ url: `${options.endpoint || this.defaultEndpoint}/v1/messages`,
1543
+ method: "POST",
1544
+ headers: {
1545
+ "Content-Type": "application/json",
1546
+ "x-api-key": options.apiKey || "",
1547
+ "anthropic-version": "2024-01-01",
1548
+ "anthropic-dangerous-direct-browser-access": "true"
1549
+ },
1550
+ body: {
1551
+ model,
1552
+ max_tokens: options.maxTokens || 2048,
1553
+ ...options.systemPrompt ? { system: options.systemPrompt } : {},
1554
+ messages: [
1555
+ { role: "user", content: options.images?.length ? userContent : prompt }
1556
+ ]
1557
+ }
1558
+ };
1559
+ },
1560
+ parseResponse(data) {
1561
+ const content = data.content?.[0]?.text || "";
1562
+ try {
1563
+ const parsed = JSON.parse(content);
1564
+ return {
1565
+ success: true,
1566
+ result: parsed,
1567
+ meta: {
1568
+ model: data.model || "",
1569
+ inputTokens: data.usage?.input_tokens || 0,
1570
+ outputTokens: data.usage?.output_tokens || 0
1571
+ }
1572
+ };
1573
+ } catch {
1574
+ return {
1575
+ success: true,
1576
+ result: { raw: content },
1577
+ meta: {
1578
+ model: data.model || "",
1579
+ inputTokens: data.usage?.input_tokens || 0,
1580
+ outputTokens: data.usage?.output_tokens || 0
1581
+ }
1582
+ };
1583
+ }
1584
+ },
1585
+ async fetchModels(endpoint, apiKey) {
1586
+ try {
1587
+ const res = await fetch(`${endpoint || this.defaultEndpoint}/v1/models`, {
1588
+ headers: {
1589
+ "x-api-key": apiKey || "",
1590
+ "anthropic-version": "2024-01-01"
1591
+ },
1592
+ signal: AbortSignal.timeout(8e3)
1593
+ });
1594
+ if (!res.ok) return this.models;
1595
+ const data = await res.json();
1596
+ return (data.data || []).filter((m) => m.id.startsWith("claude")).map((m) => ({ id: m.id, name: m.display_name || m.id })).sort((a, b) => a.name.localeCompare(b.name));
1597
+ } catch {
1598
+ return this.models;
1599
+ }
1600
+ },
1601
+ async ping(endpoint, apiKey) {
1602
+ try {
1603
+ const res = await fetch(`${endpoint || this.defaultEndpoint}/v1/messages`, {
1604
+ method: "POST",
1605
+ headers: {
1606
+ "Content-Type": "application/json",
1607
+ "x-api-key": apiKey || "",
1608
+ "anthropic-version": "2024-01-01",
1609
+ "anthropic-dangerous-direct-browser-access": "true"
1610
+ },
1611
+ body: JSON.stringify({
1612
+ model: "claude-haiku-4-5",
1613
+ max_tokens: 1,
1614
+ messages: [{ role: "user", content: "Hi" }]
1615
+ }),
1616
+ signal: AbortSignal.timeout(1e4)
1617
+ });
1618
+ return res.ok;
1619
+ } catch {
1620
+ return false;
1621
+ }
1622
+ }
1623
+ }
1624
+ };
1625
+ function getProvider(id) {
1626
+ return PROVIDERS[id] || PROVIDERS.ollama;
1627
+ }
1628
+
1629
+ // extension/core/ai-client.js
1630
+ var AIClient = class {
1631
+ constructor(endpoint = "http://localhost:11434", options = {}) {
1632
+ this.endpoint = endpoint.replace(/\/$/, "");
1633
+ this.providerId = options.provider || "ollama";
1634
+ this.apiKey = options.apiKey || "";
1635
+ this.abortController = null;
1636
+ this.provider = getProvider(this.providerId);
1637
+ }
1638
+ /**
1639
+ * Update provider configuration
1640
+ */
1641
+ setProvider(providerId, apiKey = "", endpoint = "") {
1642
+ this.providerId = providerId;
1643
+ this.apiKey = apiKey;
1644
+ this.provider = getProvider(providerId);
1645
+ if (endpoint) {
1646
+ this.endpoint = endpoint.replace(/\/$/, "");
1647
+ } else {
1648
+ this.endpoint = this.provider.defaultEndpoint;
1649
+ }
1650
+ }
1651
+ /**
1652
+ * Check if AI server is reachable
1653
+ */
1654
+ async ping() {
1655
+ return this.provider.ping(this.endpoint, this.apiKey);
1656
+ }
1657
+ /**
1658
+ * List all available models
1659
+ */
1660
+ async listModels() {
1661
+ return this.provider.fetchModels(this.endpoint, this.apiKey);
1662
+ }
1663
+ /**
1664
+ * Send a single evaluation prompt and get structured response
1665
+ * Retries once on 500 errors
1666
+ */
1667
+ async evaluate(prompt, options = {}) {
1668
+ const {
1669
+ model = "gemma4",
1670
+ systemPrompt = "",
1671
+ temperature = 0.3,
1672
+ format = "json",
1673
+ maxRetries = 1,
1674
+ maxTokens = 4096,
1675
+ images = []
1676
+ } = options;
1677
+ let lastError = null;
1678
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
1679
+ this.abortController = new AbortController();
1680
+ try {
1681
+ if (attempt > 0) {
1682
+ console.log(`[synthux] Retrying AI call (attempt ${attempt + 1})...`);
1683
+ await new Promise((r) => setTimeout(r, 3e3));
1684
+ }
1685
+ const req = this.provider.buildRequest(prompt, model, {
1686
+ endpoint: this.endpoint,
1687
+ apiKey: this.apiKey,
1688
+ systemPrompt,
1689
+ temperature,
1690
+ format,
1691
+ maxTokens,
1692
+ images: images.filter(Boolean)
1693
+ });
1694
+ const response = await fetch(req.url, {
1695
+ method: req.method,
1696
+ headers: req.headers,
1697
+ signal: this.abortController.signal,
1698
+ body: JSON.stringify(req.body)
1699
+ });
1700
+ if (!response.ok) {
1701
+ const errorText = await response.text();
1702
+ console.error(`[synthux] HTTP ${response.status} from ${req.url}:`, errorText.substring(0, 300));
1703
+ lastError = new Error(`${this.provider.name} error (${response.status}): ${errorText}`);
1704
+ if (response.status >= 500 && attempt < maxRetries) {
1705
+ console.warn(`[synthux] ${this.provider.name} 500 error, will retry...`);
1706
+ continue;
1707
+ }
1708
+ if (response.status === 401 || response.status === 403) {
1709
+ if (this.providerId === "ollama") {
1710
+ return {
1711
+ success: false,
1712
+ error: 'Ollama is blocking requests from this extension (CORS). Set OLLAMA_ORIGINS="*" and restart Ollama.',
1713
+ errorType: "cors"
1714
+ };
1715
+ }
1716
+ return {
1717
+ success: false,
1718
+ error: `Invalid API key for ${this.provider.name}. Check your settings. (HTTP ${response.status})`
1719
+ };
1720
+ }
1721
+ if (response.status === 429) {
1722
+ return {
1723
+ success: false,
1724
+ error: `Rate limit exceeded for ${this.provider.name}. Try again later.`
1725
+ };
1726
+ }
1727
+ return {
1728
+ success: false,
1729
+ error: response.status >= 500 ? `${this.provider.name} server error. Try again or restart.` : lastError.message
1730
+ };
1731
+ }
1732
+ const data = await response.json();
1733
+ const parsed = this.provider.parseResponse(data);
1734
+ return parsed;
1735
+ } catch (err) {
1736
+ if (err.name === "AbortError") {
1737
+ return { success: false, error: "Evaluation cancelled" };
1738
+ }
1739
+ lastError = err;
1740
+ if (attempt < maxRetries) continue;
1741
+ return { success: false, error: `AI evaluation failed: ${err.message}` };
1742
+ } finally {
1743
+ this.abortController = null;
1744
+ }
1745
+ }
1746
+ return { success: false, error: lastError?.message || "Unknown error" };
1747
+ }
1748
+ /**
1749
+ * Stream evaluation response (for progress display)
1750
+ * Currently only supported for Ollama
1751
+ */
1752
+ async *evaluateStream(prompt, options = {}) {
1753
+ const {
1754
+ model = "gemma4",
1755
+ systemPrompt = "",
1756
+ temperature = 0.3
1757
+ } = options;
1758
+ if (this.providerId !== "ollama") {
1759
+ const result = await this.evaluate(prompt, options);
1760
+ yield {
1761
+ token: result.success ? JSON.stringify(result.result) : result.error,
1762
+ done: true,
1763
+ meta: result.meta || null
1764
+ };
1765
+ return;
1766
+ }
1767
+ this.abortController = new AbortController();
1768
+ try {
1769
+ const response = await fetch(`${this.endpoint}/api/generate`, {
1770
+ method: "POST",
1771
+ headers: { "Content-Type": "application/json" },
1772
+ signal: this.abortController.signal,
1773
+ body: JSON.stringify({
1774
+ model,
1775
+ prompt,
1776
+ system: systemPrompt,
1777
+ stream: true,
1778
+ options: {
1779
+ temperature,
1780
+ num_predict: 2048
1781
+ }
1782
+ })
1783
+ });
1784
+ if (!response.ok) {
1785
+ throw new Error(`Ollama error (${response.status})`);
1786
+ }
1787
+ const reader = response.body.getReader();
1788
+ const decoder = new TextDecoder();
1789
+ let buffer = "";
1790
+ while (true) {
1791
+ const { done, value } = await reader.read();
1792
+ if (done) break;
1793
+ buffer += decoder.decode(value, { stream: true });
1794
+ const lines = buffer.split("\n");
1795
+ buffer = lines.pop() || "";
1796
+ for (const line of lines) {
1797
+ if (line.trim()) {
1798
+ try {
1799
+ const chunk = JSON.parse(line);
1800
+ yield {
1801
+ token: chunk.response || "",
1802
+ done: chunk.done || false,
1803
+ meta: chunk.done ? {
1804
+ model: chunk.model,
1805
+ totalDuration: chunk.total_duration,
1806
+ evalCount: chunk.eval_count
1807
+ } : null
1808
+ };
1809
+ } catch {
1810
+ }
1811
+ }
1812
+ }
1813
+ }
1814
+ } finally {
1815
+ this.abortController = null;
1816
+ }
1817
+ }
1818
+ /**
1819
+ * Cancel any ongoing evaluation
1820
+ */
1821
+ cancel() {
1822
+ if (this.abortController) {
1823
+ this.abortController.abort();
1824
+ this.abortController = null;
1825
+ }
1826
+ }
1827
+ };
1828
+
1829
+ // mcp/server.js
1830
+ var __filename = fileURLToPath(import.meta.url);
1831
+ var __dirname = path.dirname(__filename);
1832
+ var ROOT_DIR = path.resolve(__dirname, "..");
1833
+ var RULES_DIR = [
1834
+ path.join(__dirname, "rules"),
1835
+ path.join(__dirname, "..", "rules"),
1836
+ path.join(ROOT_DIR, "extension", "rules"),
1837
+ path.join(__dirname, "..", "..", "extension", "rules")
1838
+ ].find((dir) => fs.existsSync(dir)) || path.join(ROOT_DIR, "extension", "rules");
1839
+ var LOOPBACK_HOST = "127.0.0.1";
1840
+ var PORT = Number(process.env.SYNTHUX_MCP_PORT || 17483);
1841
+ var REQUIRED_TOKEN = (process.env.SYNTHUX_MCP_TOKEN || "").trim();
1842
+ var SERVER_INFO = {
1843
+ name: "synthux-mcp",
1844
+ version: "2.1.0"
1845
+ };
1846
+ var PROTOCOL_VERSION = "2024-11-05";
1847
+ var localState = {
1848
+ customRulePacks: [],
1849
+ customProfiles: [],
1850
+ lastReport: null,
1851
+ reportHistory: [],
1852
+ aiSettings: {
1853
+ ollamaEndpoint: process.env.OLLAMA_HOST || "http://localhost:11434",
1854
+ ollamaModel: process.env.SYNTHUX_MODEL || "gemma4",
1855
+ providerId: "ollama",
1856
+ apiKey: "",
1857
+ rulePackId: "nielsen-10",
1858
+ analysisMode: "deep",
1859
+ language: "en",
1860
+ enableVision: true
1861
+ }
1862
+ };
1863
+ function loadRulePackFromDisk(rulePackId = "nielsen-10") {
1864
+ const custom = localState.customRulePacks.find((p) => p.id === rulePackId);
1865
+ if (custom) return custom;
1866
+ const builtIn = BUILT_IN_RULE_PACKS.find((p) => p.id === rulePackId) || BUILT_IN_RULE_PACKS[0];
1867
+ const filePath = path.join(RULES_DIR, path.basename(builtIn.file));
1868
+ const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
1869
+ return {
1870
+ ...raw,
1871
+ id: raw.id || builtIn.id,
1872
+ shortName: raw.shortName || builtIn.shortName,
1873
+ category: raw.category || builtIn.category
1874
+ };
1875
+ }
1876
+ function isAllowedOrigin(originHeader) {
1877
+ if (!originHeader) return true;
1878
+ if (originHeader.startsWith("chrome-extension://")) return true;
1879
+ return false;
1880
+ }
1881
+ function validateSafeHttpUrl(urlStr) {
1882
+ if (!urlStr) return false;
1883
+ try {
1884
+ const parsed = new URL(urlStr);
1885
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
1886
+ } catch {
1887
+ return false;
1888
+ }
1889
+ }
1890
+ var WebSocketConnection = class {
1891
+ constructor(socket) {
1892
+ this.socket = socket;
1893
+ this.isAlive = true;
1894
+ this.extensionInfo = null;
1895
+ this.authenticated = !REQUIRED_TOKEN;
1896
+ this._buffer = Buffer.alloc(0);
1897
+ socket.on("data", (chunk) => this._onData(chunk));
1898
+ socket.on("close", () => this._onClose());
1899
+ socket.on("error", () => this._onClose());
1900
+ }
1901
+ send(obj) {
1902
+ if (this.socket.destroyed) return;
1903
+ const payload = Buffer.from(JSON.stringify(obj), "utf8");
1904
+ const len = payload.length;
1905
+ let header;
1906
+ if (len < 126) {
1907
+ header = Buffer.alloc(2);
1908
+ header[0] = 129;
1909
+ header[1] = len;
1910
+ } else if (len < 65536) {
1911
+ header = Buffer.alloc(4);
1912
+ header[0] = 129;
1913
+ header[1] = 126;
1914
+ header.writeUInt16BE(len, 2);
1915
+ } else {
1916
+ header = Buffer.alloc(10);
1917
+ header[0] = 129;
1918
+ header[1] = 127;
1919
+ header.writeBigUInt64BE(BigInt(len), 2);
1920
+ }
1921
+ try {
1922
+ this.socket.write(Buffer.concat([header, payload]));
1923
+ } catch {
1924
+ }
1925
+ }
1926
+ close() {
1927
+ if (!this.socket.destroyed) {
1928
+ try {
1929
+ this.socket.end(Buffer.from([136, 0]));
1930
+ } catch {
1931
+ }
1932
+ this.socket.destroy();
1933
+ }
1934
+ }
1935
+ _onData(chunk) {
1936
+ this._buffer = Buffer.concat([this._buffer, chunk]);
1937
+ while (this._buffer.length >= 2) {
1938
+ const firstByte = this._buffer[0];
1939
+ const secondByte = this._buffer[1];
1940
+ const opcode = firstByte & 15;
1941
+ const isMasked = (secondByte & 128) !== 0;
1942
+ let payloadLen = secondByte & 127;
1943
+ let offset = 2;
1944
+ if (payloadLen === 126) {
1945
+ if (this._buffer.length < 4) return;
1946
+ payloadLen = this._buffer.readUInt16BE(2);
1947
+ offset = 4;
1948
+ } else if (payloadLen === 127) {
1949
+ if (this._buffer.length < 10) return;
1950
+ payloadLen = Number(this._buffer.readBigUInt64BE(2));
1951
+ offset = 10;
1952
+ }
1953
+ const maskKeyLen = isMasked ? 4 : 0;
1954
+ const totalFrameLen = offset + maskKeyLen + payloadLen;
1955
+ if (this._buffer.length < totalFrameLen) return;
1956
+ let payload = this._buffer.subarray(offset + maskKeyLen, totalFrameLen);
1957
+ if (isMasked) {
1958
+ const maskKey = this._buffer.subarray(offset, offset + 4);
1959
+ const unmasked = Buffer.alloc(payloadLen);
1960
+ for (let i = 0; i < payloadLen; i++) {
1961
+ unmasked[i] = payload[i] ^ maskKey[i % 4];
1962
+ }
1963
+ payload = unmasked;
1964
+ }
1965
+ this._buffer = this._buffer.subarray(totalFrameLen);
1966
+ if (opcode === 8) {
1967
+ this.close();
1968
+ return;
1969
+ }
1970
+ if (opcode === 9) {
1971
+ this.socket.write(Buffer.from([138, 0]));
1972
+ continue;
1973
+ }
1974
+ if (opcode === 1) {
1975
+ const text = payload.toString("utf8");
1976
+ this.onMessage?.(text);
1977
+ }
1978
+ }
1979
+ }
1980
+ _onClose() {
1981
+ this.onClose?.();
1982
+ }
1983
+ };
1984
+ var activeExtensionClient = null;
1985
+ var pendingCommands = /* @__PURE__ */ new Map();
1986
+ var isProxyMode = false;
1987
+ function sendExtensionCommand(command, params = {}, timeoutMs = 12e4) {
1988
+ if (!activeExtensionClient || !activeExtensionClient.authenticated) {
1989
+ return Promise.reject(new Error("Chrome extension is not connected to MCP Bridge. Ensure the synthux extension is loaded in Chrome and MCP Bridge is enabled in Settings."));
1990
+ }
1991
+ const id = `cmd_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1992
+ return new Promise((resolve, reject) => {
1993
+ const timer = setTimeout(() => {
1994
+ pendingCommands.delete(id);
1995
+ reject(new Error(`Extension command "${command}" timed out after ${Math.round(timeoutMs / 1e3)}s.`));
1996
+ }, timeoutMs);
1997
+ pendingCommands.set(id, { resolve, reject, timer });
1998
+ activeExtensionClient.send({
1999
+ type: "MCP_COMMAND",
2000
+ id,
2001
+ command,
2002
+ params
2003
+ });
2004
+ });
2005
+ }
2006
+ var MCP_TOOLS = [
2007
+ {
2008
+ name: "synthux_status",
2009
+ description: "Check synthux MCP Server status, Chrome Extension live WebSocket connection, active browser tab, available Sectoral Rule Packs, Personas, and AI provider (Ollama Local LLM / Cloud API) status.",
2010
+ inputSchema: {
2011
+ type: "object",
2012
+ properties: {}
2013
+ }
2014
+ },
2015
+ {
2016
+ name: "synthux_open_url",
2017
+ description: "Open or navigate a Chrome tab to a target URL and wait for the page to finish loading so synthux can audit it.",
2018
+ inputSchema: {
2019
+ type: "object",
2020
+ properties: {
2021
+ url: { type: "string", description: "Target http:// or https:// URL to open and audit" },
2022
+ newTab: { type: "boolean", description: "Open in a new tab instead of reusing active tab (default: false)" },
2023
+ active: { type: "boolean", description: "Focus the tab in Chrome (default: true)" }
2024
+ },
2025
+ required: ["url"]
2026
+ }
2027
+ },
2028
+ {
2029
+ name: "synthux_list_tabs",
2030
+ description: "List all open web tabs in Chrome with their tabId, title, and URL.",
2031
+ inputSchema: {
2032
+ type: "object",
2033
+ properties: {}
2034
+ }
2035
+ },
2036
+ {
2037
+ name: "synthux_scan_page",
2038
+ description: "Extract comprehensive DOM structure, headings, landmarks, forms, navigation depth, CTAs, color contrast samples, unlabeled interactive elements, and performance metrics from the active tab or target URL.",
2039
+ inputSchema: {
2040
+ type: "object",
2041
+ properties: {
2042
+ url: { type: "string", description: "Optional URL to navigate to before scanning" },
2043
+ tabId: { type: "number", description: "Optional Chrome tab ID (uses active tab if omitted)" },
2044
+ includeScreenshot: { type: "boolean", description: "Also capture full-page screenshot (default: false)" }
2045
+ }
2046
+ }
2047
+ },
2048
+ {
2049
+ name: "synthux_run_wcag_audit",
2050
+ description: "Run deterministic accessibility checks (10 rule-based DOM checks) combined with live axe-core WCAG 2.2 AA compliance auditing on the target page.",
2051
+ inputSchema: {
2052
+ type: "object",
2053
+ properties: {
2054
+ url: { type: "string", description: "Optional URL to open before running WCAG 2.2 AA audit" },
2055
+ tabId: { type: "number", description: "Optional Chrome tab ID" },
2056
+ pageData: { type: "object", description: "Optional pre-extracted pageData for offline/headless testing" }
2057
+ }
2058
+ }
2059
+ },
2060
+ {
2061
+ name: "synthux_run_ux_audit",
2062
+ description: "Run a full autonomous synthux UX audit using the selected Sectoral Rule Pack (nielsen-10, ecommerce, saas, fintech, or custom pack), Synthetic Personas, and AI provider (Local Ollama gemma4/qwen3.8/deepseek-r1 or Cloud Gemini/OpenAI/Claude).",
2063
+ inputSchema: {
2064
+ type: "object",
2065
+ properties: {
2066
+ url: { type: "string", description: "Optional URL to open and analyze" },
2067
+ tabId: { type: "number", description: "Optional Chrome tab ID" },
2068
+ rulePackId: {
2069
+ type: "string",
2070
+ description: 'Rule pack ID: "nielsen-10", "ecommerce", "saas", "fintech", or a custom rule pack ID',
2071
+ default: "nielsen-10"
2072
+ },
2073
+ mode: {
2074
+ type: "string",
2075
+ enum: ["quick", "deep", "custom"],
2076
+ description: 'Analysis depth: "quick" (top 3 rules), "deep" (all rules), or "custom"',
2077
+ default: "quick"
2078
+ },
2079
+ profiles: {
2080
+ type: "array",
2081
+ items: { type: "string" },
2082
+ description: 'Persona IDs: ["first-time", "power-user", "accessibility"] or custom persona IDs'
2083
+ },
2084
+ heuristics: {
2085
+ type: "array",
2086
+ items: { type: "string" },
2087
+ description: 'Specific heuristic rule IDs when mode is "custom"'
2088
+ },
2089
+ provider: {
2090
+ type: "string",
2091
+ enum: ["ollama", "gemini", "openai", "claude"],
2092
+ description: "Optional AI provider override"
2093
+ },
2094
+ model: {
2095
+ type: "string",
2096
+ description: 'Optional model override (e.g., "gemma4", "qwen3.8", "deepseek-r1", "gemini-2.5-flash")'
2097
+ }
2098
+ }
2099
+ }
2100
+ },
2101
+ {
2102
+ name: "synthux_prepare_external_audit",
2103
+ description: "Agent-Brain Mode (Step 1): Scans the page in Chrome, runs axe-core WCAG 2.2 AA checks, captures a screenshot, and builds the exact Sectoral Rule Pack + Persona evaluation prompts so YOU (the connected MCP AI Agent, e.g. Antigravity Gemini 4 Argon, Claude, Cursor, Codex) can evaluate the UX directly without needing a separate LLM call inside the extension.",
2104
+ inputSchema: {
2105
+ type: "object",
2106
+ properties: {
2107
+ url: { type: "string", description: "Optional URL to open and scan" },
2108
+ tabId: { type: "number", description: "Optional Chrome tab ID" },
2109
+ rulePackId: {
2110
+ type: "string",
2111
+ description: 'Rule pack ID: "nielsen-10", "ecommerce", "saas", "fintech", or custom pack ID',
2112
+ default: "nielsen-10"
2113
+ },
2114
+ mode: {
2115
+ type: "string",
2116
+ enum: ["quick", "deep", "custom"],
2117
+ default: "quick"
2118
+ },
2119
+ profiles: {
2120
+ type: "array",
2121
+ items: { type: "string" },
2122
+ description: 'Persona IDs (e.g., ["first-time", "accessibility"])'
2123
+ },
2124
+ heuristics: {
2125
+ type: "array",
2126
+ items: { type: "string" }
2127
+ },
2128
+ includeScreenshot: {
2129
+ type: "boolean",
2130
+ description: "Include base64 screenshot in response (default: false to save context tokens)"
2131
+ },
2132
+ pageData: {
2133
+ type: "object",
2134
+ description: "Optional pre-extracted pageData for offline/headless testing when browser is closed"
2135
+ }
2136
+ }
2137
+ }
2138
+ },
2139
+ {
2140
+ name: "synthux_submit_external_audit",
2141
+ description: "Agent-Brain Mode (Step 2): Submit the heuristic evaluations generated by the MCP AI Agent back to synthux. Computes weighted scores, deduplicates issues, renders the live Issue Heatmap on the Chrome tab, captures an Annotated Screenshot with numbered markers, updates the Side Panel UI, and returns the complete Enhanced v2.0 Markdown & JSON Report.",
2142
+ inputSchema: {
2143
+ type: "object",
2144
+ properties: {
2145
+ tabId: { type: "number", description: "Optional Chrome tab ID" },
2146
+ url: { type: "string", description: "Page URL (used when running in standalone/offline mode)" },
2147
+ title: { type: "string", description: "Page title" },
2148
+ rulePackId: { type: "string", default: "nielsen-10" },
2149
+ mode: { type: "string", default: "quick" },
2150
+ model: { type: "string", description: 'Name of the MCP Agent model that performed the evaluation (e.g., "Gemini 4 Argon")' },
2151
+ showHeatmap: { type: "boolean", description: "Render live issue heatmap on the Chrome page (default: true)" },
2152
+ pageData: { type: "object", description: "Optional pageData for offline report generation" },
2153
+ evaluations: {
2154
+ type: "array",
2155
+ description: "Array of evaluations per profile and heuristic",
2156
+ items: {
2157
+ type: "object",
2158
+ properties: {
2159
+ profileId: { type: "string" },
2160
+ heuristicId: { type: "string" },
2161
+ heuristicName: { type: "string" },
2162
+ evaluation: {
2163
+ type: "object",
2164
+ properties: {
2165
+ score: { type: "number" },
2166
+ summary: { type: "string" },
2167
+ issues: { type: "array", items: { type: "object" } },
2168
+ positives: { type: "array", items: { type: "string" } },
2169
+ score_justification: { type: "string" }
2170
+ }
2171
+ }
2172
+ },
2173
+ required: ["profileId", "heuristicId", "evaluation"]
2174
+ }
2175
+ }
2176
+ },
2177
+ required: ["evaluations"]
2178
+ }
2179
+ },
2180
+ {
2181
+ name: "synthux_run_flow_audit",
2182
+ description: "Run a multi-page User Journey Flow Builder analysis across 2 or more URLs. Evaluates navigation consistency, visual coherence, flow progression, and terminology across steps.",
2183
+ inputSchema: {
2184
+ type: "object",
2185
+ properties: {
2186
+ pages: {
2187
+ type: "array",
2188
+ description: "Ordered list of pages in the user journey (minimum 2)",
2189
+ items: {
2190
+ type: "object",
2191
+ properties: {
2192
+ id: { type: "string" },
2193
+ url: { type: "string" },
2194
+ label: { type: "string" }
2195
+ },
2196
+ required: ["url"]
2197
+ }
2198
+ },
2199
+ connectors: {
2200
+ type: "array",
2201
+ items: {
2202
+ type: "object",
2203
+ properties: {
2204
+ fromId: { type: "string" },
2205
+ toId: { type: "string" }
2206
+ }
2207
+ }
2208
+ },
2209
+ notes: {
2210
+ type: "array",
2211
+ items: {
2212
+ type: "object",
2213
+ properties: {
2214
+ text: { type: "string" },
2215
+ attachedTo: { type: "string" }
2216
+ }
2217
+ }
2218
+ },
2219
+ profiles: {
2220
+ type: "array",
2221
+ items: { type: "string" }
2222
+ }
2223
+ },
2224
+ required: ["pages"]
2225
+ }
2226
+ },
2227
+ {
2228
+ name: "synthux_visual_overlay",
2229
+ description: "Control live visual overlays on the active Chrome tab: highlight specific problematic CSS selectors, show/hide the severity Issue Heatmap, clear overlays, or capture an Annotated Visual Audit screenshot.",
2230
+ inputSchema: {
2231
+ type: "object",
2232
+ properties: {
2233
+ action: {
2234
+ type: "string",
2235
+ enum: ["highlight", "clear_highlight", "heatmap", "clear_heatmap", "clear_all", "annotated_screenshot", "full_screenshot"],
2236
+ description: "Visual overlay action to execute in Chrome"
2237
+ },
2238
+ tabId: { type: "number" },
2239
+ selector: { type: "string", description: 'CSS selector to highlight (when action="highlight")' },
2240
+ severity: { type: "string", enum: ["critical", "moderate", "minor"], description: "Highlight color severity" },
2241
+ label: { type: "string", description: "Tooltip label for highlighted element" },
2242
+ issues: {
2243
+ type: "array",
2244
+ description: "Issues array with element CSS selectors and severities (for heatmap or annotated_screenshot)",
2245
+ items: { type: "object" }
2246
+ }
2247
+ },
2248
+ required: ["action"]
2249
+ }
2250
+ },
2251
+ {
2252
+ name: "synthux_manage_rule_packs",
2253
+ description: "List built-in Sectoral Rule Packs (nielsen-10, ecommerce, saas, fintech) and custom packs, inspect rules inside a pack, import/validate a new custom JSON rule pack, or delete a custom rule pack.",
2254
+ inputSchema: {
2255
+ type: "object",
2256
+ properties: {
2257
+ action: {
2258
+ type: "string",
2259
+ enum: ["list", "get", "save", "delete"],
2260
+ default: "list"
2261
+ },
2262
+ rulePackId: { type: "string", description: 'Rule pack ID for "get" or "delete"' },
2263
+ rulePack: {
2264
+ type: "object",
2265
+ description: 'Custom JSON rule pack object to validate and save (for action="save")'
2266
+ }
2267
+ }
2268
+ }
2269
+ },
2270
+ {
2271
+ name: "synthux_manage_personas",
2272
+ description: "List built-in Synthetic User Personas (first-time, power-user, accessibility) and custom personas, create a new custom persona (ageRange, techLevel, disabilities, goal), or delete a custom persona.",
2273
+ inputSchema: {
2274
+ type: "object",
2275
+ properties: {
2276
+ action: {
2277
+ type: "string",
2278
+ enum: ["list", "save", "delete"],
2279
+ default: "list"
2280
+ },
2281
+ profileId: { type: "string", description: "Custom persona ID to delete" },
2282
+ persona: {
2283
+ type: "object",
2284
+ description: 'New custom persona definition (for action="save")',
2285
+ properties: {
2286
+ name: { type: "string" },
2287
+ description: { type: "string" },
2288
+ ageRange: { type: "string", enum: ["18-25", "25-35", "35-50", "50-65", "65+"] },
2289
+ techLevel: { type: "string", enum: ["low", "medium", "high"] },
2290
+ disabilities: { type: "array", items: { type: "string" } },
2291
+ goal: { type: "string" }
2292
+ }
2293
+ }
2294
+ }
2295
+ }
2296
+ },
2297
+ {
2298
+ name: "synthux_configure_ai",
2299
+ description: "Read or update synthux AI provider configuration (Local Ollama gemma4/qwen3.8/deepseek-r1 or Cloud Gemini/OpenAI/Claude) and test provider connectivity.",
2300
+ inputSchema: {
2301
+ type: "object",
2302
+ properties: {
2303
+ action: {
2304
+ type: "string",
2305
+ enum: ["get", "update", "ping"],
2306
+ default: "get"
2307
+ },
2308
+ provider: { type: "string", enum: ["ollama", "gemini", "openai", "claude"] },
2309
+ model: { type: "string" },
2310
+ endpoint: { type: "string" },
2311
+ enableVision: { type: "boolean" },
2312
+ rulePackId: { type: "string" },
2313
+ analysisMode: { type: "string", enum: ["quick", "deep", "custom"] }
2314
+ }
2315
+ }
2316
+ },
2317
+ {
2318
+ name: "synthux_get_reports",
2319
+ description: "Retrieve the latest UX audit report, list report history, or export a report in Enhanced Markdown v2.0 or JSON format.",
2320
+ inputSchema: {
2321
+ type: "object",
2322
+ properties: {
2323
+ action: {
2324
+ type: "string",
2325
+ enum: ["latest", "history", "by_id"],
2326
+ default: "latest"
2327
+ },
2328
+ id: { type: "string", description: 'Report ID when action="by_id"' },
2329
+ format: {
2330
+ type: "string",
2331
+ enum: ["json", "markdown"],
2332
+ default: "markdown"
2333
+ }
2334
+ }
2335
+ }
2336
+ }
2337
+ ];
2338
+ async function executeToolCall(name, args = {}) {
2339
+ if (args.url && !validateSafeHttpUrl(args.url)) {
2340
+ throw new Error("Security Policy: Only valid http:// and https:// URLs are permitted.");
2341
+ }
2342
+ const extConnected = !!(activeExtensionClient && activeExtensionClient.authenticated);
2343
+ switch (name) {
2344
+ case "synthux_status": {
2345
+ let extStatus = null;
2346
+ if (extConnected) {
2347
+ try {
2348
+ extStatus = await sendExtensionCommand("PING_EXTENSION", {}, 1e4);
2349
+ } catch (err) {
2350
+ extStatus = { connected: false, error: err.message };
2351
+ }
2352
+ }
2353
+ const client = new AIClient(localState.aiSettings.ollamaEndpoint, {
2354
+ provider: localState.aiSettings.providerId,
2355
+ apiKey: localState.aiSettings.apiKey
2356
+ });
2357
+ let localAiPing = null;
2358
+ try {
2359
+ localAiPing = await client.ping();
2360
+ } catch {
2361
+ localAiPing = { status: "offline" };
2362
+ }
2363
+ return {
2364
+ mcpServer: {
2365
+ ...SERVER_INFO,
2366
+ host: LOOPBACK_HOST,
2367
+ port: PORT,
2368
+ streamableHttpUrl: `http://${LOOPBACK_HOST}:${PORT}/mcp`,
2369
+ wsBridgeUrl: `ws://${LOOPBACK_HOST}:${PORT}/ws`,
2370
+ security: {
2371
+ loopbackOnly: true,
2372
+ originVerification: true,
2373
+ tokenAuthEnabled: !!REQUIRED_TOKEN
2374
+ }
2375
+ },
2376
+ chromeExtension: extConnected ? { connected: true, ...extStatus } : {
2377
+ connected: false,
2378
+ note: "Chrome extension is not currently connected over WebSocket. Offline/standalone engine tools (rule packs, personas, WCAG checks, external audit preparation/submission, report generation, and local AI ping) remain 100% available."
2379
+ },
2380
+ localAiStatus: localAiPing,
2381
+ builtInRulePacks: BUILT_IN_RULE_PACKS.map((p) => ({ id: p.id, name: p.name, ruleCount: p.ruleCount })),
2382
+ builtInPersonas: Object.keys(PROFILES)
2383
+ };
2384
+ }
2385
+ case "synthux_open_url": {
2386
+ if (!extConnected) {
2387
+ throw new Error("Opening a live browser tab requires the synthux Chrome extension to be connected to ws://127.0.0.1:17483/ws.");
2388
+ }
2389
+ return await sendExtensionCommand("OPEN_AND_WAIT_TAB", args, 25e3);
2390
+ }
2391
+ case "synthux_list_tabs": {
2392
+ if (!extConnected) {
2393
+ return {
2394
+ success: true,
2395
+ extensionConnected: false,
2396
+ tabs: [],
2397
+ note: "Chrome extension is not connected."
2398
+ };
2399
+ }
2400
+ return await sendExtensionCommand("LIST_TABS", {}, 1e4);
2401
+ }
2402
+ case "synthux_scan_page": {
2403
+ if (extConnected) {
2404
+ return await sendExtensionCommand("SCAN_PAGE", args, 3e4);
2405
+ }
2406
+ throw new Error("Scanning a live browser DOM requires the synthux Chrome extension to be connected, or pass pre-extracted pageData to synthux_run_wcag_audit / synthux_prepare_external_audit.");
2407
+ }
2408
+ case "synthux_run_wcag_audit": {
2409
+ if (extConnected && !args.pageData) {
2410
+ return await sendExtensionCommand("RUN_WCAG_AUDIT", args, 3e4);
2411
+ }
2412
+ const pageData = args.pageData || {
2413
+ meta: { title: "Sample Page", lang: "en" },
2414
+ structure: { headings: [{ level: 1, text: "Main Heading" }], landmarks: [{ role: "main" }], forms: [] },
2415
+ navigation: { navCount: 1, skipLinks: true },
2416
+ content: { images: [], ctas: [] },
2417
+ accessibility: { hasLangAttr: true, contrastResults: [], tabOrderIssues: [], unlabeledInteractives: [] }
2418
+ };
2419
+ const accessibilityResults = runAccessibilityChecks(pageData);
2420
+ return {
2421
+ success: true,
2422
+ mode: "standalone-engine",
2423
+ accessibilityResults
2424
+ };
2425
+ }
2426
+ case "synthux_run_ux_audit": {
2427
+ if (extConnected) {
2428
+ return await sendExtensionCommand("START_ANALYSIS", args, 3e5);
2429
+ }
2430
+ throw new Error("Live browser autonomous audit requires the Chrome extension connection, or use synthux_prepare_external_audit + synthux_submit_external_audit for Agent-Brain evaluation.");
2431
+ }
2432
+ case "synthux_prepare_external_audit": {
2433
+ if (extConnected && !args.pageData) {
2434
+ return await sendExtensionCommand("PREPARE_EXTERNAL_AUDIT", args, 45e3);
2435
+ }
2436
+ const rulePackId = args.rulePackId || "nielsen-10";
2437
+ const mode = args.mode || "quick";
2438
+ const profileIds = Array.isArray(args.profiles) && args.profiles.length > 0 ? args.profiles : ["first-time", "power-user", "accessibility"];
2439
+ const pageData = args.pageData || {
2440
+ meta: { title: args.title || "Audited Page", lang: "en", description: "" },
2441
+ structure: { headings: [{ level: 1, text: "Welcome" }], landmarks: [{ role: "main" }], forms: [] },
2442
+ navigation: { navCount: 1, skipLinks: false, breadcrumb: false },
2443
+ content: { textLength: 450, wordCount: 75, images: [], imageCount: 0, imagesWithoutAlt: 0, ctas: ["Get Started"] },
2444
+ accessibility: { hasLangAttr: true, ariaRoles: ["main"], contrastResults: [], tabOrderIssues: [], unlabeledInteractives: [] },
2445
+ performance: { domSize: 120, scriptCount: 2, styleSheetCount: 1 }
2446
+ };
2447
+ const rules = loadRulePackFromDisk(rulePackId);
2448
+ const accessibilityResults = runAccessibilityChecks(pageData);
2449
+ const evaluationTasks = [];
2450
+ for (const pid of profileIds) {
2451
+ const profile = getProfile(pid) || localState.customProfiles.find((p) => p.id === pid);
2452
+ if (!profile) continue;
2453
+ const selectedRules = args.heuristics && args.heuristics.length > 0 ? (rules.rules || []).filter((r) => args.heuristics.includes(r.id)) : selectHeuristics(rules, mode, pid);
2454
+ for (const heuristic of selectedRules) {
2455
+ evaluationTasks.push({
2456
+ profileId: profile.id,
2457
+ profileName: profile.name?.en || profile.name,
2458
+ heuristicId: heuristic.id,
2459
+ heuristicName: heuristic.name?.en || heuristic.name,
2460
+ weight: heuristic.weight || 1,
2461
+ prompt: buildPrompt(heuristic, profile, pageData, false)
2462
+ });
2463
+ }
2464
+ }
2465
+ return {
2466
+ success: true,
2467
+ executionMode: "standalone-engine",
2468
+ rulePack: {
2469
+ id: rules.id || rulePackId,
2470
+ name: rules.name,
2471
+ shortName: rules.shortName,
2472
+ ruleCount: (rules.rules || []).length
2473
+ },
2474
+ mode,
2475
+ profiles: profileIds,
2476
+ accessibilityResults,
2477
+ evaluationTasks
2478
+ };
2479
+ }
2480
+ case "synthux_submit_external_audit": {
2481
+ if (extConnected && !args.pageData) {
2482
+ return await sendExtensionCommand("SUBMIT_EXTERNAL_AUDIT", args, 45e3);
2483
+ }
2484
+ const rulePackId = args.rulePackId || "nielsen-10";
2485
+ const mode = args.mode || "quick";
2486
+ const rules = loadRulePackFromDisk(rulePackId);
2487
+ const pageData = args.pageData || {
2488
+ meta: { title: args.title || "Audited Page", lang: "en" },
2489
+ structure: { headings: [{ level: 1, text: "Main" }], landmarks: [{ role: "main" }], forms: [] },
2490
+ navigation: { navCount: 1, skipLinks: true },
2491
+ content: { images: [], ctas: [] },
2492
+ accessibility: { hasLangAttr: true, contrastResults: [], tabOrderIssues: [], unlabeledInteractives: [] }
2493
+ };
2494
+ const accessibilityResults = runAccessibilityChecks(pageData);
2495
+ const rawEvaluations = Array.isArray(args.evaluations) ? args.evaluations : [];
2496
+ const profileGroups = /* @__PURE__ */ new Map();
2497
+ for (const item of rawEvaluations) {
2498
+ const pid = item.profileId || "first-time";
2499
+ if (!profileGroups.has(pid)) profileGroups.set(pid, []);
2500
+ const ruleObj = (rules.rules || []).find((r) => r.id === item.heuristicId) || {
2501
+ id: item.heuristicId || "general",
2502
+ name: { en: item.heuristicName || item.heuristicId || "General Usability" }
2503
+ };
2504
+ const parsed = parseEvaluation(item.evaluation || item);
2505
+ profileGroups.get(pid).push({
2506
+ heuristicId: ruleObj.id,
2507
+ heuristicName: ruleObj.name,
2508
+ ...parsed
2509
+ });
2510
+ }
2511
+ const profileResults = {};
2512
+ for (const [pid, evaluations] of profileGroups.entries()) {
2513
+ const profile = getProfile(pid) || localState.customProfiles.find((p) => p.id === pid) || {
2514
+ id: pid,
2515
+ icon: "\u{1F464}",
2516
+ name: { en: pid, tr: pid },
2517
+ description: { en: "MCP Persona", tr: "MCP Personas\u0131" }
2518
+ };
2519
+ const score = calculateOverallScore(evaluations, rules);
2520
+ profileResults[pid] = {
2521
+ profile: {
2522
+ id: profile.id,
2523
+ icon: profile.icon || "\u{1F464}",
2524
+ name: profile.name,
2525
+ description: profile.description,
2526
+ custom: profile.custom || false
2527
+ },
2528
+ score,
2529
+ evaluations
2530
+ };
2531
+ }
2532
+ const allScores = Object.values(profileResults).map((r) => r.score);
2533
+ const overallScore = allScores.length > 0 ? Math.round(allScores.reduce((a, b) => a + b, 0) / allScores.length) : accessibilityResults.score;
2534
+ const allIssues = [];
2535
+ Object.values(profileResults).forEach((pr) => {
2536
+ pr.evaluations.forEach((ev) => {
2537
+ (ev.issues || []).forEach((issue) => {
2538
+ allIssues.push({
2539
+ ...issue,
2540
+ heuristic: ev.heuristicName?.en || ev.heuristicName,
2541
+ profile: pr.profile.name?.en || pr.profile.name,
2542
+ profileIcon: pr.profile.icon || "\u{1F464}"
2543
+ });
2544
+ });
2545
+ });
2546
+ });
2547
+ const report = generateReport({
2548
+ url: args.url || "https://synthux.app",
2549
+ title: args.title || pageData.meta?.title || "MCP Audited Page",
2550
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2551
+ model: args.model || "Gemini 4 Argon (MCP Agent)",
2552
+ mode,
2553
+ provider: "mcp-agent",
2554
+ rulePackId: rules.id || rulePackId,
2555
+ rulePackName: rules.name,
2556
+ rulePackShortName: rules.shortName || "Nielsen 10",
2557
+ ruleCount: (rules.rules || []).length,
2558
+ overallScore,
2559
+ profileResults,
2560
+ accessibilityResults,
2561
+ issues: allIssues,
2562
+ screenshot: null,
2563
+ annotatedScreenshot: null,
2564
+ costSummary: null
2565
+ });
2566
+ localState.lastReport = report;
2567
+ localState.reportHistory.unshift({
2568
+ id: `mcp-${Date.now()}`,
2569
+ url: report.url,
2570
+ title: report.title,
2571
+ score: report.overallScore,
2572
+ mode: report.mode,
2573
+ model: report.model,
2574
+ timestamp: report.timestamp,
2575
+ report
2576
+ });
2577
+ return {
2578
+ success: true,
2579
+ executionMode: "standalone-engine",
2580
+ report
2581
+ };
2582
+ }
2583
+ case "synthux_run_flow_audit": {
2584
+ if (extConnected) {
2585
+ return await sendExtensionCommand("START_FLOW_ANALYSIS", args, 3e5);
2586
+ }
2587
+ throw new Error("Multi-page Flow Builder navigation requires the synthux Chrome extension to be connected.");
2588
+ }
2589
+ case "synthux_visual_overlay": {
2590
+ if (extConnected) {
2591
+ return await sendExtensionCommand("VISUAL_OVERLAY", args, 2e4);
2592
+ }
2593
+ throw new Error("Visual overlays (Heatmap, Highlight, Annotated Screenshot) require the live Chrome extension connection.");
2594
+ }
2595
+ case "synthux_manage_rule_packs": {
2596
+ if (extConnected) {
2597
+ return await sendExtensionCommand("MANAGE_RULE_PACKS", args, 15e3);
2598
+ }
2599
+ const action = args.action || "list";
2600
+ if (action === "list") {
2601
+ return {
2602
+ success: true,
2603
+ rulePacks: [...BUILT_IN_RULE_PACKS, ...localState.customRulePacks]
2604
+ };
2605
+ }
2606
+ if (action === "get") {
2607
+ return {
2608
+ success: true,
2609
+ rulePack: loadRulePackFromDisk(args.rulePackId || "nielsen-10")
2610
+ };
2611
+ }
2612
+ if (action === "save") {
2613
+ const normalized = validateAndNormalizeRulePack(args.rulePack);
2614
+ const idx = localState.customRulePacks.findIndex((p) => p.id === normalized.id);
2615
+ if (idx >= 0) localState.customRulePacks[idx] = normalized;
2616
+ else localState.customRulePacks.push(normalized);
2617
+ return { success: true, rulePack: normalized };
2618
+ }
2619
+ if (action === "delete") {
2620
+ localState.customRulePacks = localState.customRulePacks.filter((p) => p.id !== args.rulePackId);
2621
+ return { success: true, customRulePacks: localState.customRulePacks };
2622
+ }
2623
+ throw new Error(`Unknown rule pack action: ${action}`);
2624
+ }
2625
+ case "synthux_manage_personas": {
2626
+ if (extConnected) {
2627
+ return await sendExtensionCommand("MANAGE_PERSONAS", args, 15e3);
2628
+ }
2629
+ const action = args.action || "list";
2630
+ if (action === "list") {
2631
+ return {
2632
+ success: true,
2633
+ profiles: [...Object.values(PROFILES), ...localState.customProfiles]
2634
+ };
2635
+ }
2636
+ if (action === "save") {
2637
+ const p = args.persona || {};
2638
+ if (!p.name) throw new Error("Persona name is required.");
2639
+ const newProfile = {
2640
+ id: `custom-${Date.now()}`,
2641
+ icon: "\u{1F464}",
2642
+ custom: true,
2643
+ name: { en: p.name, tr: p.name },
2644
+ description: { en: p.description || "", tr: p.description || "" },
2645
+ ageRange: p.ageRange || "25-35",
2646
+ techLevel: p.techLevel || "medium",
2647
+ disabilities: p.disabilities || [],
2648
+ goal: p.goal || "",
2649
+ weight: 1,
2650
+ systemPrompt: buildCustomSystemPrompt(p)
2651
+ };
2652
+ localState.customProfiles.push(newProfile);
2653
+ return { success: true, profile: newProfile };
2654
+ }
2655
+ if (action === "delete") {
2656
+ localState.customProfiles = localState.customProfiles.filter((p) => p.id !== args.profileId);
2657
+ return { success: true, customProfiles: localState.customProfiles };
2658
+ }
2659
+ throw new Error(`Unknown persona action: ${action}`);
2660
+ }
2661
+ case "synthux_configure_ai": {
2662
+ if (extConnected) {
2663
+ return await sendExtensionCommand("CONFIGURE_AI", args, 15e3);
2664
+ }
2665
+ if (args.action === "update") {
2666
+ if (args.provider) localState.aiSettings.providerId = args.provider;
2667
+ if (args.model) localState.aiSettings.ollamaModel = args.model;
2668
+ if (args.endpoint) localState.aiSettings.ollamaEndpoint = args.endpoint;
2669
+ if (typeof args.enableVision === "boolean") localState.aiSettings.enableVision = args.enableVision;
2670
+ if (args.rulePackId) localState.aiSettings.rulePackId = args.rulePackId;
2671
+ if (args.analysisMode) localState.aiSettings.analysisMode = args.analysisMode;
2672
+ }
2673
+ const client = new AIClient(localState.aiSettings.ollamaEndpoint, {
2674
+ provider: localState.aiSettings.providerId,
2675
+ apiKey: localState.aiSettings.apiKey
2676
+ });
2677
+ const pingResult = await client.ping();
2678
+ const models = await client.listModels();
2679
+ return {
2680
+ success: true,
2681
+ settings: {
2682
+ ...localState.aiSettings,
2683
+ apiKey: localState.aiSettings.apiKey ? "***configured***" : ""
2684
+ },
2685
+ connectionStatus: {
2686
+ ping: pingResult,
2687
+ models
2688
+ }
2689
+ };
2690
+ }
2691
+ case "synthux_get_reports": {
2692
+ if (extConnected) {
2693
+ return await sendExtensionCommand("GET_REPORTS", args, 15e3);
2694
+ }
2695
+ const action = args.action || "latest";
2696
+ if (action === "history") {
2697
+ return {
2698
+ success: true,
2699
+ history: localState.reportHistory.map((r) => ({
2700
+ id: r.id,
2701
+ url: r.url,
2702
+ title: r.title,
2703
+ score: r.score,
2704
+ mode: r.mode,
2705
+ model: r.model,
2706
+ timestamp: r.timestamp
2707
+ }))
2708
+ };
2709
+ }
2710
+ if (action === "by_id" && args.id) {
2711
+ const entry = localState.reportHistory.find((r) => r.id === args.id);
2712
+ if (!entry) throw new Error(`Report ${args.id} not found.`);
2713
+ return {
2714
+ success: true,
2715
+ report: args.format === "markdown" ? entry.report.markdown : entry.report
2716
+ };
2717
+ }
2718
+ if (!localState.lastReport) {
2719
+ return { error: "No report generated yet in this session." };
2720
+ }
2721
+ return {
2722
+ success: true,
2723
+ report: args.format === "markdown" ? localState.lastReport.markdown : localState.lastReport
2724
+ };
2725
+ }
2726
+ default:
2727
+ throw new Error(`Unknown tool: ${name}`);
2728
+ }
2729
+ }
2730
+ async function handleJsonRpcMessage(msg) {
2731
+ if (!msg || typeof msg !== "object") return null;
2732
+ if (isProxyMode && (msg.method === "tools/call" || msg.method === "resources/read")) {
2733
+ try {
2734
+ const res = await fetch(`http://${LOOPBACK_HOST}:${PORT}/mcp`, {
2735
+ method: "POST",
2736
+ headers: {
2737
+ "Content-Type": "application/json",
2738
+ ...REQUIRED_TOKEN ? { "x-synthux-token": REQUIRED_TOKEN } : {}
2739
+ },
2740
+ body: JSON.stringify(msg)
2741
+ });
2742
+ if (res.ok) {
2743
+ return await res.json();
2744
+ }
2745
+ } catch {
2746
+ isProxyMode = false;
2747
+ }
2748
+ }
2749
+ const { id, method, params } = msg;
2750
+ if (id === void 0 || id === null) {
2751
+ return null;
2752
+ }
2753
+ try {
2754
+ switch (method) {
2755
+ case "initialize":
2756
+ return {
2757
+ jsonrpc: "2.0",
2758
+ id,
2759
+ result: {
2760
+ protocolVersion: params?.protocolVersion || PROTOCOL_VERSION,
2761
+ capabilities: {
2762
+ tools: { listChanged: false },
2763
+ resources: { listChanged: false },
2764
+ prompts: { listChanged: false }
2765
+ },
2766
+ serverInfo: SERVER_INFO
2767
+ }
2768
+ };
2769
+ case "ping":
2770
+ return {
2771
+ jsonrpc: "2.0",
2772
+ id,
2773
+ result: {}
2774
+ };
2775
+ case "tools/list":
2776
+ return {
2777
+ jsonrpc: "2.0",
2778
+ id,
2779
+ result: {
2780
+ tools: MCP_TOOLS
2781
+ }
2782
+ };
2783
+ case "tools/call": {
2784
+ const toolName = params?.name;
2785
+ const toolArgs = params?.arguments || {};
2786
+ const output = await executeToolCall(toolName, toolArgs);
2787
+ return {
2788
+ jsonrpc: "2.0",
2789
+ id,
2790
+ result: {
2791
+ content: [
2792
+ {
2793
+ type: "text",
2794
+ text: typeof output === "string" ? output : JSON.stringify(output, null, 2)
2795
+ }
2796
+ ],
2797
+ isError: !!output?.error
2798
+ }
2799
+ };
2800
+ }
2801
+ case "resources/list":
2802
+ return {
2803
+ jsonrpc: "2.0",
2804
+ id,
2805
+ result: {
2806
+ resources: BUILT_IN_RULE_PACKS.map((pack) => ({
2807
+ uri: `synthux://rules/${pack.id}`,
2808
+ name: pack.name,
2809
+ description: pack.description,
2810
+ mimeType: "application/json"
2811
+ }))
2812
+ }
2813
+ };
2814
+ case "resources/read": {
2815
+ const uri = String(params?.uri || "");
2816
+ const match = uri.match(/^synthux:\/\/rules\/(.+)$/);
2817
+ const packId = match ? match[1] : "nielsen-10";
2818
+ const data = loadRulePackFromDisk(packId);
2819
+ return {
2820
+ jsonrpc: "2.0",
2821
+ id,
2822
+ result: {
2823
+ contents: [
2824
+ {
2825
+ uri,
2826
+ mimeType: "application/json",
2827
+ text: JSON.stringify(data, null, 2)
2828
+ }
2829
+ ]
2830
+ }
2831
+ };
2832
+ }
2833
+ case "prompts/list":
2834
+ return {
2835
+ jsonrpc: "2.0",
2836
+ id,
2837
+ result: {
2838
+ prompts: [
2839
+ {
2840
+ name: "audit_website_ux",
2841
+ description: "Run a complete end-to-end UX & WCAG 2.2 AA audit on a target URL using synthux",
2842
+ arguments: [
2843
+ { name: "url", description: "Website URL to audit", required: true },
2844
+ { name: "rulePackId", description: "Rule pack (nielsen-10, ecommerce, saas, fintech)", required: false }
2845
+ ]
2846
+ }
2847
+ ]
2848
+ }
2849
+ };
2850
+ case "prompts/get": {
2851
+ const url = params?.arguments?.url || "https://example.com";
2852
+ const rulePackId = params?.arguments?.rulePackId || "nielsen-10";
2853
+ return {
2854
+ jsonrpc: "2.0",
2855
+ id,
2856
+ result: {
2857
+ description: `Audit ${url} with synthux (${rulePackId})`,
2858
+ messages: [
2859
+ {
2860
+ role: "user",
2861
+ content: {
2862
+ type: "text",
2863
+ text: `Please audit ${url} using the synthux MCP tools with rulePackId="${rulePackId}". First call synthux_prepare_external_audit (or synthux_run_ux_audit), evaluate the heuristics, and then submit the findings via synthux_submit_external_audit to generate the live heatmap and Enhanced v2.0 UX Audit Report.`
2864
+ }
2865
+ }
2866
+ ]
2867
+ }
2868
+ };
2869
+ }
2870
+ default:
2871
+ return {
2872
+ jsonrpc: "2.0",
2873
+ id,
2874
+ error: {
2875
+ code: -32601,
2876
+ message: `Method not found: ${method}`
2877
+ }
2878
+ };
2879
+ }
2880
+ } catch (err) {
2881
+ return {
2882
+ jsonrpc: "2.0",
2883
+ id,
2884
+ result: {
2885
+ content: [
2886
+ {
2887
+ type: "text",
2888
+ text: JSON.stringify({ error: err.message || String(err) }, null, 2)
2889
+ }
2890
+ ],
2891
+ isError: true
2892
+ }
2893
+ };
2894
+ }
2895
+ }
2896
+ async function handleHttpRequest(req, res) {
2897
+ const origin = req.headers?.origin;
2898
+ if (!isAllowedOrigin(origin)) {
2899
+ res.writeHead(403, { "Content-Type": "application/json" });
2900
+ res.end(JSON.stringify({ error: "Forbidden: Web origins are blocked by synthux security policy." }));
2901
+ return;
2902
+ }
2903
+ if (REQUIRED_TOKEN) {
2904
+ const headerToken = req.headers["x-synthux-token"] || (req.headers.authorization || "").replace(/^Bearer\s+/i, "");
2905
+ if (headerToken !== REQUIRED_TOKEN) {
2906
+ res.writeHead(401, { "Content-Type": "application/json" });
2907
+ res.end(JSON.stringify({ error: "Unauthorized: Invalid SYNTHUX_MCP_TOKEN." }));
2908
+ return;
2909
+ }
2910
+ }
2911
+ const url = new URL(req.url || "/", `http://${LOOPBACK_HOST}:${PORT}`);
2912
+ if (req.method === "GET" && url.pathname === "/health") {
2913
+ res.writeHead(200, { "Content-Type": "application/json" });
2914
+ res.end(JSON.stringify({
2915
+ status: "ok",
2916
+ server: SERVER_INFO,
2917
+ extensionConnected: !!(activeExtensionClient && activeExtensionClient.authenticated)
2918
+ }));
2919
+ return;
2920
+ }
2921
+ if (url.pathname === "/mcp") {
2922
+ if (req.method === "POST") {
2923
+ let body = "";
2924
+ req.on("data", (chunk) => {
2925
+ body += chunk.toString("utf8");
2926
+ if (body.length > 25 * 1024 * 1024) req.destroy?.();
2927
+ });
2928
+ req.on("end", async () => {
2929
+ try {
2930
+ const parsed = JSON.parse(body);
2931
+ if (Array.isArray(parsed)) {
2932
+ const responses = (await Promise.all(parsed.map((m) => handleJsonRpcMessage(m)))).filter(Boolean);
2933
+ res.writeHead(200, { "Content-Type": "application/json" });
2934
+ res.end(JSON.stringify(responses));
2935
+ } else {
2936
+ const response = await handleJsonRpcMessage(parsed);
2937
+ if (!response) {
2938
+ res.writeHead(202);
2939
+ res.end();
2940
+ } else {
2941
+ res.writeHead(200, { "Content-Type": "application/json" });
2942
+ res.end(JSON.stringify(response));
2943
+ }
2944
+ }
2945
+ } catch (err) {
2946
+ res.writeHead(400, { "Content-Type": "application/json" });
2947
+ res.end(JSON.stringify({
2948
+ jsonrpc: "2.0",
2949
+ id: null,
2950
+ error: { code: -32700, message: `Parse error: ${err.message}` }
2951
+ }));
2952
+ }
2953
+ });
2954
+ return;
2955
+ }
2956
+ if (req.method === "GET") {
2957
+ res.writeHead(200, { "Content-Type": "application/json" });
2958
+ res.end(JSON.stringify({
2959
+ name: SERVER_INFO.name,
2960
+ version: SERVER_INFO.version,
2961
+ transport: "streamable-http",
2962
+ endpoint: `http://${LOOPBACK_HOST}:${PORT}/mcp`,
2963
+ extensionConnected: !!(activeExtensionClient && activeExtensionClient.authenticated)
2964
+ }));
2965
+ return;
2966
+ }
2967
+ }
2968
+ res.writeHead(404, { "Content-Type": "application/json" });
2969
+ res.end(JSON.stringify({ error: "Not Found" }));
2970
+ }
2971
+ function handleWebSocketUpgrade(req, socket) {
2972
+ const origin = req.headers?.origin;
2973
+ if (!isAllowedOrigin(origin)) {
2974
+ socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
2975
+ socket.destroy();
2976
+ return;
2977
+ }
2978
+ const key = req.headers?.["sec-websocket-key"];
2979
+ if (!key) {
2980
+ socket.write("HTTP/1.1 400 Bad Request\r\n\r\n");
2981
+ socket.destroy();
2982
+ return;
2983
+ }
2984
+ const acceptKey = crypto.createHash("sha1").update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64");
2985
+ socket.write(
2986
+ `HTTP/1.1 101 Switching Protocols\r
2987
+ Upgrade: websocket\r
2988
+ Connection: Upgrade\r
2989
+ Sec-WebSocket-Accept: ${acceptKey}\r
2990
+ \r
2991
+ `
2992
+ );
2993
+ const wsClient = new WebSocketConnection(socket);
2994
+ activeExtensionClient = wsClient;
2995
+ wsClient.onMessage = (rawText) => {
2996
+ try {
2997
+ const msg = JSON.parse(rawText);
2998
+ if (msg.type === "PING") {
2999
+ wsClient.send({ type: "PONG", timestamp: Date.now() });
3000
+ return;
3001
+ }
3002
+ if (msg.type === "EXTENSION_HELLO") {
3003
+ if (REQUIRED_TOKEN && msg.token !== REQUIRED_TOKEN) {
3004
+ wsClient.authenticated = false;
3005
+ wsClient.close();
3006
+ return;
3007
+ }
3008
+ wsClient.authenticated = true;
3009
+ wsClient.extensionInfo = {
3010
+ version: msg.version,
3011
+ extensionId: msg.extensionId,
3012
+ connectedAt: msg.timestamp || (/* @__PURE__ */ new Date()).toISOString()
3013
+ };
3014
+ return;
3015
+ }
3016
+ if (msg.type === "MCP_RESPONSE" && msg.id) {
3017
+ const pending = pendingCommands.get(msg.id);
3018
+ if (pending) {
3019
+ clearTimeout(pending.timer);
3020
+ pendingCommands.delete(msg.id);
3021
+ pending.resolve(msg.result);
3022
+ }
3023
+ }
3024
+ } catch {
3025
+ }
3026
+ };
3027
+ wsClient.onClose = () => {
3028
+ if (activeExtensionClient === wsClient) {
3029
+ activeExtensionClient = null;
3030
+ }
3031
+ };
3032
+ }
3033
+ function startBridgeServer(listenOptions = { port: PORT, host: LOOPBACK_HOST }) {
3034
+ const server = http.createServer(handleHttpRequest);
3035
+ server.on("upgrade", handleWebSocketUpgrade);
3036
+ server.on("error", (err) => {
3037
+ if (err.code === "EADDRINUSE") {
3038
+ isProxyMode = true;
3039
+ } else if (err.code === "EPERM" || err.code === "EACCES") {
3040
+ }
3041
+ });
3042
+ try {
3043
+ if (listenOptions.socketPath) {
3044
+ server.listen(listenOptions.socketPath);
3045
+ } else {
3046
+ server.listen(listenOptions.port ?? PORT, listenOptions.host ?? LOOPBACK_HOST);
3047
+ }
3048
+ } catch {
3049
+ }
3050
+ return server;
3051
+ }
3052
+ function startStdioTransport() {
3053
+ const rl = readline.createInterface({
3054
+ input: process.stdin,
3055
+ terminal: false
3056
+ });
3057
+ rl.on("line", async (line) => {
3058
+ const trimmed = line.trim();
3059
+ if (!trimmed) return;
3060
+ try {
3061
+ const msg = JSON.parse(trimmed);
3062
+ const response = await handleJsonRpcMessage(msg);
3063
+ if (response) {
3064
+ process.stdout.write(JSON.stringify(response) + "\n");
3065
+ }
3066
+ } catch (err) {
3067
+ process.stdout.write(JSON.stringify({
3068
+ jsonrpc: "2.0",
3069
+ id: null,
3070
+ error: { code: -32700, message: `Parse error: ${err.message}` }
3071
+ }) + "\n");
3072
+ }
3073
+ });
3074
+ }
3075
+ if (import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith("synthux-mcp") || process.argv[1]?.endsWith("server.js")) {
3076
+ startBridgeServer();
3077
+ startStdioTransport();
3078
+ }
3079
+ export {
3080
+ MCP_TOOLS,
3081
+ executeToolCall,
3082
+ handleHttpRequest,
3083
+ handleJsonRpcMessage,
3084
+ handleWebSocketUpgrade,
3085
+ startBridgeServer
3086
+ };