@mizchi/vlmkit-ai 0.8.0 → 0.9.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.
@@ -0,0 +1,311 @@
1
+ import { VrtConfigError } from "./errors.mjs";
2
+ import { readEnv } from "@mizchi/vlmkit-core/legacy-names.ts";
3
+ //#region src/llm-client.ts
4
+ function createAnthropicClient(apiKey, model) {
5
+ const modelId = model ?? "claude-sonnet-4-6";
6
+ async function call(content, maxTokens) {
7
+ const start = Date.now();
8
+ const messageContent = typeof content === "string" ? content : content.map((c) => {
9
+ if (c.type === "text") return {
10
+ type: "text",
11
+ text: c.text
12
+ };
13
+ return {
14
+ type: "image",
15
+ source: {
16
+ type: "base64",
17
+ media_type: c.mimeType ?? "image/png",
18
+ data: c.base64
19
+ }
20
+ };
21
+ });
22
+ const res = await fetch("https://api.anthropic.com/v1/messages", {
23
+ method: "POST",
24
+ headers: {
25
+ "content-type": "application/json",
26
+ "x-api-key": apiKey,
27
+ "anthropic-version": "2023-06-01"
28
+ },
29
+ body: JSON.stringify({
30
+ model: modelId,
31
+ max_tokens: maxTokens,
32
+ messages: [{
33
+ role: "user",
34
+ content: messageContent
35
+ }]
36
+ })
37
+ });
38
+ if (!res.ok) {
39
+ const body = (await res.text()).slice(0, 200);
40
+ throw new Error(`Anthropic API error: ${res.status} ${body}`);
41
+ }
42
+ const data = await res.json();
43
+ const latencyMs = Date.now() - start;
44
+ return {
45
+ content: data.content.filter((c) => c.type === "text").map((c) => c.text).join(""),
46
+ model: modelId,
47
+ provider: "anthropic",
48
+ promptTokens: data.usage?.input_tokens ?? 0,
49
+ completionTokens: data.usage?.output_tokens ?? 0,
50
+ costUsd: 0,
51
+ latencyMs
52
+ };
53
+ }
54
+ return {
55
+ provider: "anthropic",
56
+ model: modelId,
57
+ async complete(prompt) {
58
+ return (await call(prompt, 1024)).content;
59
+ },
60
+ async completeWithImages(content, options) {
61
+ return call(content, options?.maxTokens ?? 1024);
62
+ },
63
+ async analyzeDiff(options) {
64
+ return call(buildDiffContent(options), options.maxTokens ?? 1024);
65
+ }
66
+ };
67
+ }
68
+ function createGeminiLLMClient(apiKey, model) {
69
+ const modelId = model ?? "gemini-2.5-flash-preview-05-20";
70
+ async function call(content, maxTokens) {
71
+ const { GoogleGenerativeAI } = await import("@google/generative-ai");
72
+ const genModel = new GoogleGenerativeAI(apiKey).getGenerativeModel({ model: modelId });
73
+ const start = Date.now();
74
+ const parts = typeof content === "string" ? [{ text: content }] : content.map((c) => {
75
+ if (c.type === "text") return { text: c.text };
76
+ return { inlineData: {
77
+ mimeType: c.mimeType ?? "image/png",
78
+ data: c.base64
79
+ } };
80
+ });
81
+ const result = await genModel.generateContent({
82
+ contents: [{
83
+ role: "user",
84
+ parts
85
+ }],
86
+ generationConfig: { maxOutputTokens: maxTokens }
87
+ });
88
+ const latencyMs = Date.now() - start;
89
+ const response = result.response;
90
+ const usage = response.usageMetadata;
91
+ return {
92
+ content: response.text(),
93
+ model: modelId,
94
+ provider: "gemini",
95
+ promptTokens: usage?.promptTokenCount ?? 0,
96
+ completionTokens: usage?.candidatesTokenCount ?? 0,
97
+ costUsd: 0,
98
+ latencyMs
99
+ };
100
+ }
101
+ return {
102
+ provider: "gemini",
103
+ model: modelId,
104
+ async complete(prompt) {
105
+ return (await call(prompt, 1024)).content;
106
+ },
107
+ async completeWithImages(content, options) {
108
+ return call(content, options?.maxTokens ?? 1024);
109
+ },
110
+ async analyzeDiff(options) {
111
+ return call(buildDiffContent(options), options.maxTokens ?? 1024);
112
+ }
113
+ };
114
+ }
115
+ function createOpenRouterLLMClient(apiKey, model) {
116
+ const modelId = model ?? "qwen/qwen3-vl-8b-instruct";
117
+ async function call(content, maxTokens) {
118
+ const start = Date.now();
119
+ const messageContent = typeof content === "string" ? content : content.map((c) => {
120
+ if (c.type === "text") return {
121
+ type: "text",
122
+ text: c.text
123
+ };
124
+ return {
125
+ type: "image_url",
126
+ image_url: { url: `data:${c.mimeType ?? "image/png"};base64,${c.base64}` }
127
+ };
128
+ });
129
+ const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
130
+ method: "POST",
131
+ headers: {
132
+ "Content-Type": "application/json",
133
+ "Authorization": `Bearer ${apiKey}`,
134
+ "HTTP-Referer": "https://github.com/mizchi/vrt"
135
+ },
136
+ body: JSON.stringify({
137
+ model: modelId,
138
+ max_tokens: maxTokens,
139
+ messages: [{
140
+ role: "user",
141
+ content: messageContent
142
+ }]
143
+ })
144
+ });
145
+ if (!res.ok) throw new Error(`OpenRouter API error: ${res.status} ${(await res.text()).slice(0, 200)}`);
146
+ const data = await res.json();
147
+ const latencyMs = Date.now() - start;
148
+ return {
149
+ content: data.choices[0]?.message?.content ?? "",
150
+ model: modelId,
151
+ provider: "openrouter",
152
+ promptTokens: data.usage?.prompt_tokens ?? 0,
153
+ completionTokens: data.usage?.completion_tokens ?? 0,
154
+ costUsd: 0,
155
+ latencyMs
156
+ };
157
+ }
158
+ return {
159
+ provider: "openrouter",
160
+ model: modelId,
161
+ async complete(prompt) {
162
+ return (await call(prompt, 1024)).content;
163
+ },
164
+ async completeWithImages(content, options) {
165
+ return call(content, options?.maxTokens ?? 1024);
166
+ },
167
+ async analyzeDiff(options) {
168
+ return call(buildDiffContent(options), options.maxTokens ?? 1024);
169
+ }
170
+ };
171
+ }
172
+ function buildDiffContent(options) {
173
+ const parts = [];
174
+ if (options.baselineBase64) {
175
+ parts.push({
176
+ type: "text",
177
+ text: "Baseline screenshot:"
178
+ });
179
+ parts.push({
180
+ type: "image",
181
+ base64: options.baselineBase64
182
+ });
183
+ }
184
+ if (options.currentBase64) {
185
+ parts.push({
186
+ type: "text",
187
+ text: "Current screenshot:"
188
+ });
189
+ parts.push({
190
+ type: "image",
191
+ base64: options.currentBase64
192
+ });
193
+ }
194
+ if (options.heatmapBase64) {
195
+ parts.push({
196
+ type: "text",
197
+ text: "Diff heatmap (red = changed pixels):"
198
+ });
199
+ parts.push({
200
+ type: "image",
201
+ base64: options.heatmapBase64
202
+ });
203
+ }
204
+ parts.push({
205
+ type: "text",
206
+ text: options.textReport
207
+ });
208
+ if (options.prompt) parts.push({
209
+ type: "text",
210
+ text: options.prompt
211
+ });
212
+ return parts;
213
+ }
214
+ const VALID_PROVIDERS = new Set([
215
+ "gemini",
216
+ "anthropic",
217
+ "openrouter"
218
+ ]);
219
+ /**
220
+ * Resolve provider and key from environment variables.
221
+ *
222
+ * VRT_LLM_PROVIDER: gemini (default) | anthropic | openrouter
223
+ * VRT_LLM_MODEL: model ID (defaults to provider's default)
224
+ *
225
+ * Returns a config, or describes why no config was available. The
226
+ * factory decides whether to throw based on `throwIfMissing`.
227
+ */
228
+ function resolveProviderConfig(options) {
229
+ const rawProvider = options?.provider ?? readEnv("LLM_PROVIDER") ?? "gemini";
230
+ if (!VALID_PROVIDERS.has(rawProvider)) return {
231
+ ok: false,
232
+ code: "INVALID_PROVIDER",
233
+ message: `Unknown VRT_LLM_PROVIDER "${rawProvider}". Expected: gemini | anthropic | openrouter.`
234
+ };
235
+ const provider = rawProvider;
236
+ const model = options?.model ?? readEnv("LLM_MODEL") ?? void 0;
237
+ const keyMap = {
238
+ gemini: process.env.GEMINI_API_KEY ?? process.env.GOOGLE_AI_API_KEY,
239
+ anthropic: process.env.ANTHROPIC_API_KEY,
240
+ openrouter: process.env.OPENROUTER_API_KEY
241
+ };
242
+ const envVarName = {
243
+ gemini: "GEMINI_API_KEY (or GOOGLE_AI_API_KEY)",
244
+ anthropic: "ANTHROPIC_API_KEY",
245
+ openrouter: "OPENROUTER_API_KEY"
246
+ };
247
+ const key = keyMap[provider];
248
+ if (!key) return {
249
+ ok: false,
250
+ code: "MISSING_KEY",
251
+ message: `${envVarName[provider]} is required for provider "${provider}".`
252
+ };
253
+ return {
254
+ ok: true,
255
+ provider,
256
+ key,
257
+ model
258
+ };
259
+ }
260
+ /**
261
+ * Create a unified LLM client.
262
+ *
263
+ * Provider is set via `VRT_LLM_PROVIDER` env var (default: `gemini`).
264
+ *
265
+ * Throws `VrtConfigError` when the resolved provider has no API key
266
+ * (`code: "MISSING_KEY"`) or the provider value is unknown
267
+ * (`code: "INVALID_PROVIDER"`). Pass `{ throwIfMissing: false }` for
268
+ * legacy `T | null` return.
269
+ */
270
+ function createUnifiedLLMClient(options) {
271
+ const throwIfMissing = options?.throwIfMissing ?? true;
272
+ const config = resolveProviderConfig(options);
273
+ if (!config.ok) {
274
+ if (throwIfMissing) throw new VrtConfigError(config.code, config.message);
275
+ return null;
276
+ }
277
+ switch (config.provider) {
278
+ case "anthropic": return createAnthropicClient(config.key, config.model);
279
+ case "gemini": return createGeminiLLMClient(config.key, config.model);
280
+ case "openrouter": return createOpenRouterLLMClient(config.key, config.model);
281
+ }
282
+ }
283
+ /**
284
+ * Backwards-compatible: returns the existing `LLMProvider` interface.
285
+ * Uses the provider specified by `VRT_LLM_PROVIDER`. Falls back to
286
+ * other providers if the requested key is missing.
287
+ *
288
+ * Throws `VrtConfigError` (`code: "NO_PROVIDER_AVAILABLE"`) when no
289
+ * provider in the fallback chain has an API key. Pass
290
+ * `{ throwIfMissing: false }` for the legacy `T | null` return.
291
+ */
292
+ function createLLMProvider(options) {
293
+ const throwIfMissing = options?.throwIfMissing ?? true;
294
+ const client = createUnifiedLLMClient({ throwIfMissing: false });
295
+ if (client) return { complete: (prompt) => client.complete(prompt) };
296
+ for (const provider of [
297
+ "gemini",
298
+ "anthropic",
299
+ "openrouter"
300
+ ]) {
301
+ const fb = createUnifiedLLMClient({
302
+ provider,
303
+ throwIfMissing: false
304
+ });
305
+ if (fb) return { complete: (prompt) => fb.complete(prompt) };
306
+ }
307
+ if (throwIfMissing) throw new VrtConfigError("NO_PROVIDER_AVAILABLE", "No LLM provider available. Set one of: GEMINI_API_KEY, ANTHROPIC_API_KEY, OPENROUTER_API_KEY.");
308
+ return null;
309
+ }
310
+ //#endregion
311
+ 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 };