@mizchi/vlmkit-ai 0.7.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.
@@ -1,245 +0,0 @@
1
- /**
2
- * Image generation client (OpenAI gpt-image-2).
3
- *
4
- * Mirrors the vlm-client / llm-client split: a small registry of known
5
- * models, pure builders + parsers that can be unit-tested without a network
6
- * call, and a `createImageGenClient` factory that wires them to the actual
7
- * OpenAI Images API.
8
- *
9
- * Used by:
10
- * - `design-runs/game-assets-20260520/run-gpt-image-2.mjs` (dogfood driver)
11
- * - vlmkit-markup pipelines that need to synthesize reference imagery
12
- * - downstream callers in `src/cli/workflow/` (added separately)
13
- *
14
- * The OpenAI Images endpoint returns base64-encoded PNGs by default; we
15
- * surface them as `Uint8Array`. Reference-image inputs (edit mode via
16
- * `/v1/images/edits`) are intentionally out of scope here; add a separate
17
- * `editImage` method if/when a caller needs it.
18
- */
19
- import { VrtConfigError } from "./errors.ts";
20
-
21
- // ---- Types ----
22
-
23
- export type ImageGenSize = "1024x1024" | "1024x1536" | "1536x1024" | "auto";
24
- export type ImageGenQuality = "low" | "medium" | "high" | "auto";
25
- export type ImageGenOutputFormat = "png" | "jpeg" | "webp";
26
- export type ImageGenBackground = "opaque" | "transparent" | "auto";
27
-
28
- export interface ImageGenModel {
29
- id: string;
30
- provider: "openai";
31
- /** USD per 1M tokens (matches OpenAI's published pricing table). */
32
- costPer1MInputTextTokens: number;
33
- costPer1MInputImageTokens: number;
34
- costPer1MOutputImageTokens: number;
35
- }
36
-
37
- export interface ImageGenRequest {
38
- prompt: string;
39
- size?: ImageGenSize;
40
- quality?: ImageGenQuality;
41
- n?: number;
42
- outputFormat?: ImageGenOutputFormat;
43
- background?: ImageGenBackground;
44
- }
45
-
46
- export interface ImageGenUsage {
47
- inputTextTokens: number;
48
- inputImageTokens: number;
49
- outputTokens: number;
50
- }
51
-
52
- export interface ImageGenResponse {
53
- model: string;
54
- images: Uint8Array[];
55
- usage: ImageGenUsage | null;
56
- costUsd: number;
57
- latencyMs: number;
58
- }
59
-
60
- export interface ImageGenRequestBody {
61
- model: string;
62
- prompt: string;
63
- size: ImageGenSize;
64
- quality: ImageGenQuality;
65
- n: number;
66
- output_format: ImageGenOutputFormat;
67
- background: ImageGenBackground;
68
- }
69
-
70
- export interface ImageGenClient {
71
- model: ImageGenModel;
72
- generate(req: ImageGenRequest): Promise<ImageGenResponse>;
73
- }
74
-
75
- // ---- Registry ----
76
-
77
- const IMAGE_GEN_MODELS: ImageGenModel[] = [
78
- {
79
- id: "gpt-image-2",
80
- provider: "openai",
81
- costPer1MInputTextTokens: 5,
82
- costPer1MInputImageTokens: 8,
83
- costPer1MOutputImageTokens: 30,
84
- },
85
- {
86
- id: "gpt-image-2-2026-04-21",
87
- provider: "openai",
88
- costPer1MInputTextTokens: 5,
89
- costPer1MInputImageTokens: 8,
90
- costPer1MOutputImageTokens: 30,
91
- },
92
- ];
93
-
94
- const VALID_SIZES: ReadonlySet<ImageGenSize> = new Set(["1024x1024", "1024x1536", "1536x1024", "auto"]);
95
- const VALID_QUALITIES: ReadonlySet<ImageGenQuality> = new Set(["low", "medium", "high", "auto"]);
96
- const VALID_OUTPUT_FORMATS: ReadonlySet<ImageGenOutputFormat> = new Set(["png", "jpeg", "webp"]);
97
- const VALID_BACKGROUNDS: ReadonlySet<ImageGenBackground> = new Set(["opaque", "transparent", "auto"]);
98
-
99
- export function listImageGenModels(): ImageGenModel[] {
100
- return IMAGE_GEN_MODELS.map((m) => ({ ...m }));
101
- }
102
-
103
- export function resolveImageGenModel(id: string): ImageGenModel {
104
- const hit = IMAGE_GEN_MODELS.find((m) => m.id === id);
105
- if (!hit) {
106
- throw new VrtConfigError(
107
- "INVALID_MODEL",
108
- `Unknown image generation model: "${id}". Known: ${IMAGE_GEN_MODELS.map((m) => m.id).join(", ")}`,
109
- );
110
- }
111
- return { ...hit };
112
- }
113
-
114
- // ---- Pure builders / parsers ----
115
-
116
- export function buildGenerationBody(model: ImageGenModel, req: ImageGenRequest): ImageGenRequestBody {
117
- if (!req.prompt || !req.prompt.trim()) {
118
- throw new VrtConfigError("INVALID_REQUEST", "image-gen: prompt must be a non-empty string");
119
- }
120
- const size: ImageGenSize = req.size ?? "1024x1024";
121
- const quality: ImageGenQuality = req.quality ?? "medium";
122
- const outputFormat: ImageGenOutputFormat = req.outputFormat ?? "png";
123
- const background: ImageGenBackground = req.background ?? "opaque";
124
- const n = req.n ?? 1;
125
- if (!VALID_SIZES.has(size)) {
126
- throw new VrtConfigError("INVALID_REQUEST", `image-gen: invalid size "${size}"`);
127
- }
128
- if (!VALID_QUALITIES.has(quality)) {
129
- throw new VrtConfigError("INVALID_REQUEST", `image-gen: invalid quality "${quality}"`);
130
- }
131
- if (!VALID_OUTPUT_FORMATS.has(outputFormat)) {
132
- throw new VrtConfigError("INVALID_REQUEST", `image-gen: invalid output_format "${outputFormat}"`);
133
- }
134
- if (!VALID_BACKGROUNDS.has(background)) {
135
- throw new VrtConfigError("INVALID_REQUEST", `image-gen: invalid background "${background}"`);
136
- }
137
- if (!Number.isInteger(n) || n <= 0) {
138
- throw new VrtConfigError("INVALID_REQUEST", `image-gen: n must be a positive integer, got ${n}`);
139
- }
140
- return {
141
- model: model.id,
142
- prompt: req.prompt,
143
- size,
144
- quality,
145
- n,
146
- output_format: outputFormat,
147
- background,
148
- };
149
- }
150
-
151
- interface RawGenerationResponse {
152
- data?: Array<{ b64_json?: string; url?: string }>;
153
- usage?: {
154
- input_tokens?: number;
155
- output_tokens?: number;
156
- total_tokens?: number;
157
- input_tokens_details?: { text_tokens?: number; image_tokens?: number };
158
- };
159
- }
160
-
161
- export interface ParsedGeneration {
162
- images: Uint8Array[];
163
- usage: ImageGenUsage | null;
164
- }
165
-
166
- export function parseGenerationResponse(json: RawGenerationResponse): ParsedGeneration {
167
- const images: Uint8Array[] = [];
168
- for (const entry of json.data ?? []) {
169
- if (!entry || typeof entry.b64_json !== "string") continue;
170
- images.push(new Uint8Array(Buffer.from(entry.b64_json, "base64")));
171
- }
172
- const u = json.usage;
173
- const usage: ImageGenUsage | null = u
174
- ? {
175
- inputTextTokens: u.input_tokens_details?.text_tokens ?? u.input_tokens ?? 0,
176
- inputImageTokens: u.input_tokens_details?.image_tokens ?? 0,
177
- outputTokens: u.output_tokens ?? 0,
178
- }
179
- : null;
180
- return { images, usage };
181
- }
182
-
183
- export function estimateImageGenCost(model: ImageGenModel, usage: ImageGenUsage | null): number {
184
- if (!usage) return 0;
185
- const cost = (usage.inputTextTokens * model.costPer1MInputTextTokens
186
- + usage.inputImageTokens * model.costPer1MInputImageTokens
187
- + usage.outputTokens * model.costPer1MOutputImageTokens) / 1_000_000;
188
- return Math.round(cost * 1_000_000) / 1_000_000;
189
- }
190
-
191
- // ---- Client factory ----
192
-
193
- export interface CreateImageGenClientOptions {
194
- apiKey?: string;
195
- throwIfMissing?: boolean;
196
- /** Override the API base URL (for tests / proxies). */
197
- baseUrl?: string;
198
- }
199
-
200
- export function createImageGenClient(
201
- modelOrId: ImageGenModel | string,
202
- options?: CreateImageGenClientOptions,
203
- ): ImageGenClient {
204
- const model = typeof modelOrId === "string" ? resolveImageGenModel(modelOrId) : modelOrId;
205
- const throwIfMissing = options?.throwIfMissing ?? true;
206
- const apiKey = options?.apiKey ?? process.env.OPENAI_API_KEY;
207
- if (!apiKey && throwIfMissing) {
208
- throw new VrtConfigError("MISSING_KEY", `OPENAI_API_KEY is required for ${model.id}`);
209
- }
210
- const baseUrl = options?.baseUrl ?? "https://api.openai.com";
211
- return {
212
- model,
213
- async generate(req: ImageGenRequest): Promise<ImageGenResponse> {
214
- const body = buildGenerationBody(model, req);
215
- const started = Date.now();
216
- const res = await fetch(`${baseUrl}/v1/images/generations`, {
217
- method: "POST",
218
- headers: {
219
- Authorization: `Bearer ${apiKey ?? ""}`,
220
- "Content-Type": "application/json",
221
- },
222
- body: JSON.stringify(body),
223
- });
224
- const text = await res.text();
225
- let json: RawGenerationResponse & { error?: { message?: string } };
226
- try {
227
- json = JSON.parse(text);
228
- } catch {
229
- throw new Error(`image-gen: non-JSON response from OpenAI (status ${res.status}): ${text.slice(0, 200)}`);
230
- }
231
- if (!res.ok) {
232
- const message = json.error?.message ?? text.slice(0, 200);
233
- throw new Error(`image-gen ${model.id} failed (${res.status}): ${message}`);
234
- }
235
- const parsed = parseGenerationResponse(json);
236
- return {
237
- model: model.id,
238
- images: parsed.images,
239
- usage: parsed.usage,
240
- costUsd: estimateImageGenCost(model, parsed.usage),
241
- latencyMs: Date.now() - started,
242
- };
243
- },
244
- };
245
- }
package/src/index.ts DELETED
@@ -1,89 +0,0 @@
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
- // ---- Image generation clients ----
42
- export {
43
- buildGenerationBody,
44
- createImageGenClient,
45
- estimateImageGenCost,
46
- listImageGenModels,
47
- parseGenerationResponse,
48
- resolveImageGenModel,
49
- type CreateImageGenClientOptions,
50
- type ImageGenBackground,
51
- type ImageGenClient,
52
- type ImageGenModel,
53
- type ImageGenOutputFormat,
54
- type ImageGenQuality,
55
- type ImageGenRequest,
56
- type ImageGenRequestBody,
57
- type ImageGenResponse,
58
- type ImageGenSize,
59
- type ImageGenUsage,
60
- type ParsedGeneration,
61
- } from "./image-gen-client.ts";
62
-
63
- // ---- Reasoning ----
64
- export {
65
- createReasoningPipeline,
66
- type ReasoningPipeline,
67
- type PipelineConfig,
68
- type AnalyzeOptions,
69
- type StructuredDiffReport,
70
- type VisualChange,
71
- type CssFix,
72
- type FixSuggestion,
73
- } from "./reasoning-pipeline.ts";
74
- export {
75
- reasonAboutChanges,
76
- type ReasoningChain,
77
- type ActualChange,
78
- type ExpectationMapping,
79
- } from "./reasoning.ts";
80
-
81
- // ---- Intent / diff extraction ----
82
- export {
83
- buildIntent,
84
- buildIntentWithLLM,
85
- buildReasoningPrompt,
86
- extractDiffSemantics,
87
- parseDiff,
88
- type LLMProvider,
89
- } from "./intent.ts";
package/src/intent.ts DELETED
@@ -1,322 +0,0 @@
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
- }