@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,24 @@
1
+ //#region src/errors.d.ts
2
+ /**
3
+ * Tagged error class for factory functions in @mizchi/vlmkit-ai.
4
+ *
5
+ * Factories (`createVlmClient`, `createUnifiedLLMClient`,
6
+ * `createLLMProvider`, `createReasoningPipeline`) historically returned
7
+ * `null` when configuration was missing or invalid. The caller had no way
8
+ * to discriminate between "no API key", "invalid model id", "ambiguous
9
+ * model substring", or "provider value unknown" — every failure mode
10
+ * collapsed into one nullable.
11
+ *
12
+ * From 0.5.0 the factories throw `VrtConfigError` by default. Callers
13
+ * that want the legacy null behaviour pass `{ throwIfMissing: false }`.
14
+ *
15
+ * Codes are stable; new ones can only be added (never renumbered or
16
+ * removed) in minor versions.
17
+ */
18
+ type VrtConfigErrorCode = /** Required env var (`OPENROUTER_API_KEY`, `GEMINI_API_KEY`, `ANTHROPIC_API_KEY`) not set. */"MISSING_KEY" /** Provider/model id doesn't resolve. */ | "INVALID_MODEL" /** Model substring matches more than one candidate. */ | "MULTIPLE_MATCHES" /** `VRT_LLM_PROVIDER` value is not one of the known providers. */ | "INVALID_PROVIDER" /** No provider in the fallback chain has an API key configured. */ | "NO_PROVIDER_AVAILABLE" /** An optional runtime dependency (e.g. `@google/generative-ai`) failed to import. */ | "MISSING_DEPENDENCY" /** Caller-supplied request parameters are malformed (empty prompt, out-of-range size, etc.). */ | "INVALID_REQUEST";
19
+ declare class VrtConfigError extends Error {
20
+ readonly code: VrtConfigErrorCode;
21
+ constructor(code: VrtConfigErrorCode, message: string);
22
+ }
23
+ //#endregion
24
+ export { VrtConfigError, VrtConfigErrorCode };
@@ -0,0 +1,11 @@
1
+ //#region src/errors.ts
2
+ var VrtConfigError = class extends Error {
3
+ code;
4
+ constructor(code, message) {
5
+ super(message);
6
+ this.name = "VrtConfigError";
7
+ this.code = code;
8
+ }
9
+ };
10
+ //#endregion
11
+ export { VrtConfigError };
@@ -0,0 +1,79 @@
1
+ //#region src/image-gen-client.d.ts
2
+ type ImageGenSize = "1024x1024" | "1024x1536" | "1536x1024" | "auto";
3
+ type ImageGenQuality = "low" | "medium" | "high" | "auto";
4
+ type ImageGenOutputFormat = "png" | "jpeg" | "webp";
5
+ type ImageGenBackground = "opaque" | "transparent" | "auto";
6
+ interface ImageGenModel {
7
+ id: string;
8
+ provider: "openai";
9
+ /** USD per 1M tokens (matches OpenAI's published pricing table). */
10
+ costPer1MInputTextTokens: number;
11
+ costPer1MInputImageTokens: number;
12
+ costPer1MOutputImageTokens: number;
13
+ }
14
+ interface ImageGenRequest {
15
+ prompt: string;
16
+ size?: ImageGenSize;
17
+ quality?: ImageGenQuality;
18
+ n?: number;
19
+ outputFormat?: ImageGenOutputFormat;
20
+ background?: ImageGenBackground;
21
+ }
22
+ interface ImageGenUsage {
23
+ inputTextTokens: number;
24
+ inputImageTokens: number;
25
+ outputTokens: number;
26
+ }
27
+ interface ImageGenResponse {
28
+ model: string;
29
+ images: Uint8Array[];
30
+ usage: ImageGenUsage | null;
31
+ costUsd: number;
32
+ latencyMs: number;
33
+ }
34
+ interface ImageGenRequestBody {
35
+ model: string;
36
+ prompt: string;
37
+ size: ImageGenSize;
38
+ quality: ImageGenQuality;
39
+ n: number;
40
+ output_format: ImageGenOutputFormat;
41
+ background: ImageGenBackground;
42
+ }
43
+ interface ImageGenClient {
44
+ model: ImageGenModel;
45
+ generate(req: ImageGenRequest): Promise<ImageGenResponse>;
46
+ }
47
+ declare function listImageGenModels(): ImageGenModel[];
48
+ declare function resolveImageGenModel(id: string): ImageGenModel;
49
+ declare function buildGenerationBody(model: ImageGenModel, req: ImageGenRequest): ImageGenRequestBody;
50
+ interface RawGenerationResponse {
51
+ data?: Array<{
52
+ b64_json?: string;
53
+ url?: string;
54
+ }>;
55
+ usage?: {
56
+ input_tokens?: number;
57
+ output_tokens?: number;
58
+ total_tokens?: number;
59
+ input_tokens_details?: {
60
+ text_tokens?: number;
61
+ image_tokens?: number;
62
+ };
63
+ };
64
+ }
65
+ interface ParsedGeneration {
66
+ images: Uint8Array[];
67
+ usage: ImageGenUsage | null;
68
+ }
69
+ declare function parseGenerationResponse(json: RawGenerationResponse): ParsedGeneration;
70
+ declare function estimateImageGenCost(model: ImageGenModel, usage: ImageGenUsage | null): number;
71
+ interface CreateImageGenClientOptions {
72
+ apiKey?: string;
73
+ throwIfMissing?: boolean;
74
+ /** Override the API base URL (for tests / proxies). */
75
+ baseUrl?: string;
76
+ }
77
+ declare function createImageGenClient(modelOrId: ImageGenModel | string, options?: CreateImageGenClientOptions): ImageGenClient;
78
+ //#endregion
79
+ export { CreateImageGenClientOptions, ImageGenBackground, ImageGenClient, ImageGenModel, ImageGenOutputFormat, ImageGenQuality, ImageGenRequest, ImageGenRequestBody, ImageGenResponse, ImageGenSize, ImageGenUsage, ParsedGeneration, buildGenerationBody, createImageGenClient, estimateImageGenCost, listImageGenModels, parseGenerationResponse, resolveImageGenModel };
@@ -0,0 +1,149 @@
1
+ import { VrtConfigError } from "./errors.mjs";
2
+ //#region src/image-gen-client.ts
3
+ /**
4
+ * Image generation client (OpenAI gpt-image-2).
5
+ *
6
+ * Mirrors the vlm-client / llm-client split: a small registry of known
7
+ * models, pure builders + parsers that can be unit-tested without a network
8
+ * call, and a `createImageGenClient` factory that wires them to the actual
9
+ * OpenAI Images API.
10
+ *
11
+ * Used by:
12
+ * - `design-runs/game-assets-20260520/run-gpt-image-2.mjs` (dogfood driver)
13
+ * - vlmkit-markup pipelines that need to synthesize reference imagery
14
+ * - downstream callers in `src/cli/workflow/` (added separately)
15
+ *
16
+ * The OpenAI Images endpoint returns base64-encoded PNGs by default; we
17
+ * surface them as `Uint8Array`. Reference-image inputs (edit mode via
18
+ * `/v1/images/edits`) are intentionally out of scope here; add a separate
19
+ * `editImage` method if/when a caller needs it.
20
+ */
21
+ const IMAGE_GEN_MODELS = [{
22
+ id: "gpt-image-2",
23
+ provider: "openai",
24
+ costPer1MInputTextTokens: 5,
25
+ costPer1MInputImageTokens: 8,
26
+ costPer1MOutputImageTokens: 30
27
+ }, {
28
+ id: "gpt-image-2-2026-04-21",
29
+ provider: "openai",
30
+ costPer1MInputTextTokens: 5,
31
+ costPer1MInputImageTokens: 8,
32
+ costPer1MOutputImageTokens: 30
33
+ }];
34
+ const VALID_SIZES = new Set([
35
+ "1024x1024",
36
+ "1024x1536",
37
+ "1536x1024",
38
+ "auto"
39
+ ]);
40
+ const VALID_QUALITIES = new Set([
41
+ "low",
42
+ "medium",
43
+ "high",
44
+ "auto"
45
+ ]);
46
+ const VALID_OUTPUT_FORMATS = new Set([
47
+ "png",
48
+ "jpeg",
49
+ "webp"
50
+ ]);
51
+ const VALID_BACKGROUNDS = new Set([
52
+ "opaque",
53
+ "transparent",
54
+ "auto"
55
+ ]);
56
+ function listImageGenModels() {
57
+ return IMAGE_GEN_MODELS.map((m) => ({ ...m }));
58
+ }
59
+ function resolveImageGenModel(id) {
60
+ const hit = IMAGE_GEN_MODELS.find((m) => m.id === id);
61
+ if (!hit) throw new VrtConfigError("INVALID_MODEL", `Unknown image generation model: "${id}". Known: ${IMAGE_GEN_MODELS.map((m) => m.id).join(", ")}`);
62
+ return { ...hit };
63
+ }
64
+ function buildGenerationBody(model, req) {
65
+ if (!req.prompt || !req.prompt.trim()) throw new VrtConfigError("INVALID_REQUEST", "image-gen: prompt must be a non-empty string");
66
+ const size = req.size ?? "1024x1024";
67
+ const quality = req.quality ?? "medium";
68
+ const outputFormat = req.outputFormat ?? "png";
69
+ const background = req.background ?? "opaque";
70
+ const n = req.n ?? 1;
71
+ if (!VALID_SIZES.has(size)) throw new VrtConfigError("INVALID_REQUEST", `image-gen: invalid size "${size}"`);
72
+ if (!VALID_QUALITIES.has(quality)) throw new VrtConfigError("INVALID_REQUEST", `image-gen: invalid quality "${quality}"`);
73
+ if (!VALID_OUTPUT_FORMATS.has(outputFormat)) throw new VrtConfigError("INVALID_REQUEST", `image-gen: invalid output_format "${outputFormat}"`);
74
+ if (!VALID_BACKGROUNDS.has(background)) throw new VrtConfigError("INVALID_REQUEST", `image-gen: invalid background "${background}"`);
75
+ if (!Number.isInteger(n) || n <= 0) throw new VrtConfigError("INVALID_REQUEST", `image-gen: n must be a positive integer, got ${n}`);
76
+ return {
77
+ model: model.id,
78
+ prompt: req.prompt,
79
+ size,
80
+ quality,
81
+ n,
82
+ output_format: outputFormat,
83
+ background
84
+ };
85
+ }
86
+ function parseGenerationResponse(json) {
87
+ const images = [];
88
+ for (const entry of json.data ?? []) {
89
+ if (!entry || typeof entry.b64_json !== "string") continue;
90
+ images.push(new Uint8Array(Buffer.from(entry.b64_json, "base64")));
91
+ }
92
+ const u = json.usage;
93
+ return {
94
+ images,
95
+ usage: u ? {
96
+ inputTextTokens: u.input_tokens_details?.text_tokens ?? u.input_tokens ?? 0,
97
+ inputImageTokens: u.input_tokens_details?.image_tokens ?? 0,
98
+ outputTokens: u.output_tokens ?? 0
99
+ } : null
100
+ };
101
+ }
102
+ function estimateImageGenCost(model, usage) {
103
+ if (!usage) return 0;
104
+ const cost = (usage.inputTextTokens * model.costPer1MInputTextTokens + usage.inputImageTokens * model.costPer1MInputImageTokens + usage.outputTokens * model.costPer1MOutputImageTokens) / 1e6;
105
+ return Math.round(cost * 1e6) / 1e6;
106
+ }
107
+ function createImageGenClient(modelOrId, options) {
108
+ const model = typeof modelOrId === "string" ? resolveImageGenModel(modelOrId) : modelOrId;
109
+ const throwIfMissing = options?.throwIfMissing ?? true;
110
+ const apiKey = options?.apiKey ?? process.env.OPENAI_API_KEY;
111
+ if (!apiKey && throwIfMissing) throw new VrtConfigError("MISSING_KEY", `OPENAI_API_KEY is required for ${model.id}`);
112
+ const baseUrl = options?.baseUrl ?? "https://api.openai.com";
113
+ return {
114
+ model,
115
+ async generate(req) {
116
+ const body = buildGenerationBody(model, req);
117
+ const started = Date.now();
118
+ const res = await fetch(`${baseUrl}/v1/images/generations`, {
119
+ method: "POST",
120
+ headers: {
121
+ Authorization: `Bearer ${apiKey ?? ""}`,
122
+ "Content-Type": "application/json"
123
+ },
124
+ body: JSON.stringify(body)
125
+ });
126
+ const text = await res.text();
127
+ let json;
128
+ try {
129
+ json = JSON.parse(text);
130
+ } catch {
131
+ throw new Error(`image-gen: non-JSON response from OpenAI (status ${res.status}): ${text.slice(0, 200)}`);
132
+ }
133
+ if (!res.ok) {
134
+ const message = json.error?.message ?? text.slice(0, 200);
135
+ throw new Error(`image-gen ${model.id} failed (${res.status}): ${message}`);
136
+ }
137
+ const parsed = parseGenerationResponse(json);
138
+ return {
139
+ model: model.id,
140
+ images: parsed.images,
141
+ usage: parsed.usage,
142
+ costUsd: estimateImageGenCost(model, parsed.usage),
143
+ latencyMs: Date.now() - started
144
+ };
145
+ }
146
+ };
147
+ }
148
+ //#endregion
149
+ export { buildGenerationBody, createImageGenClient, estimateImageGenCost, listImageGenModels, parseGenerationResponse, resolveImageGenModel };
@@ -0,0 +1,8 @@
1
+ import { VrtConfigError, VrtConfigErrorCode } from "./errors.mjs";
2
+ import { CreateImageGenClientOptions, ImageGenBackground, ImageGenClient, ImageGenModel, ImageGenOutputFormat, ImageGenQuality, ImageGenRequest, ImageGenRequestBody, ImageGenResponse, ImageGenSize, ImageGenUsage, ParsedGeneration, buildGenerationBody, createImageGenClient, estimateImageGenCost, listImageGenModels, parseGenerationResponse, resolveImageGenModel } from "./image-gen-client.mjs";
3
+ import { LLMProvider, buildIntent, buildIntentWithLLM, buildReasoningPrompt, extractDiffSemantics, parseDiff } from "./intent.mjs";
4
+ import { CreateLLMProviderOptions, ImageContent, LLMClientOptions, LLMProviderName, LLMResponse, MessageContent, TextContent, UnifiedLLMClient, createLLMProvider, createUnifiedLLMClient } from "./llm-client.mjs";
5
+ import { CreateVlmClientOptions, VlmClient, VlmModel, VlmResponse, createVlmClient, fetchVisionModels, isGeminiDirectModel, listGeminiModels, listModels, resolveGeminiModel, resolveModel } from "./vlm-client.mjs";
6
+ import { AnalyzeOptions, CssFix, FixSuggestion, PipelineConfig, ReasoningPipeline, StructuredDiffReport, VisualChange, createReasoningPipeline } from "./reasoning-pipeline.mjs";
7
+ import { ActualChange, ExpectationMapping, ReasoningChain, reasonAboutChanges } from "./reasoning.mjs";
8
+ export { type ActualChange, type AnalyzeOptions, type CreateImageGenClientOptions, type CreateLLMProviderOptions, type CreateVlmClientOptions, type CssFix, type ExpectationMapping, type FixSuggestion, type ImageContent, type ImageGenBackground, type ImageGenClient, type ImageGenModel, type ImageGenOutputFormat, type ImageGenQuality, type ImageGenRequest, type ImageGenRequestBody, type ImageGenResponse, type ImageGenSize, type ImageGenUsage, type LLMClientOptions, type LLMProvider, type LLMProviderName, type LLMResponse, type MessageContent, type ParsedGeneration, type PipelineConfig, type ReasoningChain, type ReasoningPipeline, type StructuredDiffReport, type TextContent, type UnifiedLLMClient, type VisualChange, type VlmClient, type VlmModel, type VlmResponse, VrtConfigError, type VrtConfigErrorCode, buildGenerationBody, buildIntent, buildIntentWithLLM, buildReasoningPrompt, createImageGenClient, createLLMProvider, createReasoningPipeline, createUnifiedLLMClient, createVlmClient, estimateImageGenCost, extractDiffSemantics, fetchVisionModels, isGeminiDirectModel, listGeminiModels, listImageGenModels, listModels, parseDiff, parseGenerationResponse, reasonAboutChanges, resolveGeminiModel, resolveImageGenModel, resolveModel };
package/dist/index.mjs ADDED
@@ -0,0 +1,8 @@
1
+ import { VrtConfigError } from "./errors.mjs";
2
+ import { buildGenerationBody, createImageGenClient, estimateImageGenCost, listImageGenModels, parseGenerationResponse, resolveImageGenModel } from "./image-gen-client.mjs";
3
+ import { createLLMProvider, createUnifiedLLMClient } from "./llm-client.mjs";
4
+ import { createVlmClient, fetchVisionModels, isGeminiDirectModel, listGeminiModels, listModels, resolveGeminiModel, resolveModel } from "./vlm-client.mjs";
5
+ import { createReasoningPipeline } from "./reasoning-pipeline.mjs";
6
+ import { reasonAboutChanges } from "./reasoning.mjs";
7
+ import { buildIntent, buildIntentWithLLM, buildReasoningPrompt, extractDiffSemantics, parseDiff } from "./intent.mjs";
8
+ export { VrtConfigError, buildGenerationBody, buildIntent, buildIntentWithLLM, buildReasoningPrompt, createImageGenClient, createLLMProvider, createReasoningPipeline, createUnifiedLLMClient, createVlmClient, estimateImageGenCost, extractDiffSemantics, fetchVisionModels, isGeminiDirectModel, listGeminiModels, listImageGenModels, listModels, parseDiff, parseGenerationResponse, reasonAboutChanges, resolveGeminiModel, resolveImageGenModel, resolveModel };
@@ -0,0 +1,29 @@
1
+ import { ChangeIntent, DiffSemantics, FileChange, VrtDiff } from "@mizchi/vlmkit-core/types.ts";
2
+
3
+ //#region src/intent.d.ts
4
+ /**
5
+ * Parse git diff and return structured change information.
6
+ */
7
+ declare function extractDiffSemantics(repoDir: string, base?: string, head?: string): Promise<DiffSemantics>;
8
+ /**
9
+ * Parse unified diff into FileChange[].
10
+ */
11
+ declare function parseDiff(diffText: string): FileChange[];
12
+ /**
13
+ * Infer change intent from files and commit message.
14
+ * Lightweight version without LLM. See buildIntentWithLLM for LLM version.
15
+ */
16
+ declare function buildIntent(files: FileChange[], commitMessage: string): ChangeIntent;
17
+ interface LLMProvider {
18
+ complete(prompt: string): Promise<string>;
19
+ }
20
+ /**
21
+ * Build Intent from diff and commit message using LLM.
22
+ */
23
+ declare function buildIntentWithLLM(files: FileChange[], commitMessage: string, llm: LLMProvider): Promise<ChangeIntent>;
24
+ /**
25
+ * Build a reasoning prompt that validates VRT diff against Intent.
26
+ */
27
+ declare function buildReasoningPrompt(diff: VrtDiff, intent: ChangeIntent): string;
28
+ //#endregion
29
+ export { LLMProvider, buildIntent, buildIntentWithLLM, buildReasoningPrompt, extractDiffSemantics, parseDiff };
@@ -0,0 +1,213 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ //#region src/intent.ts
4
+ const execFileAsync = promisify(execFile);
5
+ /**
6
+ * Parse git diff and return structured change information.
7
+ */
8
+ async function extractDiffSemantics(repoDir, base = "HEAD~1", head = "HEAD") {
9
+ const [diffResult, logResult] = await Promise.all([execFileAsync("git", [
10
+ "diff",
11
+ "--unified=3",
12
+ `${base}...${head}`
13
+ ], {
14
+ cwd: repoDir,
15
+ maxBuffer: 10 * 1024 * 1024
16
+ }), execFileAsync("git", [
17
+ "log",
18
+ "--format=%s%n%b",
19
+ "-1",
20
+ head
21
+ ], { cwd: repoDir })]);
22
+ const filesChanged = parseDiff(diffResult.stdout);
23
+ const commitMessage = logResult.stdout.trim();
24
+ return {
25
+ filesChanged,
26
+ commitMessage,
27
+ intent: buildIntent(filesChanged, commitMessage)
28
+ };
29
+ }
30
+ /**
31
+ * Parse unified diff into FileChange[].
32
+ */
33
+ function parseDiff(diffText) {
34
+ const files = [];
35
+ const fileSections = diffText.split(/^diff --git /m).slice(1);
36
+ for (const section of fileSections) {
37
+ const headerMatch = section.match(/^a\/(.+?) b\/(.+)/);
38
+ if (!headerMatch) continue;
39
+ const path = headerMatch[2];
40
+ let additions = 0;
41
+ let deletions = 0;
42
+ const hunks = [];
43
+ const lines = section.split("\n");
44
+ let currentHunk = null;
45
+ let lineNum = 0;
46
+ for (const line of lines) {
47
+ const hunkMatch = line.match(/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@(.*)$/);
48
+ if (hunkMatch) {
49
+ if (currentHunk) hunks.push(currentHunk);
50
+ lineNum = parseInt(hunkMatch[2], 10);
51
+ currentHunk = {
52
+ header: line,
53
+ content: "",
54
+ startLine: lineNum,
55
+ endLine: lineNum
56
+ };
57
+ continue;
58
+ }
59
+ if (currentHunk) {
60
+ currentHunk.content += line + "\n";
61
+ if (line.startsWith("+") && !line.startsWith("+++")) {
62
+ additions++;
63
+ lineNum++;
64
+ } else if (line.startsWith("-") && !line.startsWith("---")) deletions++;
65
+ else if (!line.startsWith("\\")) lineNum++;
66
+ currentHunk.endLine = lineNum;
67
+ }
68
+ }
69
+ if (currentHunk) hunks.push(currentHunk);
70
+ files.push({
71
+ path,
72
+ additions,
73
+ deletions,
74
+ hunks
75
+ });
76
+ }
77
+ return files;
78
+ }
79
+ /**
80
+ * Infer change intent from files and commit message.
81
+ * Lightweight version without LLM. See buildIntentWithLLM for LLM version.
82
+ */
83
+ function buildIntent(files, commitMessage) {
84
+ const changeType = inferChangeType(commitMessage);
85
+ const affectedComponents = files.filter((f) => isComponentFile(f.path)).map((f) => f.path);
86
+ const expectedVisualChanges = inferVisualExpectations(files, commitMessage, changeType);
87
+ return {
88
+ summary: commitMessage.split("\n")[0],
89
+ expectedVisualChanges,
90
+ expectedA11yChanges: [],
91
+ affectedComponents,
92
+ changeType
93
+ };
94
+ }
95
+ function inferChangeType(message) {
96
+ const lower = message.toLowerCase();
97
+ if (/^fix[:(]|bug\s*fix|hotfix|patch/.test(lower)) return "bugfix";
98
+ if (/^feat[:(]|feature|add\s/.test(lower)) return "feature";
99
+ if (/^refactor[:(]|cleanup|restructure/.test(lower)) return "refactor";
100
+ if (/^style[:(]|css|theme|color|font|layout/.test(lower)) return "style";
101
+ if (/^a11y[:(]|accessibility|aria|wcag|screen.?reader|label/.test(lower)) return "a11y";
102
+ if (/^deps?[:(]|upgrade|bump|update.*dep/.test(lower)) return "deps";
103
+ return "unknown";
104
+ }
105
+ function isComponentFile(path) {
106
+ return /\.(tsx|jsx|vue|svelte|mbt)$/.test(path);
107
+ }
108
+ /**
109
+ * Infer expected visual changes from file changes (heuristic version).
110
+ */
111
+ function inferVisualExpectations(files, _commitMessage, changeType) {
112
+ const expectations = [];
113
+ if (changeType === "refactor" || changeType === "deps") {
114
+ for (const file of files) if (isComponentFile(file.path)) expectations.push({
115
+ component: file.path,
116
+ description: "No visual change expected (refactor/deps)",
117
+ confidence: .7
118
+ });
119
+ return expectations;
120
+ }
121
+ for (const file of files) {
122
+ if (!isComponentFile(file.path)) continue;
123
+ if (file.hunks.some((h) => /(?:style|css|className|color|font|margin|padding|border|background)/i.test(h.content))) expectations.push({
124
+ component: file.path,
125
+ description: `Visual style changes in ${file.path}`,
126
+ confidence: .8
127
+ });
128
+ if (file.hunks.some((h) => /(?:flex|grid|display|position|width|height|overflow)/i.test(h.content))) expectations.push({
129
+ component: file.path,
130
+ description: `Layout changes in ${file.path}`,
131
+ confidence: .8
132
+ });
133
+ if (file.hunks.some((h) => /(?:text|label|title|heading|<h[1-6]|<p|<span|innerText)/i.test(h.content))) expectations.push({
134
+ component: file.path,
135
+ description: `Content/text changes in ${file.path}`,
136
+ confidence: .6
137
+ });
138
+ }
139
+ return expectations;
140
+ }
141
+ /**
142
+ * Build Intent from diff and commit message using LLM.
143
+ */
144
+ async function buildIntentWithLLM(files, commitMessage, llm) {
145
+ const prompt = `Analyze this code change and predict its visual impact.
146
+
147
+ Commit message: ${commitMessage}
148
+
149
+ Files changed:
150
+ ${files.map((f) => `${f.path} (+${f.additions}/-${f.deletions})`).join("\n")}
151
+
152
+ Key diff hunks:
153
+ ${files.flatMap((f) => f.hunks.slice(0, 3).map((h) => `--- ${f.path}\n${h.content.slice(0, 500)}`)).join("\n\n")}
154
+
155
+ Respond in JSON:
156
+ {
157
+ "summary": "one-line summary of the change",
158
+ "changeType": "feature|bugfix|refactor|style|deps|unknown",
159
+ "expectedVisualChanges": [
160
+ { "component": "file path", "description": "what visual change is expected", "confidence": 0.0-1.0 }
161
+ ],
162
+ "affectedComponents": ["list of component file paths"]
163
+ }`;
164
+ const response = await llm.complete(prompt);
165
+ try {
166
+ const parsed = JSON.parse(response);
167
+ return {
168
+ summary: parsed.summary ?? commitMessage,
169
+ changeType: parsed.changeType ?? "unknown",
170
+ expectedVisualChanges: parsed.expectedVisualChanges ?? [],
171
+ expectedA11yChanges: parsed.expectedA11yChanges ?? [],
172
+ affectedComponents: parsed.affectedComponents ?? []
173
+ };
174
+ } catch {
175
+ return buildIntent(files, commitMessage);
176
+ }
177
+ }
178
+ /**
179
+ * Build a reasoning prompt that validates VRT diff against Intent.
180
+ */
181
+ function buildReasoningPrompt(diff, intent) {
182
+ const matchingExpectations = intent.expectedVisualChanges.filter((e) => diff.snapshot.testTitle.includes(e.component) || e.component.includes(diff.snapshot.testTitle));
183
+ return `You are a visual regression test reviewer.
184
+
185
+ ## Change Intent
186
+ Summary: ${intent.summary}
187
+ Type: ${intent.changeType}
188
+ Expected visual changes:
189
+ ${intent.expectedVisualChanges.map((e) => `- ${e.component}: ${e.description} (confidence: ${e.confidence})`).join("\n")}
190
+
191
+ ## Visual Diff Detected
192
+ Test: ${diff.snapshot.testTitle}
193
+ Project: ${diff.snapshot.projectName}
194
+ Diff ratio: ${(diff.diffRatio * 100).toFixed(2)}%
195
+ Diff pixels: ${diff.diffPixels} / ${diff.totalPixels}
196
+ Diff regions: ${diff.regions.length} region(s)
197
+ ${diff.regions.map((r) => ` - (${r.x},${r.y}) ${r.width}x${r.height}: ${r.diffPixelCount}px`).join("\n")}
198
+
199
+ ## Matching Expectations
200
+ ${matchingExpectations.length > 0 ? matchingExpectations.map((e) => `- ${e.description}`).join("\n") : "None found"}
201
+
202
+ ## Task
203
+ Decide: should this visual diff be APPROVED (matches intent), REJECTED (unexpected regression), or ESCALATED (uncertain, needs human review)?
204
+
205
+ Respond in JSON:
206
+ {
207
+ "decision": "approve|reject|escalate",
208
+ "reasoning": "explanation",
209
+ "confidence": 0.0-1.0
210
+ }`;
211
+ }
212
+ //#endregion
213
+ export { buildIntent, buildIntentWithLLM, buildReasoningPrompt, extractDiffSemantics, parseDiff };
@@ -0,0 +1,87 @@
1
+ import { LLMProvider } from "./intent.mjs";
2
+
3
+ //#region src/llm-client.d.ts
4
+ interface LLMClientOptions {
5
+ /** Whether vision support is needed */
6
+ vision?: boolean;
7
+ /** Max tokens */
8
+ maxTokens?: number;
9
+ /** Specific provider */
10
+ provider?: "anthropic" | "gemini" | "openrouter";
11
+ /** Specific model */
12
+ model?: string;
13
+ /**
14
+ * When `false`, factories return `null` instead of throwing
15
+ * `VrtConfigError` if the required API key is missing. Default: `true`.
16
+ */
17
+ throwIfMissing?: boolean;
18
+ }
19
+ interface ImageContent {
20
+ type: "image";
21
+ base64: string;
22
+ mimeType?: string;
23
+ }
24
+ interface TextContent {
25
+ type: "text";
26
+ text: string;
27
+ }
28
+ type MessageContent = string | Array<TextContent | ImageContent>;
29
+ interface LLMResponse {
30
+ content: string;
31
+ model: string;
32
+ provider: string;
33
+ promptTokens: number;
34
+ completionTokens: number;
35
+ costUsd: number;
36
+ latencyMs: number;
37
+ }
38
+ interface UnifiedLLMClient {
39
+ /** Text only (backwards-compatible) */
40
+ complete(prompt: string): Promise<string>;
41
+ /** Text + images */
42
+ completeWithImages(content: MessageContent, options?: {
43
+ maxTokens?: number;
44
+ }): Promise<LLMResponse>;
45
+ /** VRT diff analysis: pass heatmap + text report together */
46
+ analyzeDiff(options: {
47
+ heatmapBase64?: string;
48
+ baselineBase64?: string;
49
+ currentBase64?: string;
50
+ textReport: string;
51
+ prompt?: string;
52
+ maxTokens?: number;
53
+ }): Promise<LLMResponse>;
54
+ provider: string;
55
+ model: string;
56
+ }
57
+ type LLMProviderName = "gemini" | "anthropic" | "openrouter";
58
+ /**
59
+ * Create a unified LLM client.
60
+ *
61
+ * Provider is set via `VRT_LLM_PROVIDER` env var (default: `gemini`).
62
+ *
63
+ * Throws `VrtConfigError` when the resolved provider has no API key
64
+ * (`code: "MISSING_KEY"`) or the provider value is unknown
65
+ * (`code: "INVALID_PROVIDER"`). Pass `{ throwIfMissing: false }` for
66
+ * legacy `T | null` return.
67
+ */
68
+ declare function createUnifiedLLMClient(options?: LLMClientOptions): UnifiedLLMClient | null;
69
+ interface CreateLLMProviderOptions {
70
+ /**
71
+ * When `false`, returns `null` instead of throwing `VrtConfigError`
72
+ * if no provider has an API key. Default: `true`.
73
+ */
74
+ throwIfMissing?: boolean;
75
+ }
76
+ /**
77
+ * Backwards-compatible: returns the existing `LLMProvider` interface.
78
+ * Uses the provider specified by `VRT_LLM_PROVIDER`. Falls back to
79
+ * other providers if the requested key is missing.
80
+ *
81
+ * Throws `VrtConfigError` (`code: "NO_PROVIDER_AVAILABLE"`) when no
82
+ * provider in the fallback chain has an API key. Pass
83
+ * `{ throwIfMissing: false }` for the legacy `T | null` return.
84
+ */
85
+ declare function createLLMProvider(options?: CreateLLMProviderOptions): LLMProvider | null;
86
+ //#endregion
87
+ export { CreateLLMProviderOptions, ImageContent, LLMClientOptions, LLMProviderName, LLMResponse, MessageContent, TextContent, UnifiedLLMClient, createLLMProvider, createUnifiedLLMClient };