@mizchi/vlmkit-ai 0.6.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mizchi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # @mizchi/vlmkit-ai
2
+
3
+ VLM / LLM clients and reasoning pipeline used by VRT to interpret diff
4
+ images and natural-language intent.
5
+
6
+ Part of the [`vrt`](https://github.com/mizchi/vrt) monorepo.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pnpm add @mizchi/vlmkit-ai
12
+ ```
13
+
14
+ Set `OPENROUTER_API_KEY`, `GEMINI_API_KEY`, or `ANTHROPIC_API_KEY` depending on
15
+ the provider you target.
16
+
17
+ ## Usage
18
+
19
+ ```ts
20
+ import { buildIntent, runReasoning, askVlm } from "@mizchi/vlmkit-ai";
21
+
22
+ const intent = await buildIntent({
23
+ baseUrl: "http://localhost:3000",
24
+ description: "Migrate hero section from Tailwind to vanilla CSS",
25
+ });
26
+
27
+ const reasoning = await runReasoning({ /* diff context */ });
28
+ ```
29
+
30
+ ## What's included
31
+
32
+ | Module | Purpose |
33
+ |---|---|
34
+ | `llm-client` | Provider-agnostic chat-completion wrapper (Gemini / Anthropic). |
35
+ | `vlm-client` | OpenRouter VLM client for diff-image analysis. |
36
+ | `reasoning`, `reasoning-pipeline` | Multi-step structured reasoning over diff context. |
37
+ | `intent` | Natural-language intent extraction. |
38
+ | `nlp` | Stopword / synonym / heuristic helpers. |
39
+
40
+ ## Environment variables
41
+
42
+ | Variable | Purpose |
43
+ |---|---|
44
+ | `VRT_LLM_PROVIDER` | `gemini` (default) \| `anthropic` |
45
+ | `VRT_LLM_MODEL` | Override provider default model |
46
+ | `VRT_VLM_MODEL` | OpenRouter VLM model id |
47
+ | `OPENROUTER_API_KEY` | VLM access |
48
+ | `GEMINI_API_KEY` | Gemini LLM access |
49
+ | `ANTHROPIC_API_KEY` | Anthropic LLM access |
50
+
51
+ ## License
52
+
53
+ MIT
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@mizchi/vlmkit-ai",
3
+ "version": "0.6.0",
4
+ "description": "VLM / LLM clients, reasoning pipeline, and NLP helpers used by VRT to interpret diff images and natural-language intent.",
5
+ "license": "MIT",
6
+ "author": "mizchi",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/mizchi/vlmkit.git",
10
+ "directory": "packages/vlmkit-ai"
11
+ },
12
+ "homepage": "https://github.com/mizchi/vlmkit/tree/main/packages/vlmkit-ai#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/mizchi/vlmkit/issues"
15
+ },
16
+ "type": "module",
17
+ "files": [
18
+ "src/**/*.ts",
19
+ "!src/**/*.test.ts",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "exports": {
24
+ ".": "./src/index.ts",
25
+ "./*.ts": "./src/*.ts"
26
+ },
27
+ "dependencies": {
28
+ "@google/generative-ai": "^0.24.1",
29
+ "@mizchi/vlmkit-core": "0.6.0"
30
+ },
31
+ "scripts": {
32
+ "test": "node --test 'src/**/*.test.ts'"
33
+ }
34
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Tagged error class for factory functions in @mizchi/vlmkit-ai.
3
+ *
4
+ * Factories (`createVlmClient`, `createUnifiedLLMClient`,
5
+ * `createLLMProvider`, `createReasoningPipeline`) historically returned
6
+ * `null` when configuration was missing or invalid. The caller had no way
7
+ * to discriminate between "no API key", "invalid model id", "ambiguous
8
+ * model substring", or "provider value unknown" — every failure mode
9
+ * collapsed into one nullable.
10
+ *
11
+ * From 0.5.0 the factories throw `VrtConfigError` by default. Callers
12
+ * that want the legacy null behaviour pass `{ throwIfMissing: false }`.
13
+ *
14
+ * Codes are stable; new ones can only be added (never renumbered or
15
+ * removed) in minor versions.
16
+ */
17
+ export type VrtConfigErrorCode =
18
+ /** Required env var (`OPENROUTER_API_KEY`, `GEMINI_API_KEY`, `ANTHROPIC_API_KEY`) not set. */
19
+ | "MISSING_KEY"
20
+ /** Provider/model id doesn't resolve. */
21
+ | "INVALID_MODEL"
22
+ /** Model substring matches more than one candidate. */
23
+ | "MULTIPLE_MATCHES"
24
+ /** `VRT_LLM_PROVIDER` value is not one of the known providers. */
25
+ | "INVALID_PROVIDER"
26
+ /** No provider in the fallback chain has an API key configured. */
27
+ | "NO_PROVIDER_AVAILABLE"
28
+ /** An optional runtime dependency (e.g. `@google/generative-ai`) failed to import. */
29
+ | "MISSING_DEPENDENCY";
30
+
31
+ export class VrtConfigError extends Error {
32
+ readonly code: VrtConfigErrorCode;
33
+
34
+ constructor(code: VrtConfigErrorCode, message: string) {
35
+ super(message);
36
+ this.name = "VrtConfigError";
37
+ this.code = code;
38
+ }
39
+ }
package/src/index.ts ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * @mizchi/vlmkit-ai — VLM / LLM clients, reasoning pipeline, NLP helpers
3
+ *
4
+ * Curated public API. The `nlp` module (STOP_WORDS / SYNONYMS dictionaries)
5
+ * remains deep-importable but is not in the barrel — those are tuning
6
+ * tables, not user-facing primitives.
7
+ */
8
+
9
+ // ---- Errors ----
10
+ export { VrtConfigError, type VrtConfigErrorCode } from "./errors.ts";
11
+
12
+ // ---- LLM clients ----
13
+ export {
14
+ createUnifiedLLMClient,
15
+ createLLMProvider,
16
+ type CreateLLMProviderOptions,
17
+ type LLMClientOptions,
18
+ type LLMResponse,
19
+ type LLMProviderName,
20
+ type UnifiedLLMClient,
21
+ type MessageContent,
22
+ type TextContent,
23
+ type ImageContent,
24
+ } from "./llm-client.ts";
25
+
26
+ // ---- VLM clients ----
27
+ export {
28
+ fetchVisionModels,
29
+ listModels,
30
+ resolveModel,
31
+ listGeminiModels,
32
+ resolveGeminiModel,
33
+ isGeminiDirectModel,
34
+ createVlmClient,
35
+ type CreateVlmClientOptions,
36
+ type VlmClient,
37
+ type VlmModel,
38
+ type VlmResponse,
39
+ } from "./vlm-client.ts";
40
+
41
+ // ---- Reasoning ----
42
+ export {
43
+ createReasoningPipeline,
44
+ type ReasoningPipeline,
45
+ type PipelineConfig,
46
+ type AnalyzeOptions,
47
+ type StructuredDiffReport,
48
+ type VisualChange,
49
+ type CssFix,
50
+ type FixSuggestion,
51
+ } from "./reasoning-pipeline.ts";
52
+ export {
53
+ reasonAboutChanges,
54
+ type ReasoningChain,
55
+ type ActualChange,
56
+ type ExpectationMapping,
57
+ } from "./reasoning.ts";
58
+
59
+ // ---- Intent / diff extraction ----
60
+ export {
61
+ buildIntent,
62
+ buildIntentWithLLM,
63
+ buildReasoningPrompt,
64
+ extractDiffSemantics,
65
+ parseDiff,
66
+ type LLMProvider,
67
+ } from "./intent.ts";
package/src/intent.ts ADDED
@@ -0,0 +1,322 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import type {
4
+ ChangeIntent,
5
+ DiffSemantics,
6
+ FileChange,
7
+ DiffHunk,
8
+ VisualExpectation,
9
+ VrtDiff,
10
+ } from "@mizchi/vlmkit-core/types.ts";
11
+
12
+ const execFileAsync = promisify(execFile);
13
+
14
+ /**
15
+ * Parse git diff and return structured change information.
16
+ */
17
+ export async function extractDiffSemantics(
18
+ repoDir: string,
19
+ base: string = "HEAD~1",
20
+ head: string = "HEAD"
21
+ ): Promise<DiffSemantics> {
22
+ const [diffResult, logResult] = await Promise.all([
23
+ execFileAsync("git", ["diff", "--unified=3", `${base}...${head}`], {
24
+ cwd: repoDir,
25
+ maxBuffer: 10 * 1024 * 1024,
26
+ }),
27
+ execFileAsync("git", ["log", "--format=%s%n%b", "-1", head], {
28
+ cwd: repoDir,
29
+ }),
30
+ ]);
31
+
32
+ const filesChanged = parseDiff(diffResult.stdout);
33
+ const commitMessage = logResult.stdout.trim();
34
+ const intent = buildIntent(filesChanged, commitMessage);
35
+
36
+ return { filesChanged, commitMessage, intent };
37
+ }
38
+
39
+ /**
40
+ * Parse unified diff into FileChange[].
41
+ */
42
+ export function parseDiff(diffText: string): FileChange[] {
43
+ const files: FileChange[] = [];
44
+ const fileSections = diffText.split(/^diff --git /m).slice(1);
45
+
46
+ for (const section of fileSections) {
47
+ const headerMatch = section.match(/^a\/(.+?) b\/(.+)/);
48
+ if (!headerMatch) continue;
49
+
50
+ const path = headerMatch[2];
51
+ let additions = 0;
52
+ let deletions = 0;
53
+ const hunks: DiffHunk[] = [];
54
+
55
+ const lines = section.split("\n");
56
+
57
+ let currentHunk: DiffHunk | null = null;
58
+ let lineNum = 0;
59
+
60
+ for (const line of lines) {
61
+ const hunkMatch = line.match(
62
+ /^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@(.*)$/
63
+ );
64
+ if (hunkMatch) {
65
+ if (currentHunk) hunks.push(currentHunk);
66
+ lineNum = parseInt(hunkMatch[2], 10);
67
+ currentHunk = {
68
+ header: line,
69
+ content: "",
70
+ startLine: lineNum,
71
+ endLine: lineNum,
72
+ };
73
+ continue;
74
+ }
75
+
76
+ if (currentHunk) {
77
+ currentHunk.content += line + "\n";
78
+ if (line.startsWith("+") && !line.startsWith("+++")) {
79
+ additions++;
80
+ lineNum++;
81
+ } else if (line.startsWith("-") && !line.startsWith("---")) {
82
+ deletions++;
83
+ } else if (!line.startsWith("\\")) {
84
+ lineNum++;
85
+ }
86
+ currentHunk.endLine = lineNum;
87
+ }
88
+ }
89
+ if (currentHunk) hunks.push(currentHunk);
90
+
91
+ files.push({ path, additions, deletions, hunks });
92
+ }
93
+
94
+ return files;
95
+ }
96
+
97
+ /**
98
+ * Infer change intent from files and commit message.
99
+ * Lightweight version without LLM. See buildIntentWithLLM for LLM version.
100
+ */
101
+ export function buildIntent(
102
+ files: FileChange[],
103
+ commitMessage: string
104
+ ): ChangeIntent {
105
+ const changeType = inferChangeType(commitMessage);
106
+ const affectedComponents = files
107
+ .filter((f) => isComponentFile(f.path))
108
+ .map((f) => f.path);
109
+
110
+ const expectedVisualChanges = inferVisualExpectations(
111
+ files,
112
+ commitMessage,
113
+ changeType
114
+ );
115
+
116
+ return {
117
+ summary: commitMessage.split("\n")[0],
118
+ expectedVisualChanges,
119
+ expectedA11yChanges: [],
120
+ affectedComponents,
121
+ changeType,
122
+ };
123
+ }
124
+
125
+ function inferChangeType(
126
+ message: string
127
+ ): ChangeIntent["changeType"] {
128
+ const lower = message.toLowerCase();
129
+ if (/^fix[:(]|bug\s*fix|hotfix|patch/.test(lower)) return "bugfix";
130
+ if (/^feat[:(]|feature|add\s/.test(lower)) return "feature";
131
+ if (/^refactor[:(]|cleanup|restructure/.test(lower)) return "refactor";
132
+ if (/^style[:(]|css|theme|color|font|layout/.test(lower)) return "style";
133
+ if (/^a11y[:(]|accessibility|aria|wcag|screen.?reader|label/.test(lower)) return "a11y";
134
+ if (/^deps?[:(]|upgrade|bump|update.*dep/.test(lower)) return "deps";
135
+ return "unknown";
136
+ }
137
+
138
+ function isComponentFile(path: string): boolean {
139
+ return /\.(tsx|jsx|vue|svelte|mbt)$/.test(path);
140
+ }
141
+
142
+ /**
143
+ * Infer expected visual changes from file changes (heuristic version).
144
+ */
145
+ function inferVisualExpectations(
146
+ files: FileChange[],
147
+ _commitMessage: string,
148
+ changeType: ChangeIntent["changeType"]
149
+ ): VisualExpectation[] {
150
+ const expectations: VisualExpectation[] = [];
151
+
152
+ // refactor/deps: no visual change expected
153
+ if (changeType === "refactor" || changeType === "deps") {
154
+ for (const file of files) {
155
+ if (isComponentFile(file.path)) {
156
+ expectations.push({
157
+ component: file.path,
158
+ description: "No visual change expected (refactor/deps)",
159
+ confidence: 0.7,
160
+ });
161
+ }
162
+ }
163
+ return expectations;
164
+ }
165
+
166
+ for (const file of files) {
167
+ if (!isComponentFile(file.path)) continue;
168
+
169
+ // Detect CSS/style changes
170
+ const styleChanges = file.hunks.some(
171
+ (h) =>
172
+ /(?:style|css|className|color|font|margin|padding|border|background)/i.test(
173
+ h.content
174
+ )
175
+ );
176
+
177
+ if (styleChanges) {
178
+ expectations.push({
179
+ component: file.path,
180
+ description: `Visual style changes in ${file.path}`,
181
+ confidence: 0.8,
182
+ });
183
+ }
184
+
185
+ // Detect layout changes
186
+ const layoutChanges = file.hunks.some(
187
+ (h) =>
188
+ /(?:flex|grid|display|position|width|height|overflow)/i.test(h.content)
189
+ );
190
+
191
+ if (layoutChanges) {
192
+ expectations.push({
193
+ component: file.path,
194
+ description: `Layout changes in ${file.path}`,
195
+ confidence: 0.8,
196
+ });
197
+ }
198
+
199
+ // Detect text/content changes
200
+ const contentChanges = file.hunks.some(
201
+ (h) =>
202
+ /(?:text|label|title|heading|<h[1-6]|<p|<span|innerText)/i.test(
203
+ h.content
204
+ )
205
+ );
206
+
207
+ if (contentChanges) {
208
+ expectations.push({
209
+ component: file.path,
210
+ description: `Content/text changes in ${file.path}`,
211
+ confidence: 0.6,
212
+ });
213
+ }
214
+ }
215
+
216
+ return expectations;
217
+ }
218
+
219
+ // ---- LLM-assisted intent extraction ----
220
+
221
+ export interface LLMProvider {
222
+ complete(prompt: string): Promise<string>;
223
+ }
224
+
225
+ /**
226
+ * Build Intent from diff and commit message using LLM.
227
+ */
228
+ export async function buildIntentWithLLM(
229
+ files: FileChange[],
230
+ commitMessage: string,
231
+ llm: LLMProvider
232
+ ): Promise<ChangeIntent> {
233
+ const diffSummary = files
234
+ .map((f) => `${f.path} (+${f.additions}/-${f.deletions})`)
235
+ .join("\n");
236
+
237
+ const hunkSamples = files
238
+ .flatMap((f) =>
239
+ f.hunks.slice(0, 3).map((h) => `--- ${f.path}\n${h.content.slice(0, 500)}`)
240
+ )
241
+ .join("\n\n");
242
+
243
+ const prompt = `Analyze this code change and predict its visual impact.
244
+
245
+ Commit message: ${commitMessage}
246
+
247
+ Files changed:
248
+ ${diffSummary}
249
+
250
+ Key diff hunks:
251
+ ${hunkSamples}
252
+
253
+ Respond in JSON:
254
+ {
255
+ "summary": "one-line summary of the change",
256
+ "changeType": "feature|bugfix|refactor|style|deps|unknown",
257
+ "expectedVisualChanges": [
258
+ { "component": "file path", "description": "what visual change is expected", "confidence": 0.0-1.0 }
259
+ ],
260
+ "affectedComponents": ["list of component file paths"]
261
+ }`;
262
+
263
+ const response = await llm.complete(prompt);
264
+ try {
265
+ const parsed = JSON.parse(response);
266
+ return {
267
+ summary: parsed.summary ?? commitMessage,
268
+ changeType: parsed.changeType ?? "unknown",
269
+ expectedVisualChanges: parsed.expectedVisualChanges ?? [],
270
+ expectedA11yChanges: parsed.expectedA11yChanges ?? [],
271
+ affectedComponents: parsed.affectedComponents ?? [],
272
+ };
273
+ } catch {
274
+ // fallback to heuristic
275
+ return buildIntent(files, commitMessage);
276
+ }
277
+ }
278
+
279
+ // ---- Verdict Construction ----
280
+
281
+ /**
282
+ * Build a reasoning prompt that validates VRT diff against Intent.
283
+ */
284
+ export function buildReasoningPrompt(
285
+ diff: VrtDiff,
286
+ intent: ChangeIntent
287
+ ): string {
288
+ const matchingExpectations = intent.expectedVisualChanges.filter(
289
+ (e) =>
290
+ diff.snapshot.testTitle.includes(e.component) ||
291
+ e.component.includes(diff.snapshot.testTitle)
292
+ );
293
+
294
+ return `You are a visual regression test reviewer.
295
+
296
+ ## Change Intent
297
+ Summary: ${intent.summary}
298
+ Type: ${intent.changeType}
299
+ Expected visual changes:
300
+ ${intent.expectedVisualChanges.map((e) => `- ${e.component}: ${e.description} (confidence: ${e.confidence})`).join("\n")}
301
+
302
+ ## Visual Diff Detected
303
+ Test: ${diff.snapshot.testTitle}
304
+ Project: ${diff.snapshot.projectName}
305
+ Diff ratio: ${(diff.diffRatio * 100).toFixed(2)}%
306
+ Diff pixels: ${diff.diffPixels} / ${diff.totalPixels}
307
+ Diff regions: ${diff.regions.length} region(s)
308
+ ${diff.regions.map((r) => ` - (${r.x},${r.y}) ${r.width}x${r.height}: ${r.diffPixelCount}px`).join("\n")}
309
+
310
+ ## Matching Expectations
311
+ ${matchingExpectations.length > 0 ? matchingExpectations.map((e) => `- ${e.description}`).join("\n") : "None found"}
312
+
313
+ ## Task
314
+ Decide: should this visual diff be APPROVED (matches intent), REJECTED (unexpected regression), or ESCALATED (uncertain, needs human review)?
315
+
316
+ Respond in JSON:
317
+ {
318
+ "decision": "approve|reject|escalate",
319
+ "reasoning": "explanation",
320
+ "confidence": 0.0-1.0
321
+ }`;
322
+ }