@mizchi/vlmkit-ai 0.8.0 → 0.8.1

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.
@@ -0,0 +1,256 @@
1
+ import { VrtConfigError } from "./errors.mjs";
2
+ import { createUnifiedLLMClient } from "./llm-client.mjs";
3
+ import { createVlmClient, resolveModel } from "./vlm-client.mjs";
4
+ import { resizeBase64Png } from "@mizchi/vlmkit-core/image-resize.ts";
5
+ //#region src/reasoning-pipeline.ts
6
+ /**
7
+ * VRT Reasoning Pipeline -- two-stage VLM + LLM pipeline
8
+ *
9
+ * Stage 1 (VLM, cheap): heatmap/screenshot -> structured diff report
10
+ * Stage 2 (LLM, expensive): structured report + CSS source -> fix code generation
11
+ *
12
+ * Usage:
13
+ * const pipeline = createReasoningPipeline();
14
+ * const analysis = await pipeline.analyze(heatmapBase64, textReport);
15
+ * const fix = await pipeline.suggestFix(analysis, cssSource);
16
+ */
17
+ const STAGE1_PROMPT = `You are analyzing a VRT (Visual Regression Testing) diff image. The red/pink areas in the heatmap show WHERE pixels differ, NOT the actual colors of the elements.
18
+
19
+ IMPORTANT: Red in the heatmap means "this area changed" — it does NOT mean the element is red. You must infer the actual CSS values from the element context, not from the heatmap color.
20
+
21
+ For each visual change, output ONE line in this EXACT format:
22
+ CHANGE: [element] | [css-property] | [before-value] | [after-value] | [severity:low/medium/high]
23
+
24
+ Example:
25
+ CHANGE: h1 heading | color | #333333 | #111111 | low
26
+ CHANGE: .card | padding | 16px | 12px | medium
27
+ CHANGE: .card | background-color | #f0f0f0 | #eff6ff | medium
28
+ CHANGE: table header | text-transform | none | uppercase | high
29
+
30
+ Rules:
31
+ - Do NOT repeat the same element+property combination.
32
+ - Do NOT confuse heatmap red with actual CSS colors.
33
+ - Use approximate CSS values based on visual appearance.
34
+
35
+ After all changes, add:
36
+ SUMMARY: <one sentence describing the overall change>
37
+ REGRESSION: <yes/no>`;
38
+ function buildStage2Prompt(report, cssSource, cssDiff) {
39
+ const changeList = report.changes.map((c) => `- ${c.element}: ${c.property} changed from "${c.before}" to "${c.after}" (${c.severity})`).join("\n");
40
+ const cssDiffSection = cssDiff ? `\n## CSS Diff from Baseline (authoritative — use these exact values)\n${cssDiff}` : "";
41
+ return `You are fixing CSS to match a target visual appearance.
42
+
43
+ ## Visual Changes Detected (from image analysis)
44
+ ${changeList}
45
+
46
+ Summary: ${report.summary}
47
+ ${cssDiffSection}
48
+
49
+ ## Current CSS
50
+ \`\`\`css
51
+ ${cssSource}
52
+ \`\`\`
53
+
54
+ ## Task
55
+ Provide CSS fixes to restore the baseline appearance. For each fix, output ONE line in this format:
56
+ FIX: [selector] | [property] | [value] | [reason]
57
+
58
+ IMPORTANT RULES:
59
+ - If "CSS Diff from Baseline" is provided above, use those EXACT selectors and values. They are authoritative.
60
+ - Do NOT modify selectors that are not mentioned in the diff.
61
+ - Do NOT guess CSS values — only use values from the diff or the visual analysis.
62
+ - For MISSING rules, add them back exactly as shown.
63
+
64
+ After all fixes, add:
65
+ EXPLANATION: <brief explanation of the root cause>
66
+ CONFIDENCE: <high/medium/low>`;
67
+ }
68
+ function parseStage1Response(raw) {
69
+ const changes = [];
70
+ const seen = /* @__PURE__ */ new Set();
71
+ let summary = "";
72
+ let regression = false;
73
+ for (const line of raw.split("\n")) {
74
+ const trimmed = line.trim();
75
+ const changeMatch = trimmed.match(/^CHANGE:\s*(.+?)\s*\|\s*(.+?)\s*\|\s*(.+?)\s*\|\s*(.+?)\s*\|\s*(low|medium|high)/i);
76
+ if (changeMatch) {
77
+ const key = `${changeMatch[1].trim()}|${changeMatch[2].trim()}`;
78
+ if (seen.has(key)) continue;
79
+ seen.add(key);
80
+ changes.push({
81
+ element: changeMatch[1].trim(),
82
+ property: changeMatch[2].trim(),
83
+ before: changeMatch[3].trim(),
84
+ after: changeMatch[4].trim(),
85
+ severity: changeMatch[5].toLowerCase()
86
+ });
87
+ continue;
88
+ }
89
+ const summaryMatch = trimmed.match(/^SUMMARY:\s*(.+)/i);
90
+ if (summaryMatch) {
91
+ summary = summaryMatch[1].trim();
92
+ continue;
93
+ }
94
+ const regressionMatch = trimmed.match(/^REGRESSION:\s*(yes|no)/i);
95
+ if (regressionMatch) regression = regressionMatch[1].toLowerCase() === "yes";
96
+ }
97
+ return {
98
+ changes,
99
+ summary,
100
+ regression
101
+ };
102
+ }
103
+ function parseStage2Response(raw) {
104
+ const fixes = [];
105
+ let explanation = "";
106
+ let confidence = "medium";
107
+ for (const line of raw.split("\n")) {
108
+ const trimmed = line.trim();
109
+ const fixMatch = trimmed.match(/^FIX:\s*(.+?)\s*\|\s*(.+?)\s*\|\s*(.+?)\s*\|\s*(.+)/i);
110
+ if (fixMatch) {
111
+ fixes.push({
112
+ selector: fixMatch[1].trim(),
113
+ property: fixMatch[2].trim(),
114
+ value: fixMatch[3].trim(),
115
+ reason: fixMatch[4].trim()
116
+ });
117
+ continue;
118
+ }
119
+ const explMatch = trimmed.match(/^EXPLANATION:\s*(.+)/i);
120
+ if (explMatch) {
121
+ explanation = explMatch[1].trim();
122
+ continue;
123
+ }
124
+ const confMatch = trimmed.match(/^CONFIDENCE:\s*(high|medium|low)/i);
125
+ if (confMatch) confidence = confMatch[1].toLowerCase();
126
+ }
127
+ return {
128
+ fixes,
129
+ explanation,
130
+ confidence
131
+ };
132
+ }
133
+ function createReasoningPipeline(config) {
134
+ const throwIfMissing = config?.throwIfMissing ?? true;
135
+ let vlmClient = null;
136
+ let vlmModelId = config?.vlmModel ?? process.env.VRT_VLM_MODEL ?? "bytedance/ui-tars-1.5-7b";
137
+ let llmClient = createUnifiedLLMClient({
138
+ provider: config?.llmProvider,
139
+ model: config?.llmModel,
140
+ throwIfMissing: false
141
+ });
142
+ if (!llmClient) for (const provider of [
143
+ "gemini",
144
+ "anthropic",
145
+ "openrouter"
146
+ ]) {
147
+ llmClient = createUnifiedLLMClient({
148
+ provider,
149
+ throwIfMissing: false
150
+ });
151
+ if (llmClient) break;
152
+ }
153
+ if (!llmClient && !process.env.OPENROUTER_API_KEY) {
154
+ if (throwIfMissing) throw new VrtConfigError("NO_PROVIDER_AVAILABLE", "Reasoning pipeline needs an LLM (GEMINI/ANTHROPIC/OPENROUTER_API_KEY) or a VLM (OPENROUTER_API_KEY).");
155
+ return null;
156
+ }
157
+ return {
158
+ vlmModel: vlmModelId,
159
+ llmModel: llmClient?.model ?? "none",
160
+ async analyze(options) {
161
+ if (!vlmClient) try {
162
+ vlmClient = await createVlmClient(await resolveModel(vlmModelId), { throwIfMissing: false });
163
+ } catch {
164
+ vlmClient = null;
165
+ }
166
+ if (!vlmClient) {
167
+ if (!llmClient) throw new Error("No VLM or LLM available");
168
+ const resp = await llmClient.completeWithImages(options.textReport ?? "No visual data available", { maxTokens: 1024 });
169
+ return {
170
+ ...parseStage1Response(resp.content),
171
+ raw: resp.content,
172
+ vlmModel: resp.model,
173
+ vlmLatencyMs: resp.latencyMs,
174
+ vlmCostUsd: resp.costUsd
175
+ };
176
+ }
177
+ let imageBase64 = null;
178
+ if (options.selectorCropBase64) imageBase64 = options.selectorCropBase64;
179
+ else if (options.heatmapBase64) imageBase64 = options.heatmapBase64;
180
+ else if (options.currentBase64) imageBase64 = options.currentBase64;
181
+ if (!imageBase64) throw new Error("No image data provided for VLM analysis");
182
+ const resolution = options.resolution ?? config?.resolution ?? "medium";
183
+ imageBase64 = resizeBase64Png(imageBase64, { resolution });
184
+ let prompt = STAGE1_PROMPT;
185
+ if (options.shiftInfo) {
186
+ const si = options.shiftInfo;
187
+ prompt += `\n\nShift detection:`;
188
+ if (si.globalShift !== 0) {
189
+ prompt += `\n- Global vertical shift: ${si.globalShift > 0 ? "+" : ""}${si.globalShift}px`;
190
+ prompt += `\n- Compensated diff (shift excluded): ${(si.compensatedDiffRatio * 100).toFixed(1)}%`;
191
+ if (si.shiftOnly) prompt += `\n- SHIFT ONLY: all changes appear to be positional shifts, not content changes. Focus on layout-affecting properties (height, padding, margin).`;
192
+ else prompt += `\n- ${si.contentChangeCount} content change region(s) detected beyond the shift.`;
193
+ } else prompt += `\n- No vertical shift detected.`;
194
+ }
195
+ if (options.compactHeatmap) prompt += `\n\nDiff heatmap (10x10 grid, X=changed, .=unchanged):\n${options.compactHeatmap}`;
196
+ if (options.textReport) prompt += `\n\nAdditional context from VRT pipeline:\n${options.textReport}`;
197
+ const resp = await vlmClient.analyzeImage(imageBase64, prompt, { maxTokens: 1024 });
198
+ return {
199
+ ...parseStage1Response(resp.content),
200
+ raw: resp.content,
201
+ vlmModel: resp.model,
202
+ vlmLatencyMs: resp.latencyMs,
203
+ vlmCostUsd: resp.costUsd
204
+ };
205
+ },
206
+ async suggestFix(report, cssSource, cssDiff) {
207
+ if (!llmClient) throw new Error("No LLM available for Stage 2");
208
+ const prompt = buildStage2Prompt(report, cssSource, cssDiff);
209
+ const resp = await llmClient.completeWithImages(prompt, { maxTokens: 2048 });
210
+ return {
211
+ ...parseStage2Response(resp.content),
212
+ raw: resp.content,
213
+ llmModel: resp.model,
214
+ llmLatencyMs: resp.latencyMs,
215
+ llmCostUsd: resp.costUsd
216
+ };
217
+ },
218
+ async analyzeAndFix(options) {
219
+ const adaptive = config?.adaptiveResolution !== false;
220
+ const maxRes = config?.maxResolution ?? "high";
221
+ const resolutionLadder = [
222
+ "low",
223
+ "medium",
224
+ "high",
225
+ "full"
226
+ ];
227
+ let analysis = await this.analyze(options);
228
+ let fix = await this.suggestFix(analysis, options.cssSource, options.cssDiff);
229
+ let escalated = false;
230
+ if (adaptive && fix.confidence === "low" && analysis.changes.length <= 1) {
231
+ const currentRes = options.resolution ?? config?.resolution ?? "medium";
232
+ const currentIdx = resolutionLadder.indexOf(currentRes);
233
+ if (currentIdx < resolutionLadder.indexOf(maxRes)) {
234
+ const nextRes = resolutionLadder[currentIdx + 1];
235
+ const escalationImage = options.highResHeatmapBase64 ?? options.heatmapBase64;
236
+ if (escalationImage) {
237
+ analysis = await this.analyze({
238
+ ...options,
239
+ heatmapBase64: escalationImage,
240
+ resolution: nextRes
241
+ });
242
+ fix = await this.suggestFix(analysis, options.cssSource, options.cssDiff);
243
+ escalated = true;
244
+ }
245
+ }
246
+ }
247
+ return {
248
+ analysis,
249
+ fix,
250
+ escalated
251
+ };
252
+ }
253
+ };
254
+ }
255
+ //#endregion
256
+ export { createReasoningPipeline };
@@ -0,0 +1,41 @@
1
+ import { A11yDiff, ChangeIntent, PageExpectation } from "@mizchi/vlmkit-core/types.ts";
2
+
3
+ //#region src/reasoning.d.ts
4
+ /**
5
+ * Expectation -> change -> realization reasoning chain
6
+ *
7
+ * 1. Expectation: what we intend to change (intent + expectation)
8
+ * 2. Change: what actually changed (a11y diff)
9
+ * 3. Realization: whether the expectation was realized in a11y semantics
10
+ */
11
+ interface ReasoningChain {
12
+ testId: string;
13
+ /** Expectation summary */
14
+ expectation: string;
15
+ /** Actual changes */
16
+ actualChanges: ActualChange[];
17
+ /** Expectation-to-actual mappings */
18
+ mappings: ExpectationMapping[];
19
+ /** Verdict */
20
+ verdict: "realized" | "partially-realized" | "not-realized" | "unexpected-side-effects";
21
+ /** Human-readable reasoning */
22
+ reasoning: string;
23
+ }
24
+ interface ActualChange {
25
+ type: string;
26
+ description: string;
27
+ path: string;
28
+ severity: string;
29
+ }
30
+ interface ExpectationMapping {
31
+ expected: string;
32
+ actual: string | null;
33
+ realized: boolean;
34
+ reasoning: string;
35
+ }
36
+ /**
37
+ * Reason about whether expected changes were realized in the a11y tree diff.
38
+ */
39
+ declare function reasonAboutChanges(testId: string, pageExp: PageExpectation, a11yDiff: A11yDiff | undefined, intent: ChangeIntent): ReasoningChain;
40
+ //#endregion
41
+ export { ActualChange, ExpectationMapping, ReasoningChain, reasonAboutChanges };
@@ -0,0 +1,148 @@
1
+ import { STOP_WORDS, SYNONYMS } from "./nlp.mjs";
2
+ //#region src/reasoning.ts
3
+ /**
4
+ * Reason about whether expected changes were realized in the a11y tree diff.
5
+ */
6
+ function reasonAboutChanges(testId, pageExp, a11yDiff, intent) {
7
+ const expectation = pageExp.expect ?? pageExp.expectedA11yChanges?.map((e) => e.description).join("; ") ?? intent.summary;
8
+ const actualChanges = (a11yDiff?.changes ?? []).map((c) => ({
9
+ type: c.type,
10
+ description: c.description,
11
+ path: c.path,
12
+ severity: c.severity
13
+ }));
14
+ const expectedChanges = pageExp.expectedA11yChanges ?? [];
15
+ const mappings = [];
16
+ const consumed = /* @__PURE__ */ new Set();
17
+ for (const exp of expectedChanges) {
18
+ const changes = a11yDiff?.changes ?? [];
19
+ const matchedIdx = findBestMatchIdx(exp, changes, consumed);
20
+ if (matchedIdx >= 0) {
21
+ consumed.add(matchedIdx);
22
+ const matchedActual = changes[matchedIdx];
23
+ mappings.push({
24
+ expected: exp.description,
25
+ actual: `${matchedActual.type}: ${matchedActual.description}`,
26
+ realized: true,
27
+ reasoning: buildMappingReasoning(exp, matchedActual)
28
+ });
29
+ } else mappings.push({
30
+ expected: exp.description,
31
+ actual: null,
32
+ realized: false,
33
+ reasoning: `Expected "${exp.description}" was not detected in the a11y diff`
34
+ });
35
+ }
36
+ const sideEffects = actualChanges.filter((_, i) => !consumed.has(i));
37
+ const allRealized = mappings.length > 0 && mappings.every((m) => m.realized);
38
+ const someRealized = mappings.some((m) => m.realized);
39
+ const hasSideEffects = sideEffects.length > 0;
40
+ let verdict;
41
+ if (mappings.length === 0 && actualChanges.length === 0) verdict = "not-realized";
42
+ else if (allRealized && !hasSideEffects) verdict = "realized";
43
+ else if (allRealized && hasSideEffects) verdict = "unexpected-side-effects";
44
+ else if (someRealized) verdict = "partially-realized";
45
+ else verdict = "not-realized";
46
+ const reasoning = buildReasoning(testId, expectation, mappings, sideEffects, verdict);
47
+ return {
48
+ testId,
49
+ expectation,
50
+ actualChanges,
51
+ mappings,
52
+ verdict,
53
+ reasoning
54
+ };
55
+ }
56
+ function findBestMatchIdx(exp, changes, consumed) {
57
+ if (exp.type || exp.role || exp.name) {
58
+ let bestIdx = -1;
59
+ let bestFieldScore = 0;
60
+ for (let i = 0; i < changes.length; i++) {
61
+ if (consumed.has(i)) continue;
62
+ const c = changes[i];
63
+ let fieldScore = 0;
64
+ let fieldCount = 0;
65
+ if (exp.type) {
66
+ fieldCount++;
67
+ if (c.type === exp.type) fieldScore++;
68
+ else continue;
69
+ }
70
+ if (exp.role) {
71
+ fieldCount++;
72
+ const inPath = c.path.toLowerCase().includes(exp.role.toLowerCase());
73
+ const inDesc = c.description.toLowerCase().includes(exp.role.toLowerCase());
74
+ if (inPath || inDesc) fieldScore++;
75
+ else continue;
76
+ }
77
+ if (exp.name) {
78
+ fieldCount++;
79
+ if (c.description.toLowerCase().includes(exp.name.toLowerCase())) fieldScore++;
80
+ else continue;
81
+ }
82
+ if (fieldScore > bestFieldScore) {
83
+ bestFieldScore = fieldScore;
84
+ bestIdx = i;
85
+ }
86
+ }
87
+ if (bestIdx >= 0) return bestIdx;
88
+ }
89
+ const keywords = exp.description.toLowerCase().split(/\s+/).filter((w) => w.length > 2 && !STOP_WORDS.has(w)).flatMap((k) => [k, ...SYNONYMS[k] ?? []]);
90
+ let bestIdx = -1;
91
+ let bestScore = 0;
92
+ for (let i = 0; i < changes.length; i++) {
93
+ if (consumed.has(i)) continue;
94
+ const change = changes[i];
95
+ const target = `${change.type} ${change.description} ${change.path}`.toLowerCase();
96
+ const matched = keywords.filter((k) => target.includes(k)).length;
97
+ const score = keywords.length > 0 ? matched / keywords.length : 0;
98
+ if (score > bestScore && matched >= 2) {
99
+ bestScore = score;
100
+ bestIdx = i;
101
+ }
102
+ }
103
+ return bestIdx;
104
+ }
105
+ function buildMappingReasoning(exp, actual) {
106
+ const parts = [];
107
+ parts.push(`Expected: "${exp.description}"`);
108
+ parts.push(`Actual: [${actual.type}] ${actual.description}`);
109
+ parts.push(`Path: ${actual.path}`);
110
+ if (actual.type === "node-added") parts.push("→ New element was added to the a11y tree, matching expectation");
111
+ else if (actual.type === "node-removed" || actual.type === "landmark-changed") parts.push("→ Element was removed from the a11y tree, matching expectation");
112
+ else if (actual.type === "name-changed") {
113
+ const before = actual.before?.name ?? "(none)";
114
+ const after = actual.after?.name ?? "(none)";
115
+ parts.push(`→ Accessible name changed: "${before}" → "${after}"`);
116
+ } else if (actual.type === "role-changed") parts.push(`→ Role changed: ${actual.before?.role} → ${actual.after?.role}`);
117
+ else if (actual.type === "state-changed") parts.push("→ ARIA state changed");
118
+ return parts.join(". ");
119
+ }
120
+ function buildReasoning(testId, expectation, mappings, sideEffects, verdict) {
121
+ const lines = [];
122
+ lines.push(`[${testId}] Expectation: "${expectation}"`);
123
+ lines.push("");
124
+ if (mappings.length > 0) {
125
+ lines.push("Expectation → Realization mapping:");
126
+ for (const m of mappings) {
127
+ const icon = m.realized ? "✓" : "✗";
128
+ lines.push(` ${icon} ${m.expected}`);
129
+ if (m.actual) lines.push(` ↔ ${m.actual}`);
130
+ lines.push(` ${m.reasoning}`);
131
+ }
132
+ lines.push("");
133
+ }
134
+ if (sideEffects.length > 0) {
135
+ lines.push("Side effects (not in expectations):");
136
+ for (const se of sideEffects) lines.push(` ! [${se.type}] ${se.description}`);
137
+ lines.push("");
138
+ }
139
+ lines.push(`Verdict: ${verdict.toUpperCase()} — ${{
140
+ "realized": "All expected changes were realized in the a11y tree",
141
+ "partially-realized": "Some expected changes were realized, but not all",
142
+ "not-realized": "Expected changes were not detected in the a11y tree",
143
+ "unexpected-side-effects": "All expected changes were realized, but additional unexpected changes were detected"
144
+ }[verdict]}`);
145
+ return lines.join("\n");
146
+ }
147
+ //#endregion
148
+ export { reasonAboutChanges };
@@ -0,0 +1,63 @@
1
+ //#region src/vlm-client.d.ts
2
+ interface VlmModel {
3
+ id: string;
4
+ name: string;
5
+ promptCostPer1k: number;
6
+ completionCostPer1k: number;
7
+ contextLength: number;
8
+ modality: string;
9
+ }
10
+ interface VlmResponse {
11
+ content: string;
12
+ model: string;
13
+ promptTokens: number;
14
+ completionTokens: number;
15
+ totalTokens: number;
16
+ costUsd: number;
17
+ latencyMs: number;
18
+ }
19
+ interface VlmClient {
20
+ model: VlmModel;
21
+ analyzeImage(imageBase64: string, prompt: string, options?: {
22
+ maxTokens?: number;
23
+ }): Promise<VlmResponse>;
24
+ analyzeImageFile(imagePath: string, prompt: string, options?: {
25
+ maxTokens?: number;
26
+ }): Promise<VlmResponse>;
27
+ analyzeDiff(baselineBase64: string, currentBase64: string, prompt: string, options?: {
28
+ maxTokens?: number;
29
+ }): Promise<VlmResponse>;
30
+ }
31
+ declare function fetchVisionModels(): Promise<VlmModel[]>;
32
+ declare function listModels(options?: {
33
+ maxCost?: number;
34
+ limit?: number;
35
+ includeGemini?: boolean;
36
+ includeClaude?: boolean;
37
+ }): Promise<VlmModel[]>;
38
+ declare function resolveModel(idOrIndex: string): Promise<VlmModel>;
39
+ declare function isGeminiDirectModel(id: string): boolean;
40
+ declare function resolveGeminiModel(id: string): VlmModel | undefined;
41
+ declare function listGeminiModels(): VlmModel[];
42
+ declare function isClaudeDirectModel(id: string): boolean;
43
+ declare function resolveClaudeModel(id: string): VlmModel | undefined;
44
+ declare function listClaudeModels(): VlmModel[];
45
+ interface CreateVlmClientOptions {
46
+ /** Override `OPENROUTER_API_KEY` / `GEMINI_API_KEY` lookup. */
47
+ apiKey?: string;
48
+ /**
49
+ * When `false`, return `null` instead of throwing `VrtConfigError`
50
+ * if the required API key is missing. Default: `true`.
51
+ */
52
+ throwIfMissing?: boolean;
53
+ }
54
+ /**
55
+ * Construct a VLM client for the given model.
56
+ *
57
+ * Throws `VrtConfigError` (`code: "MISSING_KEY"`) when the model's
58
+ * required API key isn't set in the environment. Pass
59
+ * `{ throwIfMissing: false }` for the legacy `T | null` return.
60
+ */
61
+ declare function createVlmClient(model: VlmModel, options?: CreateVlmClientOptions): Promise<VlmClient | null>;
62
+ //#endregion
63
+ export { CreateVlmClientOptions, VlmClient, VlmModel, VlmResponse, createVlmClient, fetchVisionModels, isClaudeDirectModel, isGeminiDirectModel, listClaudeModels, listGeminiModels, listModels, resolveClaudeModel, resolveGeminiModel, resolveModel };