@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,310 @@
1
+ import { VrtConfigError } from "./errors.mjs";
2
+ //#region src/llm-client.ts
3
+ function createAnthropicClient(apiKey, model) {
4
+ const modelId = model ?? "claude-sonnet-4-6";
5
+ async function call(content, maxTokens) {
6
+ const start = Date.now();
7
+ const messageContent = typeof content === "string" ? content : content.map((c) => {
8
+ if (c.type === "text") return {
9
+ type: "text",
10
+ text: c.text
11
+ };
12
+ return {
13
+ type: "image",
14
+ source: {
15
+ type: "base64",
16
+ media_type: c.mimeType ?? "image/png",
17
+ data: c.base64
18
+ }
19
+ };
20
+ });
21
+ const res = await fetch("https://api.anthropic.com/v1/messages", {
22
+ method: "POST",
23
+ headers: {
24
+ "content-type": "application/json",
25
+ "x-api-key": apiKey,
26
+ "anthropic-version": "2023-06-01"
27
+ },
28
+ body: JSON.stringify({
29
+ model: modelId,
30
+ max_tokens: maxTokens,
31
+ messages: [{
32
+ role: "user",
33
+ content: messageContent
34
+ }]
35
+ })
36
+ });
37
+ if (!res.ok) {
38
+ const body = (await res.text()).slice(0, 200);
39
+ throw new Error(`Anthropic API error: ${res.status} ${body}`);
40
+ }
41
+ const data = await res.json();
42
+ const latencyMs = Date.now() - start;
43
+ return {
44
+ content: data.content.filter((c) => c.type === "text").map((c) => c.text).join(""),
45
+ model: modelId,
46
+ provider: "anthropic",
47
+ promptTokens: data.usage?.input_tokens ?? 0,
48
+ completionTokens: data.usage?.output_tokens ?? 0,
49
+ costUsd: 0,
50
+ latencyMs
51
+ };
52
+ }
53
+ return {
54
+ provider: "anthropic",
55
+ model: modelId,
56
+ async complete(prompt) {
57
+ return (await call(prompt, 1024)).content;
58
+ },
59
+ async completeWithImages(content, options) {
60
+ return call(content, options?.maxTokens ?? 1024);
61
+ },
62
+ async analyzeDiff(options) {
63
+ return call(buildDiffContent(options), options.maxTokens ?? 1024);
64
+ }
65
+ };
66
+ }
67
+ function createGeminiLLMClient(apiKey, model) {
68
+ const modelId = model ?? "gemini-2.5-flash-preview-05-20";
69
+ async function call(content, maxTokens) {
70
+ const { GoogleGenerativeAI } = await import("@google/generative-ai");
71
+ const genModel = new GoogleGenerativeAI(apiKey).getGenerativeModel({ model: modelId });
72
+ const start = Date.now();
73
+ const parts = typeof content === "string" ? [{ text: content }] : content.map((c) => {
74
+ if (c.type === "text") return { text: c.text };
75
+ return { inlineData: {
76
+ mimeType: c.mimeType ?? "image/png",
77
+ data: c.base64
78
+ } };
79
+ });
80
+ const result = await genModel.generateContent({
81
+ contents: [{
82
+ role: "user",
83
+ parts
84
+ }],
85
+ generationConfig: { maxOutputTokens: maxTokens }
86
+ });
87
+ const latencyMs = Date.now() - start;
88
+ const response = result.response;
89
+ const usage = response.usageMetadata;
90
+ return {
91
+ content: response.text(),
92
+ model: modelId,
93
+ provider: "gemini",
94
+ promptTokens: usage?.promptTokenCount ?? 0,
95
+ completionTokens: usage?.candidatesTokenCount ?? 0,
96
+ costUsd: 0,
97
+ latencyMs
98
+ };
99
+ }
100
+ return {
101
+ provider: "gemini",
102
+ model: modelId,
103
+ async complete(prompt) {
104
+ return (await call(prompt, 1024)).content;
105
+ },
106
+ async completeWithImages(content, options) {
107
+ return call(content, options?.maxTokens ?? 1024);
108
+ },
109
+ async analyzeDiff(options) {
110
+ return call(buildDiffContent(options), options.maxTokens ?? 1024);
111
+ }
112
+ };
113
+ }
114
+ function createOpenRouterLLMClient(apiKey, model) {
115
+ const modelId = model ?? "qwen/qwen3-vl-8b-instruct";
116
+ async function call(content, maxTokens) {
117
+ const start = Date.now();
118
+ const messageContent = typeof content === "string" ? content : content.map((c) => {
119
+ if (c.type === "text") return {
120
+ type: "text",
121
+ text: c.text
122
+ };
123
+ return {
124
+ type: "image_url",
125
+ image_url: { url: `data:${c.mimeType ?? "image/png"};base64,${c.base64}` }
126
+ };
127
+ });
128
+ const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
129
+ method: "POST",
130
+ headers: {
131
+ "Content-Type": "application/json",
132
+ "Authorization": `Bearer ${apiKey}`,
133
+ "HTTP-Referer": "https://github.com/mizchi/vrt"
134
+ },
135
+ body: JSON.stringify({
136
+ model: modelId,
137
+ max_tokens: maxTokens,
138
+ messages: [{
139
+ role: "user",
140
+ content: messageContent
141
+ }]
142
+ })
143
+ });
144
+ if (!res.ok) throw new Error(`OpenRouter API error: ${res.status} ${(await res.text()).slice(0, 200)}`);
145
+ const data = await res.json();
146
+ const latencyMs = Date.now() - start;
147
+ return {
148
+ content: data.choices[0]?.message?.content ?? "",
149
+ model: modelId,
150
+ provider: "openrouter",
151
+ promptTokens: data.usage?.prompt_tokens ?? 0,
152
+ completionTokens: data.usage?.completion_tokens ?? 0,
153
+ costUsd: 0,
154
+ latencyMs
155
+ };
156
+ }
157
+ return {
158
+ provider: "openrouter",
159
+ model: modelId,
160
+ async complete(prompt) {
161
+ return (await call(prompt, 1024)).content;
162
+ },
163
+ async completeWithImages(content, options) {
164
+ return call(content, options?.maxTokens ?? 1024);
165
+ },
166
+ async analyzeDiff(options) {
167
+ return call(buildDiffContent(options), options.maxTokens ?? 1024);
168
+ }
169
+ };
170
+ }
171
+ function buildDiffContent(options) {
172
+ const parts = [];
173
+ if (options.baselineBase64) {
174
+ parts.push({
175
+ type: "text",
176
+ text: "Baseline screenshot:"
177
+ });
178
+ parts.push({
179
+ type: "image",
180
+ base64: options.baselineBase64
181
+ });
182
+ }
183
+ if (options.currentBase64) {
184
+ parts.push({
185
+ type: "text",
186
+ text: "Current screenshot:"
187
+ });
188
+ parts.push({
189
+ type: "image",
190
+ base64: options.currentBase64
191
+ });
192
+ }
193
+ if (options.heatmapBase64) {
194
+ parts.push({
195
+ type: "text",
196
+ text: "Diff heatmap (red = changed pixels):"
197
+ });
198
+ parts.push({
199
+ type: "image",
200
+ base64: options.heatmapBase64
201
+ });
202
+ }
203
+ parts.push({
204
+ type: "text",
205
+ text: options.textReport
206
+ });
207
+ if (options.prompt) parts.push({
208
+ type: "text",
209
+ text: options.prompt
210
+ });
211
+ return parts;
212
+ }
213
+ const VALID_PROVIDERS = new Set([
214
+ "gemini",
215
+ "anthropic",
216
+ "openrouter"
217
+ ]);
218
+ /**
219
+ * Resolve provider and key from environment variables.
220
+ *
221
+ * VRT_LLM_PROVIDER: gemini (default) | anthropic | openrouter
222
+ * VRT_LLM_MODEL: model ID (defaults to provider's default)
223
+ *
224
+ * Returns a config, or describes why no config was available. The
225
+ * factory decides whether to throw based on `throwIfMissing`.
226
+ */
227
+ function resolveProviderConfig(options) {
228
+ const rawProvider = options?.provider ?? process.env.VRT_LLM_PROVIDER ?? "gemini";
229
+ if (!VALID_PROVIDERS.has(rawProvider)) return {
230
+ ok: false,
231
+ code: "INVALID_PROVIDER",
232
+ message: `Unknown VRT_LLM_PROVIDER "${rawProvider}". Expected: gemini | anthropic | openrouter.`
233
+ };
234
+ const provider = rawProvider;
235
+ const model = options?.model ?? process.env.VRT_LLM_MODEL ?? void 0;
236
+ const keyMap = {
237
+ gemini: process.env.GEMINI_API_KEY ?? process.env.GOOGLE_AI_API_KEY,
238
+ anthropic: process.env.ANTHROPIC_API_KEY,
239
+ openrouter: process.env.OPENROUTER_API_KEY
240
+ };
241
+ const envVarName = {
242
+ gemini: "GEMINI_API_KEY (or GOOGLE_AI_API_KEY)",
243
+ anthropic: "ANTHROPIC_API_KEY",
244
+ openrouter: "OPENROUTER_API_KEY"
245
+ };
246
+ const key = keyMap[provider];
247
+ if (!key) return {
248
+ ok: false,
249
+ code: "MISSING_KEY",
250
+ message: `${envVarName[provider]} is required for provider "${provider}".`
251
+ };
252
+ return {
253
+ ok: true,
254
+ provider,
255
+ key,
256
+ model
257
+ };
258
+ }
259
+ /**
260
+ * Create a unified LLM client.
261
+ *
262
+ * Provider is set via `VRT_LLM_PROVIDER` env var (default: `gemini`).
263
+ *
264
+ * Throws `VrtConfigError` when the resolved provider has no API key
265
+ * (`code: "MISSING_KEY"`) or the provider value is unknown
266
+ * (`code: "INVALID_PROVIDER"`). Pass `{ throwIfMissing: false }` for
267
+ * legacy `T | null` return.
268
+ */
269
+ function createUnifiedLLMClient(options) {
270
+ const throwIfMissing = options?.throwIfMissing ?? true;
271
+ const config = resolveProviderConfig(options);
272
+ if (!config.ok) {
273
+ if (throwIfMissing) throw new VrtConfigError(config.code, config.message);
274
+ return null;
275
+ }
276
+ switch (config.provider) {
277
+ case "anthropic": return createAnthropicClient(config.key, config.model);
278
+ case "gemini": return createGeminiLLMClient(config.key, config.model);
279
+ case "openrouter": return createOpenRouterLLMClient(config.key, config.model);
280
+ }
281
+ }
282
+ /**
283
+ * Backwards-compatible: returns the existing `LLMProvider` interface.
284
+ * Uses the provider specified by `VRT_LLM_PROVIDER`. Falls back to
285
+ * other providers if the requested key is missing.
286
+ *
287
+ * Throws `VrtConfigError` (`code: "NO_PROVIDER_AVAILABLE"`) when no
288
+ * provider in the fallback chain has an API key. Pass
289
+ * `{ throwIfMissing: false }` for the legacy `T | null` return.
290
+ */
291
+ function createLLMProvider(options) {
292
+ const throwIfMissing = options?.throwIfMissing ?? true;
293
+ const client = createUnifiedLLMClient({ throwIfMissing: false });
294
+ if (client) return { complete: (prompt) => client.complete(prompt) };
295
+ for (const provider of [
296
+ "gemini",
297
+ "anthropic",
298
+ "openrouter"
299
+ ]) {
300
+ const fb = createUnifiedLLMClient({
301
+ provider,
302
+ throwIfMissing: false
303
+ });
304
+ if (fb) return { complete: (prompt) => fb.complete(prompt) };
305
+ }
306
+ if (throwIfMissing) throw new VrtConfigError("NO_PROVIDER_AVAILABLE", "No LLM provider available. Set one of: GEMINI_API_KEY, ANTHROPIC_API_KEY, OPENROUTER_API_KEY.");
307
+ return null;
308
+ }
309
+ //#endregion
310
+ export { createLLMProvider, createUnifiedLLMClient };
package/dist/nlp.d.mts ADDED
@@ -0,0 +1,8 @@
1
+ //#region src/nlp.d.ts
2
+ /**
3
+ * Text-matching helpers shared between expectation matching and reasoning.
4
+ */
5
+ declare const STOP_WORDS: Set<string>;
6
+ declare const SYNONYMS: Record<string, string[]>;
7
+ //#endregion
8
+ export { STOP_WORDS, SYNONYMS };
package/dist/nlp.mjs ADDED
@@ -0,0 +1,50 @@
1
+ //#region src/nlp.ts
2
+ /**
3
+ * Text-matching helpers shared between expectation matching and reasoning.
4
+ */
5
+ const STOP_WORDS = new Set([
6
+ "gets",
7
+ "from",
8
+ "with",
9
+ "that",
10
+ "this",
11
+ "should",
12
+ "have",
13
+ "the",
14
+ "for",
15
+ "and",
16
+ "all",
17
+ "proper"
18
+ ]);
19
+ const SYNONYMS = {
20
+ input: [
21
+ "textbox",
22
+ "searchbox",
23
+ "combobox"
24
+ ],
25
+ textbox: ["input", "searchbox"],
26
+ searchbox: [
27
+ "input",
28
+ "textbox",
29
+ "search"
30
+ ],
31
+ label: ["name", "accessible"],
32
+ name: ["label"],
33
+ button: ["btn"],
34
+ nav: ["navigation"],
35
+ navigation: ["nav"],
36
+ search: ["searchbox"],
37
+ tab: ["tablist", "tabpanel"],
38
+ tablist: ["tab", "tabs"],
39
+ tabpanel: [
40
+ "tab",
41
+ "panel",
42
+ "content"
43
+ ],
44
+ panel: ["tabpanel"],
45
+ table: ["grid"],
46
+ column: ["columnheader", "header"],
47
+ header: ["columnheader", "column"]
48
+ };
49
+ //#endregion
50
+ export { STOP_WORDS, SYNONYMS };
@@ -0,0 +1,92 @@
1
+ import { ResolutionPreset } from "@mizchi/vlmkit-core/image-resize.ts";
2
+
3
+ //#region src/reasoning-pipeline.d.ts
4
+ interface VisualChange {
5
+ element: string;
6
+ property: string;
7
+ before: string;
8
+ after: string;
9
+ severity: "low" | "medium" | "high";
10
+ }
11
+ interface StructuredDiffReport {
12
+ changes: VisualChange[];
13
+ summary: string;
14
+ regression: boolean;
15
+ raw: string;
16
+ vlmModel: string;
17
+ vlmLatencyMs: number;
18
+ vlmCostUsd: number;
19
+ }
20
+ interface CssFix {
21
+ selector: string;
22
+ property: string;
23
+ value: string;
24
+ reason: string;
25
+ }
26
+ interface FixSuggestion {
27
+ fixes: CssFix[];
28
+ explanation: string;
29
+ confidence: "high" | "medium" | "low";
30
+ raw: string;
31
+ llmModel: string;
32
+ llmLatencyMs: number;
33
+ llmCostUsd: number;
34
+ }
35
+ interface PipelineConfig {
36
+ /** Stage 1: VLM for image analysis (default: qwen3-vl-8b via OpenRouter) */
37
+ vlmModel?: string;
38
+ /** Stage 2: LLM for code generation (default: from VRT_LLM_PROVIDER) */
39
+ llmProvider?: "gemini" | "anthropic" | "openrouter";
40
+ llmModel?: string;
41
+ /** Image resolution (default: medium = 400x300) */
42
+ resolution?: ResolutionPreset;
43
+ /** Auto-escalate when resolution is insufficient (default: true) */
44
+ adaptiveResolution?: boolean;
45
+ /** Escalation ceiling (default: high) */
46
+ maxResolution?: ResolutionPreset;
47
+ /**
48
+ * When `false`, returns `null` instead of throwing `VrtConfigError`
49
+ * if neither VLM nor LLM credentials are available. Default: `true`.
50
+ */
51
+ throwIfMissing?: boolean;
52
+ }
53
+ interface AnalyzeOptions {
54
+ heatmapBase64?: string;
55
+ baselineBase64?: string;
56
+ currentBase64?: string;
57
+ textReport?: string;
58
+ /** Resolution override (takes priority over pipeline config) */
59
+ resolution?: ResolutionPreset;
60
+ /** Cropped region for the target selector (base64 PNG) */
61
+ selectorCropBase64?: string;
62
+ /** Compact ASCII heatmap from DiffReport (10x10 grid + regions) */
63
+ compactHeatmap?: string;
64
+ /** Shift detection results */
65
+ shiftInfo?: {
66
+ globalShift: number;
67
+ shiftOnly: boolean;
68
+ compensatedDiffRatio: number;
69
+ contentChangeCount: number;
70
+ };
71
+ }
72
+ interface ReasoningPipeline {
73
+ /** Stage 1: image -> structured diff */
74
+ analyze(options: AnalyzeOptions): Promise<StructuredDiffReport>;
75
+ /** Stage 2: structured diff + CSS -> fix proposal */
76
+ suggestFix(report: StructuredDiffReport, cssSource: string, cssDiff?: string): Promise<FixSuggestion>;
77
+ /** Run Stage 1 + 2 sequentially. Auto-escalates resolution if needed */
78
+ analyzeAndFix(options: AnalyzeOptions & {
79
+ cssSource: string; /** CSS text diff (MISSING/CHANGED lines. Passed directly to Stage 2) */
80
+ cssDiff?: string; /** High-resolution image for escalation (used by adaptive resolution) */
81
+ highResHeatmapBase64?: string;
82
+ }): Promise<{
83
+ analysis: StructuredDiffReport;
84
+ fix: FixSuggestion;
85
+ escalated: boolean;
86
+ }>;
87
+ vlmModel: string;
88
+ llmModel: string;
89
+ }
90
+ declare function createReasoningPipeline(config?: PipelineConfig): ReasoningPipeline | null;
91
+ //#endregion
92
+ export { AnalyzeOptions, CssFix, FixSuggestion, PipelineConfig, ReasoningPipeline, StructuredDiffReport, VisualChange, createReasoningPipeline };